Add endianness-specific reading functions.
This commit is contained in:
parent
3ddf351a08
commit
070a35f694
@ -21,7 +21,7 @@ pub const ReadOnlySpan = struct {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const ReadWriteError = error{IncompleteWrite};
|
pub const ReadWriteError = error{ IncompleteRead, IncompleteWrite };
|
||||||
|
|
||||||
pub const Readable = coral.Callable(usize, &.{[]u8});
|
pub const Readable = coral.Callable(usize, &.{[]u8});
|
||||||
|
|
||||||
@ -139,6 +139,47 @@ pub fn printFormatted(buffer: [:0]u8, comptime format: []const u8, args: anytype
|
|||||||
return buffer[0..len :0];
|
return buffer[0..len :0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn readBig(input: Readable, comptime T: type) ReadWriteError!T {
|
||||||
|
var buffer: [@sizeOf(T)]u8 align(@alignOf(T)) = undefined;
|
||||||
|
|
||||||
|
if (input.call(.{&buffer}) != buffer.len) {
|
||||||
|
return error.IncompleteRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (builtin.cpu.arch.endian()) {
|
||||||
|
.big => {},
|
||||||
|
|
||||||
|
.little => {
|
||||||
|
std.mem.byteSwapAllFields(T, @ptrCast(&buffer));
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return std.mem.bytesToValue(T, &buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn readLittle(input: Readable, comptime T: type) ReadWriteError!T {
|
||||||
|
var buffer: [@sizeOf(T)]u8 = undefined;
|
||||||
|
|
||||||
|
if (input.call(.{&buffer}) != buffer.len) {
|
||||||
|
return error.IncompleteRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (builtin.cpu.arch.endian()) {
|
||||||
|
.big => {
|
||||||
|
std.mem.byteSwapAllFields(T, &buffer);
|
||||||
|
},
|
||||||
|
|
||||||
|
.little => {},
|
||||||
|
}
|
||||||
|
|
||||||
|
return std.mem.bytesToValue(T, &buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const readNative = switch (builtin.cpu.arch.endian()) {
|
||||||
|
.little => readLittle,
|
||||||
|
.big => readBig,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
|
pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
|
||||||
return .{
|
return .{
|
||||||
.bytes = switch (@typeInfo(@TypeOf(ptr)).pointer.size) {
|
.bytes = switch (@typeInfo(@TypeOf(ptr)).pointer.size) {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user