It seems that @ptrCast
doesn’t see through reading thus requires the use of @as()
in this case.
test {
var x: [4]u8 = "allo".*;
const y: u32 = @ptrCast(x).*;
_ = y;
}
Or is it intentionally omitted from inference?
It seems that @ptrCast
doesn’t see through reading thus requires the use of @as()
in this case.
test {
var x: [4]u8 = "allo".*;
const y: u32 = @ptrCast(x).*;
_ = y;
}
Or is it intentionally omitted from inference?
I don’t believe this is possible as there is an ambiguity. This @ptrCast
could be interpreted in 2 ways:
x
to *u8
, read the 'a'
character and enlarge it implicitly to u32
;x
to *u32*
, read the 4 bytes as an u32
integer.For both of these, there are better ways to do it:
x[0]
;std.mem.bytesAsValue(u32, x)
(with maybe std.mem.bigToNative
to convert endianness if necessary).In general, there’s also possible alignment issues here too.
There’s std.mem.readIntNative
/readIntLittle
/readIntBig
for this.
const y = std.mem.readIntNative(u32, &x);
Yep, and as you can see in the implementation:
pub fn readIntNative(comptime T: type, bytes: *const [@divExact(@typeInfo(T).Int.bits, 8)]u8) T {
return @as(*align(1) const T, @ptrCast(bytes)).*;
}
It’s just an aligned cast.