diff --git a/src/coral/bytes.zig b/src/coral/bytes.zig index 4e49575..d47809f 100644 --- a/src/coral/bytes.zig +++ b/src/coral/bytes.zig @@ -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}); @@ -139,6 +139,47 @@ pub fn printFormatted(buffer: [:0]u8, comptime format: []const u8, args: anytype 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)) { return .{ .bytes = switch (@typeInfo(@TypeOf(ptr)).pointer.size) {