You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
use core::mem::size_of;use core::num::NonZeroU8;structFoo(u8,u16);structBar(u8,u16,NonZeroU8);fnmain(){dbg!(size_of::<Foo>());dbg!(size_of::<Option<Foo>>());dbg!(size_of::<Bar>());dbg!(size_of::<Option<Bar>>());}
size_of::<Foo>() returns 4 as expected. size_of::<Option<Foo>>() returns 6, indicating that the unused padding byte is not being used to store the tag for the Option. (playground)
However, by adding a field that is NonZero*, the compiler is able to take advantage of the unused bit. This, of course, only works with one bit, not the potential eight.
In this example, the size of Bar is the same as Foo, but the situation that I ran across this with requires an increase in size of the struct to decrease the size of Option<CompoundStruct>; needless to say this is a tradeoff I don't want to make.
Presumably the compiler could do some magic here to take advantage of the niche values.
The text was updated successfully, but these errors were encountered:
The problem with this optimization is that you can no longer overwrite padding bytes when writing to a mutable reference, because doing so could potentially mutate the discriminant, leading to an invalid state.
I thought the compiler would (or should?) optimize copying structs like Foo to a single instruction that copies 4 bytes (which include the padding bytes), however looks like I'm wrong (#63159 is also kinda related to this). C however behaves like I expected
(Playground)
Output:
size_of::<Foo>()
returns 4 as expected.size_of::<Option<Foo>>()
returns 6, indicating that the unused padding byte is not being used to store the tag for theOption
. (playground)However, by adding a field that is
NonZero*
, the compiler is able to take advantage of the unused bit. This, of course, only works with one bit, not the potential eight.In this example, the size of
Bar
is the same asFoo
, but the situation that I ran across this with requires an increase in size of the struct to decrease the size ofOption<CompoundStruct>
; needless to say this is a tradeoff I don't want to make.Presumably the compiler could do some magic here to take advantage of the niche values.
The text was updated successfully, but these errors were encountered: