-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add @intFromStruct
and @structFromInt
for converting between a packed struct and its integer representation
#18882
Comments
Is there any reason to limit this to structs as opposed to packed unions? And in that case, how about |
The same question could be asked about Also, reminder that |
It seems to me that the motivating logic here only applies to one direction, namely casting from packed struct/enum/whatever to an integer. I see no advantage over bitcast for casting an integer to a packed struct/enum/whatever as the destination type is still required. In light of this realization I would counter-propose a single For the other direction I propose that |
@ifreund Having separate builtins for To me that seems like the fitting null hypothesis for Zig to start out with. |
If you compare and contrast this, given @ifreund's solution, with #10710, the goal of both is to reduce convolution. The arguement for
|
Regarding @ifreund's proposal, I agree with But not with removing |
I propose adding a function to std.mem for this, along the lines of asBytes fn BackingIntPtr(comptime T: type) type {
const BackingT = @typeInfo(std.meta.Child(T)).Struct.backing_integer orelse @compileError("Not a pointer to packed struct");
return CopyPtrAttrs(T, .One, BackingT);
}
pub fn asBackingInteger(packed_struct: anytype) BackingIntPtr(@TypeOf(packed_struct)) {
return @ptrCast(packed_struct);
} The use case as I see it is to be able to operate on the memory of the packed struct as a single value, like for setting whole registers(e.g. MicroZig mmio) or clearing/masking the value, and that would cover it without introducing unnecessary builtins. |
@ifreund
|
@bitCast
already works to do this conversion, however it requires sometimes duplicating the destination integer type, which can lead to bugs if the packed struct integer type changes, or if the packed struct changes to an integer or enum or other@bitCast
eligible type.The exact same reasoning is why we have
@enumFromInt
and@intFromEnum
for enums.Generally, the more specific conversion is preferred, because it is more resilient to code churn.
The text was updated successfully, but these errors were encountered: