| ... | @@ -139,48 +139,17 @@ pub fn fileSize(dir: std.fs.Dir, sub_path: string) !u64 { | ... | @@ -139,48 +139,17 @@ pub fn fileSize(dir: std.fs.Dir, sub_path: string) !u64 { |
| 139 | return s.size; | 139 | return s.size; |
| 140 | } | 140 | } |
| 141 | | 141 | |
| 142 | pub const HashFn = enum { | 142 | pub fn hashFile(dir: std.fs.Dir, sub_path: string, comptime Algo: type) ![Algo.digest_length * 2]u8 { |
| 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 | | | |
| 157 | pub fn hashFile(alloc: std.mem.Allocator, dir: std.fs.Dir, sub_path: string, comptime algo: HashFn) !string { | | |
| 158 | const file = try dir.openFile(sub_path, .{}); | 143 | const file = try dir.openFile(sub_path, .{}); |
| 159 | defer file.close(); | 144 | 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 | }; | | |
| 175 | var h = Algo.init(.{}); | 145 | var h = Algo.init(.{}); |
| 176 | var out: [Algo.digest_length]u8 = undefined; | 146 | var out: [Algo.digest_length]u8 = undefined; |
| 177 | try pipe(file.reader(), h.writer()); | 147 | try pipe(file.reader(), h.writer()); |
| 178 | h.final(&out); | 148 | h.final(&out); |
| 179 | | | |
| 180 | var res: [Algo.digest_length * 2]u8 = undefined; | 149 | var res: [Algo.digest_length * 2]u8 = undefined; |
| 181 | var fbs = std.io.fixedBufferStream(&res); | 150 | var fbs = std.io.fixedBufferStream(&res); |
| 182 | try std.fmt.format(fbs.writer(), "{x}", .{std.fmt.fmtSliceHexLower(&out)}); | 151 | try std.fmt.format(fbs.writer(), "{x}", .{std.fmt.fmtSliceHexLower(&out)}); |
| 183 | return try alloc.dupe(u8, &res); | 152 | return res; |
| 184 | } | 153 | } |
| 185 | | 154 | |
| 186 | pub fn pipe(reader_from: anytype, writer_to: anytype) !void { | 155 | pub fn pipe(reader_from: anytype, writer_to: anytype) !void { |