From bff7daf2d430062fc37cbf3b69fe102a5b0bad58 Mon Sep 17 00:00:00 2001 From: Alexander Rolley Date: Fri, 14 Feb 2025 15:12:07 +0100 Subject: Implement (de)serialize for bool, int, float. --- src/estd/io/stdio.zig | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) (limited to 'src') 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"), }; } -- cgit v1.2.3-70-g09d2