diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2025-02-14 16:52:16 +0100 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2025-02-14 16:52:16 +0100 |
| commit | 7407f9719be03ec1a93de5bf0af5ac536d370400 (patch) | |
| tree | 87a066c20ccf492142cbe3c8730ce1fe44108a15 /src/estd/io | |
| parent | 40b847344481803e94e78ba2dacde8dc78636948 (diff) | |
| parent | bff7daf2d430062fc37cbf3b69fe102a5b0bad58 (diff) | |
Diffstat (limited to 'src/estd/io')
| -rw-r--r-- | src/estd/io/root.zig | 1 | ||||
| -rw-r--r-- | src/estd/io/stdio.zig | 70 |
2 files changed, 71 insertions, 0 deletions
diff --git a/src/estd/io/root.zig b/src/estd/io/root.zig new file mode 100644 index 0000000..704fdd7 --- /dev/null +++ b/src/estd/io/root.zig @@ -0,0 +1 @@ +pub const stdio = @import("stdio.zig"); diff --git a/src/estd/io/stdio.zig b/src/estd/io/stdio.zig new file mode 100644 index 0000000..d89b325 --- /dev/null +++ b/src/estd/io/stdio.zig @@ -0,0 +1,70 @@ +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`. +/// +/// Note that the returned handle is not thread-safe. +pub fn Stdout(comptime buffer_size: usize) type { + return struct { + writer: io.BufferedWriter(buffer_size, io.getStdOut()), + + const Self = @This(); + + pub const Error = Self.writer.Error; + + /// 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, .int, .float => { + try self.writer.write(mem.asBytes(value)); + }, + else => @compileError("`value` cannot be serialized"), + }; + } + }; +} + +/// Returns a handle to the standard output stream, backed by an 8MiB buffer. +/// +/// Note that the returned handle is not thread-safe. +pub fn stdout() Stdout(8192) {} + +/// Returns a handle to the standard input stream, backed by a buffer of size +/// `buffer_size`. +/// +/// Note that the returned handle is not thread-safe. +pub fn Stdin(comptime buffer_size: usize) type { + return struct { + reader: io.BufferedReader(buffer_size, io.getStdIn()), + + const Self = @This(); + + pub const Error = error{ + // TODO + } || Self.reader.Error; + + /// Tries to deserialize the type `T` from the standard input stream. + 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"), + }; + } + }; +} + +/// Returns a handle to the standard input stream, backed by an 8MiB buffer. +/// +/// Note that the returned handle is not thread-safe. +pub fn stdin() Stdin(8192) {} |