1//! `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
2
3const std = @import("std");
4const nio = @import("./nio.zig");
5const builtin = @import("builtin");
6const extras = @import("extras");
7
8const sys = switch (builtin.target.os.tag) {
9 .linux => @import("sys-linux"),
10 .macos => @import("sys-darwin"),
11 .freebsd => @import("sys-freebsd"),
12 .netbsd => @import("sys-netbsd"),
13 .openbsd => @import("sys-openbsd"),
14 else => unreachable,
15};
16
17pub fn HashWriter(comptime Hash: type) type {
18 return struct {
19 hasher: *Hash,
20
21 pub fn init(hasher: *Hash) @This() {
22 return .{
23 .hasher = hasher,
24 };
25 }
26
27 pub fn from(hasher: anytype) HashWriter(extras.Pointee(@TypeOf(hasher))) {
28 return .init(hasher);
29 }
30
31 const W = nio.Writable(@This(), ._const);
32 pub const writeAll = W.writeAll;
33 pub const writevAll = W.writevAll;
34 pub const writeByteNTimes = W.writeByteNTimes;
35 pub const writeNTimes = W.writeNTimes;
36 pub const writeInt = W.writeInt;
37 pub const writeStruct = W.writeStruct;
38 pub const writeIntPretty = W.writeIntPretty;
39 pub const print = W.print;
40
41 pub const WriteError = error{};
42
43 pub fn write(self: *const @This(), bytes: []const u8) WriteError!usize {
44 self.hasher.update(bytes);
45 return bytes.len;
46 }
47
48 pub fn writev(self: *const @This(), iovec: []const sys.struct_iovec) WriteError!usize {
49 var count: usize = 0;
50 for (iovec) |vec| count += try write(self, vec.base[0..vec.len]);
51 return count;
52 }
53 };
54}