summaryrefslogtreecommitdiff
path: root/src/estd/io/stdio.zig
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2025-02-14 16:52:16 +0100
committerNathan Reiner <nathan@nathanreiner.xyz>2025-02-14 16:52:16 +0100
commit7407f9719be03ec1a93de5bf0af5ac536d370400 (patch)
tree87a066c20ccf492142cbe3c8730ce1fe44108a15 /src/estd/io/stdio.zig
parent40b847344481803e94e78ba2dacde8dc78636948 (diff)
parentbff7daf2d430062fc37cbf3b69fe102a5b0bad58 (diff)
Merge branch 'master' of https://gitlab.com/Jockerkat/eostreHEADmaster
Diffstat (limited to 'src/estd/io/stdio.zig')
-rw-r--r--src/estd/io/stdio.zig70
1 files changed, 70 insertions, 0 deletions
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) {}