authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2022-11-11 13:36:05 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2022-11-11 13:36:05 -08:00
logcab8f0eb4859d9c7249020e43af522a5fd43b41d
tree920f7927a74b341267432c509b55319824fe7e78
parentaa9d248faae804341b40efe628e1489d95e7474e

hashFile: directly accept the Algo


1 files changed, 2 insertions(+), 33 deletions(-)

src/lib.zig+2-33
......@@ -139,48 +139,17 @@ pub fn fileSize(dir: std.fs.Dir, sub_path: string) !u64 {
139139 return s.size;
140140}
141141
142pub const HashFn = enum {
143 blake3,
144 gimli,
145 md5,
146 sha1,
147 sha224,
148 sha256,
149 sha384,
150 sha512,
151 sha3_224,
152 sha3_256,
153 sha3_384,
154 sha3_512,
155};
156
157pub fn hashFile(alloc: std.mem.Allocator, dir: std.fs.Dir, sub_path: string, comptime algo: HashFn) !string {
142pub fn hashFile(dir: std.fs.Dir, sub_path: string, comptime Algo: type) ![Algo.digest_length * 2]u8 {
158143 const file = try dir.openFile(sub_path, .{});
159144 defer file.close();
160 const hash = std.crypto.hash;
161 const Algo = switch (algo) {
162 .blake3 => hash.Blake3,
163 .gimli => hash.Gimli,
164 .md5 => hash.Md5,
165 .sha1 => hash.Sha1,
166 .sha224 => hash.sha2.Sha224,
167 .sha256 => hash.sha2.Sha256,
168 .sha384 => hash.sha2.Sha384,
169 .sha512 => hash.sha2.Sha512,
170 .sha3_224 => hash.sha3.Sha3_224,
171 .sha3_256 => hash.sha3.Sha3_256,
172 .sha3_384 => hash.sha3.Sha3_384,
173 .sha3_512 => hash.sha3.Sha3_512,
174 };
175145 var h = Algo.init(.{});
176146 var out: [Algo.digest_length]u8 = undefined;
177147 try pipe(file.reader(), h.writer());
178148 h.final(&out);
179
180149 var res: [Algo.digest_length * 2]u8 = undefined;
181150 var fbs = std.io.fixedBufferStream(&res);
182151 try std.fmt.format(fbs.writer(), "{x}", .{std.fmt.fmtSliceHexLower(&out)});
183 return try alloc.dupe(u8, &res);
152 return res;
184153}
185154
186155pub fn pipe(reader_from: anytype, writer_to: anytype) !void {