diff --git a/hash_writer.zig b/hash_writer.zig new file mode 100644 index 0000000000000000000000000000000000000000..e8578455609bfa33b1bbb3113f93142bb1a3ba82 --- /dev/null +++ b/hash_writer.zig @@ -0,0 +1,46 @@ +//! `std.Io.Writer.Hashing` is recommended to use over this but that type owns the hasher so this allows you to print into an existing Hash + +const std = @import("std"); +const nio = @import("./nio.zig"); +const builtin = @import("builtin"); + +const sys = switch (builtin.target.os.tag) { + .linux => @import("sys-linux"), + .macos => @import("sys-darwin"), + else => unreachable, +}; + +pub fn HashWriter(comptime Hash: type) type { + return struct { + hasher: *Hash, + + pub fn init(hasher: *Hash) @This() { + return .{ + .hasher = hasher, + }; + } + + const W = nio.Writable(@This(), ._const); + pub const writeAll = W.writeAll; + pub const writevAll = W.writevAll; + pub const writeByteNTimes = W.writeByteNTimes; + pub const writeNTimes = W.writeNTimes; + pub const writeInt = W.writeInt; + pub const writeStruct = W.writeStruct; + pub const writeIntPretty = W.writeIntPretty; + pub const print = W.print; + + pub const WriteError = error{}; + + pub fn write(self: *const @This(), bytes: []const u8) WriteError!usize { + self.hasher.update(bytes); + return bytes.len; + } + + pub fn writev(self: *const @This(), iovec: []const sys.struct_iovec) WriteError!usize { + var count: usize = 0; + for (iovec) |vec| count += try write(self, vec.base[0..vec.len]); + return count; + } + }; +} diff --git a/nio.zig b/nio.zig index 7e29e05566d5cbb977ee78e1e8903854b51dcc0f..2bde4a3ca4892e9f749b2b9b3d34f3e6f7e3b221 100644 --- a/nio.zig +++ b/nio.zig @@ -444,6 +444,8 @@ pub const CountingReader = @import("./counting_reader.zig").CountingReader; pub const LimitedReader = @import("./limited_reader.zig").LimitedReader; +pub const HashWriter = @import("./hash_writer.zig").HashWriter; + pub const crypto_random: std.Random = .{ .ptr = undefined, .fillFn = getrandomFill,