diff options
| author | Alexander Rolley <arolley35@gmail.com> | 2025-02-14 15:12:07 +0100 |
|---|---|---|
| committer | Alexander Rolley <arolley35@gmail.com> | 2025-02-14 15:12:07 +0100 |
| commit | bff7daf2d430062fc37cbf3b69fe102a5b0bad58 (patch) | |
| tree | d0131e6876cd080c9a1aab45f2a9b54264c5242e /src/estd | |
| parent | 080bb49438fe770164382e2ac109dd8283600b16 (diff) | |
Implement (de)serialize for bool, int, float.
Diffstat (limited to 'src/estd')
| -rw-r--r-- | src/estd/io/stdio.zig | 27 |
1 files changed, 16 insertions, 11 deletions
diff --git a/src/estd/io/stdio.zig b/src/estd/io/stdio.zig index 8b5924e..d89b325 100644 --- a/src/estd/io/stdio.zig +++ b/src/estd/io/stdio.zig @@ -1,5 +1,6 @@ const std = @import("std"); const io = std.io; +const mem = std.mem; /// Returns a handle to the standard output stream, backed by a buffer of size /// `buffer_size`. @@ -13,18 +14,14 @@ pub fn Stdout(comptime buffer_size: usize) type { pub const Error = Self.writer.Error; - /// Tries to serialize the type `T` to the standard output stream. - pub fn serialize(self: *Self, comptime T: type) Error!void { - return switch (@typeInfo(T)) { + /// Tries to serialize the `value` to the standard output stream. + pub fn serialize(self: *Self, value: anytype) Error!void { + return switch (@typeInfo(@TypeOf(value))) { .void => {}, - .bool => { - if (T) { - try self.writer.write("true"); - } else { - try self.writer.write("false"); - } + .bool, .int, .float => { + try self.writer.write(mem.asBytes(value)); }, - else => @compileError("`T` cannot be serialized"), + else => @compileError("`value` cannot be serialized"), }; } }; @@ -50,9 +47,17 @@ pub fn Stdin(comptime buffer_size: usize) type { } || Self.reader.Error; /// Tries to deserialize the type `T` from the standard input stream. - pub fn deserialize(comptime T: type) Error!T { + pub fn deserialize(self: *Self, comptime T: type) Error!T { return switch (@typeInfo(T)) { .void => {}, + .bool, .int, .float => { + const size = @sizeOf(T); + const buffer: [size]u8 = 0; + + try self.reader.read(buffer); + + return mem.bytesToValue(T, buffer); + }, else => @compileError("`T` cannot be deserialized"), }; } |