diff --git a/AnyWritable.zig b/AnyWritable.zig new file mode 100644 index 0000000000000000000000000000000000000000..258967bfc742463dd79d4f70a3738a68e862e818 --- /dev/null +++ b/AnyWritable.zig @@ -0,0 +1,31 @@ +const std = @import("std"); + +const nio = @import("./nio.zig"); +const AnyWritable = @This(); + +vtable: *const struct { + write: *const fn (*allowzero anyopaque, []const u8) anyerror!usize, +}, +state: *allowzero anyopaque, + +pub const WriteError = anyerror; +pub usingnamespace nio.Writable(@This(), ._var); +pub fn write(r: *AnyWritable, buffer: []u8) !usize { + return r.vtable.write(r.state, buffer); +} +pub fn anyWritable(r: AnyWritable) AnyWritable { + return r; +} + +pub fn fromStd(writer_ptr: anytype) AnyWritable { + const S = struct { + fn _write(s: *allowzero anyopaque, buffer: []const u8) !usize { + const r: @TypeOf(writer_ptr) = @ptrCast(@alignCast(s)); + return r.write(buffer); + } + }; + return .{ + .vtable = &.{ .write = &S._write }, + .state = @constCast(@ptrCast(writer_ptr)), + }; +} diff --git a/nio.zig b/nio.zig index b57ea344f387a2a5507374e7486cd98a8b5a7d81..66f9a737038c1edfcfdc497e315a78a0b79c3c44 100644 --- a/nio.zig +++ b/nio.zig @@ -136,4 +136,6 @@ pub fn Writable(T: type, this_kind: enum { _var, _const, _bare }) type { pub const AnyReadable = @import("./AnyReadable.zig"); +pub const AnyWritable = @import("./AnyWritable.zig"); + pub const FixedBufferStream = @import("./fixed_buffer_stream.zig").FixedBufferStream;