authorgravatar for johnnymarler@gmail.comJonathan Marler <johnnymarler@gmail.com> 2022-11-16 23:41:54-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-01-09 14:18:01-07:00
log9f215318b8967940a8fc2385de9bc0e3faf02e7e
treed084f0db90dcb4744cc70325a0dbc5ae8b836b05
parent91b8d9e370f0dfc62f7bf7297ce9a7e22bae9f67

packed struct fix example and clarify least to most significant ordering

The packed struct example was mistakenly applying endianness where it shouldn't have been. This wasn't being caught because we don't currently test the examples on Big-endian systems. I updated the test to remove the endianness where it didn't apply, and added a new part of the test to demonstrate when it would apply.

1 files changed, 10 insertions(+), 7 deletions(-)

doc/langref.html.in+10-7
...@@ -3277,7 +3277,7 @@ test "default struct initialization fields" {...@@ -3277,7 +3277,7 @@ test "default struct initialization fields" {
3277 Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:3277 Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:
3278 </p>3278 </p>
3279 <ul>3279 <ul>
3280 <li>Fields remain in the order declared.</li>3280 <li>Fields remain in the order declared, least to most significant.</li>
3281 <li>There is no padding between fields.</li>3281 <li>There is no padding between fields.</li>
3282 <li>Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer3282 <li>Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer
3283 than 8 bits will still use 1 byte of memory, in packed structs, they use3283 than 8 bits will still use 1 byte of memory, in packed structs, they use
...@@ -3320,16 +3320,19 @@ fn doTheTest() !void {...@@ -3320,16 +3320,19 @@ fn doTheTest() !void {
3320 try expect(@sizeOf(Divided) == 2);3320 try expect(@sizeOf(Divided) == 2);
3321 var full = Full{ .number = 0x1234 };3321 var full = Full{ .number = 0x1234 };
3322 var divided = @bitCast(Divided, full);3322 var divided = @bitCast(Divided, full);
3323 try expect(divided.half1 == 0x34);
3324 try expect(divided.quarter3 == 0x2);
3325 try expect(divided.quarter4 == 0x1);
3326
3327 var ordered = @bitCast([2]u8, full);
3323 switch (native_endian) {3328 switch (native_endian) {
3324 .Big => {3329 .Big => {
3325 try expect(divided.half1 == 0x12);3330 try expect(ordered[0] == 0x12);
3326 try expect(divided.quarter3 == 0x3);3331 try expect(ordered[1] == 0x34);
3327 try expect(divided.quarter4 == 0x4);
3328 },3332 },
3329 .Little => {3333 .Little => {
3330 try expect(divided.half1 == 0x34);3334 try expect(ordered[0] == 0x34);
3331 try expect(divided.quarter3 == 0x2);3335 try expect(ordered[1] == 0x12);
3332 try expect(divided.quarter4 == 0x1);
3333 },3336 },
3334 }3337 }
3335}3338}