Skip to content

Commit ebcc78c

Browse files
feat: add anywriter
1 parent 9db0545 commit ebcc78c

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ Any+ is a Zig library for handling anytypes in the runtime.
66

77
- [x] Runtime `anytype`
88
- [ ] Any-reader
9-
- [ ] Any-writer
9+
- [x] Any-writer

any+.zig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
/// Anytype in runtime
22
pub const Anytype = @import("any+/anytype.zig");
33

4+
/// An opaque writer type
5+
pub const Anywriter = @import("any+/anywriter.zig");
6+
47
test {
58
_ = Anytype;
9+
_ = Anywriter;
610
}

any+/anywriter.zig

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const std = @import("std");
2+
const Self = @This();
3+
4+
pub const Error = anyerror;
5+
const PointerWrite = *const fn (*const Self, []const u8) Error!void;
6+
7+
pub const Writer = std.io.Writer(Self, Error, write);
8+
9+
type: []const u8,
10+
ptr: *anyopaque,
11+
ptrWrite: PointerWrite,
12+
13+
pub inline fn init(writer: anytype) Self {
14+
return initExplicit(@TypeOf(writer), writer);
15+
}
16+
17+
pub inline fn initExplicit(comptime T: type, writer: T) Self {
18+
return .{
19+
.type = @typeName(T),
20+
.ptr = @constCast(&writer),
21+
.ptrWrite = (struct {
22+
fn func(self: *const Self, buf: []const u8) Error!void {
23+
if (!std.mem.eql(u8, self.type, @typeName(T))) return error.InvalidCast;
24+
const w: *T = @ptrCast(@alignCast(self.ptr));
25+
return w.write(buf);
26+
}
27+
}).func,
28+
};
29+
}
30+
31+
pub fn write(self: Self, buf: []const u8) Error!void {
32+
return self.ptrWrite(&self, buf);
33+
}

0 commit comments

Comments
 (0)