Function bytesAsValue [src]
Given a pointer to an array of bytes, returns a pointer to a value of the specified type
backed by those bytes, preserving pointer attributes.
Prototype
pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes))
Parameters
T: type
Example
test bytesAsValue {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);
var codeface_bytes: [4]u8 = switch (native_endian) {
.big => "\xC0\xDE\xFA\xCE",
.little => "\xCE\xFA\xDE\xC0",
}.*;
const codeface = bytesAsValue(u32, &codeface_bytes);
try testing.expect(codeface.* == 0xC0DEFACE);
codeface.* = 0;
for (codeface_bytes) |b|
try testing.expect(b == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
const inst_bytes = switch (native_endian) {
.little => "\xBE\xEF\xDE\xA1",
.big => "\xA1\xDE\xEF\xBE",
};
const inst2 = bytesAsValue(S, inst_bytes);
try testing.expect(std.meta.eql(inst, inst2.*));
}
Source
pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes)) {
return @ptrCast(bytes);
}