2022-01-18 21:41:09 +01:00
|
|
|
module util
|
|
|
|
|
|
|
|
import os
|
|
|
|
import crypto.md5
|
2022-01-31 14:43:57 +01:00
|
|
|
import crypto.sha256
|
2022-01-18 21:41:09 +01:00
|
|
|
|
|
|
|
// hash_file returns the md5 & sha256 hash of a given file
|
2022-01-18 22:52:14 +01:00
|
|
|
// TODO actually implement sha256
|
2022-01-18 21:41:09 +01:00
|
|
|
pub fn hash_file(path &string) ?(string, string) {
|
|
|
|
file := os.open(path) or { return error('Failed to open file.') }
|
|
|
|
|
|
|
|
mut md5sum := md5.new()
|
2022-01-31 14:43:57 +01:00
|
|
|
mut sha256sum := sha256.new()
|
2022-01-18 21:41:09 +01:00
|
|
|
|
2022-01-18 22:52:14 +01:00
|
|
|
buf_size := int(1_000_000)
|
2022-01-18 21:41:09 +01:00
|
|
|
mut buf := []byte{len: buf_size}
|
|
|
|
mut bytes_left := os.file_size(path)
|
|
|
|
|
|
|
|
for bytes_left > 0 {
|
|
|
|
// TODO check if just breaking here is safe
|
2022-01-19 17:15:37 +01:00
|
|
|
bytes_read := file.read(mut buf) or { return error('Failed to read from file.') }
|
2022-01-18 21:41:09 +01:00
|
|
|
bytes_left -= u64(bytes_read)
|
|
|
|
|
2022-01-19 17:15:37 +01:00
|
|
|
// For now we'll assume that this always works
|
|
|
|
md5sum.write(buf[..bytes_read]) or {
|
2022-01-31 14:43:57 +01:00
|
|
|
return error('Failed to update md5 checksum. This should never happen.')
|
|
|
|
}
|
|
|
|
sha256sum.write(buf[..bytes_read]) or {
|
|
|
|
return error('Failed to update sha256 checksum. This should never happen.')
|
2022-01-18 21:41:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-31 14:43:57 +01:00
|
|
|
return md5sum.checksum().hex(), sha256sum.checksum().hex()
|
2022-01-18 21:41:09 +01:00
|
|
|
}
|