diff --git a/src/libuv/Tty.zig b/src/libuv/Tty.zig index 0887a0503..7c4b335ae 100644 --- a/src/libuv/Tty.zig +++ b/src/libuv/Tty.zig @@ -9,11 +9,13 @@ const c = @import("c.zig"); const errors = @import("error.zig"); const Loop = @import("Loop.zig"); const Handle = @import("handle.zig").Handle; +const Stream = @import("stream.zig").Stream; const Pty = @import("../Pty.zig"); handle: *c.uv_tty_t, pub usingnamespace Handle(Tty); +pub usingnamespace Stream(Tty); pub fn init(alloc: Allocator, loop: Loop, fd: fd_t) !Tty { var tty = try alloc.create(c.uv_tty_t); @@ -41,6 +43,9 @@ test "Tty" { var tty = try init(testing.allocator, loop, pty.slave); defer tty.deinit(testing.allocator); + try testing.expect(try tty.isReadable()); + try testing.expect(try tty.isWritable()); + tty.close(null); _ = try loop.run(.default); } diff --git a/src/libuv/stream.zig b/src/libuv/stream.zig new file mode 100644 index 000000000..63203e327 --- /dev/null +++ b/src/libuv/stream.zig @@ -0,0 +1,33 @@ +const c = @import("c.zig"); + +const Loop = @import("Loop.zig"); +const errors = @import("error.zig"); + +/// Returns a struct that has all the shared stream functions for the +/// given stream type T. The type T must have a field named "handle". +/// This is expected to be used with usingnamespace to add the shared +/// stream functions to other handle types. +pub fn Stream(comptime T: type) type { + // 1. T should be a struct + // 2. First field should be the handle pointer + + return struct { + // note: this has to be here: https://github.com/ziglang/zig/issues/11367 + const tInfo = @typeInfo(T).Struct; + const HandleType = tInfo.fields[0].field_type; + + /// Returns 1 if the stream is readable, 0 otherwise. + pub fn isReadable(self: T) !bool { + const res = c.uv_is_readable(@ptrCast(*c.uv_stream_t, self.handle)); + try errors.convertError(res); + return res > 0; + } + + /// Returns 1 if the stream is writable, 0 otherwise. + pub fn isWritable(self: T) !bool { + const res = c.uv_is_writable(@ptrCast(*c.uv_stream_t, self.handle)); + try errors.convertError(res); + return res > 0; + } + }; +}