以下代碼將檔案讀入位元組并計算位元組陣列的 md5sum。它可以作業,但我想在 V 中找到一個需要更少 RAM 的解決方案。感謝您的意見 !
import os
import crypto.md5
b := os.read_bytes("file.txt") or {panic(err)}
s := md5.sum(b).hex()
println(s)
我也試過沒有成功:
import os
import crypto.md5
import io
mut f := os.open_file("file.txt", "r")?
mut h := md5.new()
io.cp(mut f, mut h)?
s := h.sum().hex()
println(s) // does not return the correct md5sum
uj5u.com熱心網友回復:
好的。這就是你要找的。它產生相同的結果,md5sum只是稍微慢一點。block_size與使用的記憶體量和計算校驗和的速度成反比。減少block_size會降低記憶體占用,但需要更長的計算時間。增加block_size會產生相反的效果。我在 2GB 的 manjaro 磁盤映像上進行了測驗,可以確認記憶體使用率非常低。
-prod注意:在沒有標志的情況下,它的執行速度似乎明顯變慢。V 編譯器進行了特殊優化,以便在生產構建中運行得更快。
import crypto.md5
import io
import os
fn main() {
println(hash_file('manjaro.img')?)
}
const block_size = 64 * 65535
fn hash_file(path string) ?string {
mut file := os.open(path)?
defer {
file.close()
}
mut buf := []u8{len: block_size}
mut r := io.new_buffered_reader(reader: file)
mut digest := md5.new()
for {
x := r.read(mut buf) or { break }
digest.write(buf[..x])?
}
return digest.checksum().hex()
}
uj5u.com熱心網友回復:
總結一下我從評論中學到的東西:
- V 是一種帶有型別引數的編程語言
md5.sum接受一個位元組陣列引數,而不是位元組序列,例如從檔案中讀取。- 沒有其他選擇
md5.sum
因此,您必須自己實作 MD5。也許標準庫是開源的,您可以在此基礎上構建!或者,您可以系結任何現有的 MD5(例如 C)實作,并在讀取它們時輸入位元組,以 512 位 = 2? 位元組的塊為單位。
編輯:我不知道 V,所以我很難判斷,但它看起來Digest.write會是一種通過 MD5 計算連續推送資料的方法。也許這與從檔案中讀取位元組的while回圈一起是解決方案?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485464.html
