summaryrefslogtreecommitdiff
path: root/src/estd/io/stdio.zig
blob: 8b5924e4f97346ba0d684d5b83862e773ddf6d85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const std = @import("std");
const io = std.io;

/// 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 type `T` to the standard output stream.
		pub fn serialize(self: *Self, comptime T: type) Error!void {
			return switch (@typeInfo(T)) {
				.void => {},
				.bool => {
					if (T) {
						try self.writer.write("true");
					} else {
						try self.writer.write("false");
					}
				},
				else => @compileError("`T` 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(comptime T: type) Error!T {
			return switch (@typeInfo(T)) {
				.void => {},
				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) {}