authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-10-12 23:57:26 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-10-12 23:57:26 -07:00
logfc9553f55eee4bdf08a6cddb908eebc2860547b0
treeb78686e2521f8d58d7e580b416b30537d1cc1d7b
parent19d5e8bfcc1a053184ca9647afbefb41cbc206cc

AnyReader: support building from std.fs.File.Reader


1 files changed, 30 insertions(+), 11 deletions(-)

src/lib.zig+30-11
......@@ -698,17 +698,36 @@ pub const AnyReader = struct {
698698 const R = @TypeOf(reader);
699699 const ctx = reader.context;
700700 const Ctx = @TypeOf(ctx);
701 comptime std.debug.assert(std.meta.trait.is(.Pointer)(Ctx));
702 const S = struct {
703 fn foo(s: *anyopaque, buffer: []u8) anyerror!usize {
704 const r = R{ .context = @ptrCast(@alignCast(s)) };
705 return r.read(buffer);
706 }
707 };
708 return .{
709 .readFn = S.foo,
710 .state = ctx,
711 };
701 switch (@typeInfo(Ctx)) {
702 .Pointer => {
703 const S = struct {
704 fn foo(s: *anyopaque, buffer: []u8) anyerror!usize {
705 const r = R{ .context = @ptrCast(@alignCast(s)) };
706 return r.read(buffer);
707 }
708 };
709 return .{
710 .readFn = S.foo,
711 .state = ctx,
712 };
713 },
714 .Struct => switch (R) {
715 std.fs.File.Reader => {
716 const S = struct {
717 fn foo(s: *anyopaque, buffer: []u8) anyerror!usize {
718 const r = R{ .context = .{ .handle = @intCast(@intFromPtr(s)) } };
719 return r.read(buffer);
720 }
721 };
722 return .{
723 .readFn = S.foo,
724 .state = @ptrFromInt(@as(usize, @intCast(ctx.handle))),
725 };
726 },
727 else => @compileError(@typeName(R)),
728 },
729 else => |v| @compileError(@typeName(R) ++ " , " ++ @tagName(v)),
730 }
712731 }
713732
714733 pub fn read(r: AnyReader, buffer: []u8) anyerror!usize {