commit 58d9004cea5f8aa73c76382cd21e1c88b1bc21e1 (tree)
parent a09a5ad574b8e85480645e0920d6cf4c7e850748
Author: Jonathan Marler <johnnymarler@gmail.com>
Date: Wed, 16 Nov 2022 23:41:54 -0700
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.
Diffstat:
1 file changed, 10 insertions(+), 7 deletions(-)
diff --git a/doc/langref.html.in b/doc/langref.html.in
@@ -3277,7 +3277,7 @@ test "default struct initialization fields" {
Unlike normal structs, {#syntax#}packed{#endsyntax#} structs have guaranteed in-memory layout:
</p>
<ul>
- <li>Fields remain in the order declared.</li>
+ <li>Fields remain in the order declared, least to most significant.</li>
<li>There is no padding between fields.</li>
<li>Zig supports arbitrary width {#link|Integers#} and although normally, integers with fewer
than 8 bits will still use 1 byte of memory, in packed structs, they use
@@ -3320,16 +3320,19 @@ fn doTheTest() !void {
try expect(@sizeOf(Divided) == 2);
var full = Full{ .number = 0x1234 };
var divided = @bitCast(Divided, full);
+ try expect(divided.half1 == 0x34);
+ try expect(divided.quarter3 == 0x2);
+ try expect(divided.quarter4 == 0x1);
+
+ var ordered = @bitCast([2]u8, full);
switch (native_endian) {
.Big => {
- try expect(divided.half1 == 0x12);
- try expect(divided.quarter3 == 0x3);
- try expect(divided.quarter4 == 0x4);
+ try expect(ordered[0] == 0x12);
+ try expect(ordered[1] == 0x34);
},
.Little => {
- try expect(divided.half1 == 0x34);
- try expect(divided.quarter3 == 0x2);
- try expect(divided.quarter4 == 0x1);
+ try expect(ordered[0] == 0x34);
+ try expect(ordered[1] == 0x12);
},
}
}