libuv: start shared stream functions

This commit is contained in:
Mitchell Hashimoto
2022-04-24 22:03:14 -07:00
parent 6613ae0f8f
commit 02eeece569
2 changed files with 38 additions and 0 deletions

View File

@ -9,11 +9,13 @@ const c = @import("c.zig");
const errors = @import("error.zig"); const errors = @import("error.zig");
const Loop = @import("Loop.zig"); const Loop = @import("Loop.zig");
const Handle = @import("handle.zig").Handle; const Handle = @import("handle.zig").Handle;
const Stream = @import("stream.zig").Stream;
const Pty = @import("../Pty.zig"); const Pty = @import("../Pty.zig");
handle: *c.uv_tty_t, handle: *c.uv_tty_t,
pub usingnamespace Handle(Tty); pub usingnamespace Handle(Tty);
pub usingnamespace Stream(Tty);
pub fn init(alloc: Allocator, loop: Loop, fd: fd_t) !Tty { pub fn init(alloc: Allocator, loop: Loop, fd: fd_t) !Tty {
var tty = try alloc.create(c.uv_tty_t); var tty = try alloc.create(c.uv_tty_t);
@ -41,6 +43,9 @@ test "Tty" {
var tty = try init(testing.allocator, loop, pty.slave); var tty = try init(testing.allocator, loop, pty.slave);
defer tty.deinit(testing.allocator); defer tty.deinit(testing.allocator);
try testing.expect(try tty.isReadable());
try testing.expect(try tty.isWritable());
tty.close(null); tty.close(null);
_ = try loop.run(.default); _ = try loop.run(.default);
} }

33
src/libuv/stream.zig Normal file
View File

@ -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;
}
};
}