Is there is a way of getting the backing int of a packed struct aside from using @ptrCast()
?
This should be enough:
const int = @typeInfo(PackedStruct).Struct.backing_integer.?;
I use @bitCast
for this. I’m assuming you want the backing integer, and not the backing integer type.
It’s a little trickier to obtain a pointer to the value of the packed struct as a pointer to the backing integer, but that shouldn’t matter for any packed struct which is native word sized or smaller. The packed struct is just an integer to the compiler, so the @bitCast
is just a compiler directive.
What I mean is that this:
// usize or whatever
var as_int: usize = @bitCast(pack_struct);
as_int |= some_mask;
pack_struct = @bitCast(as_int);
Is subject to the same sort of compiler optimizations as it would be without the bitcasts. So needing to modify a packed struct in-place with a pointer is not so important, since the compiler can decide to do that anyway if it’s efficient. Any mutation is going to happen in registers anyhow, so it washes out to the same thing.