| 1 | const std = @import("std"); |
| 2 | const builtin = @import("builtin"); |
| 3 | const assert = std.debug.assert; |
| 4 | const expectEqual = std.testing.expectEqual; |
| 5 | const native_endian = builtin.cpu.arch.endian(); |
| 6 | |
| 7 | test "packed struct explicit backing integer" { |
| 8 | if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO |
| 9 | if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO |
| 10 | |
| 11 | const S1 = packed struct { a: u8, b: u8, c: u8 }; |
| 12 | |
| 13 | const S2 = packed struct(i24) { d: u8, e: u8, f: u8 }; |
| 14 | |
| 15 | const S3 = packed struct { x: S1, y: S2 }; |
| 16 | const S3Padded = packed struct(u64) { s3: S3, pad: u16 }; |
| 17 | |
| 18 | try expectEqual(48, @bitSizeOf(S3)); |
| 19 | try expectEqual(@sizeOf(u48), @sizeOf(S3)); |
| 20 | |
| 21 | try expectEqual(3, @offsetOf(S3, "y")); |
| 22 | try expectEqual(24, @bitOffsetOf(S3, "y")); |
| 23 | |
| 24 | if (native_endian == .little) { |
| 25 | const s3 = @as(S3Padded, @bitCast(@as(u64, 0xe952d5c71ff4))).s3; |
| 26 | try expectEqual(@as(u8, 0xf4), s3.x.a); |
| 27 | try expectEqual(@as(u8, 0x1f), s3.x.b); |
| 28 | try expectEqual(@as(u8, 0xc7), s3.x.c); |
| 29 | try expectEqual(@as(u8, 0xd5), s3.y.d); |
| 30 | try expectEqual(@as(u8, 0x52), s3.y.e); |
| 31 | try expectEqual(@as(u8, 0xe9), s3.y.f); |
| 32 | } |
| 33 | |
| 34 | const S4 = packed struct { a: i32, b: i8 }; |
| 35 | const S5 = packed struct(u80) { a: i32, b: i8, c: S4 }; |
| 36 | const S6 = packed struct(i80) { a: i32, b: S4, c: i8 }; |
| 37 | |
| 38 | const expectedBitSize = 80; |
| 39 | const expectedByteSize = @sizeOf(u80); |
| 40 | try expectEqual(expectedBitSize, @bitSizeOf(S5)); |
| 41 | try expectEqual(expectedByteSize, @sizeOf(S5)); |
| 42 | try expectEqual(expectedBitSize, @bitSizeOf(S6)); |
| 43 | try expectEqual(expectedByteSize, @sizeOf(S6)); |
| 44 | |
| 45 | try expectEqual(5, @offsetOf(S5, "c")); |
| 46 | try expectEqual(40, @bitOffsetOf(S5, "c")); |
| 47 | try expectEqual(9, @offsetOf(S6, "c")); |
| 48 | try expectEqual(72, @bitOffsetOf(S6, "c")); |
| 49 | } |