在開發程式尤其是撰寫測試或腳本的時候,有時會需要判斷兩個檔案的內容是否相同。可是由於檔案體積可能會很大,不可能直接把兩個檔案都整個讀進記憶體後再進行比對,所以要分段讀取。不過 Rust 的標準函式庫並沒有內建像這樣的比對檔案內容的功能,要另外實作才行。
Same Content
「Same Content」是筆者開發的套件,可以用來判斷來自兩個檔案或是兩個有實作 Read 特性的實體的資料內容是否相同。
Crates.io
Cargo.toml
same-content = "*"
使用方法
same_content 這個 crate 提供的 same_content_from_readers 函數可以傳入兩個有實作 Read 特性的實體,它會在堆疊中建立緩衝空間來儲存分段讀取到的資料,一旦發現兩個來源的資料內容不同,就會立刻回傳 false。
use std::fs::File;
use same_content::*;
assert!(!same_content_from_readers(&mut File::open("tests/data/P1140310.jpg").unwrap(), &mut File::open("tests/data/P1140558.jpg").unwrap()).unwrap());
不過對於檔案(File 結構實體),其實使用 same_content_from_files 函數會更好,因為它會在讀取內容之前,先判斷兩個檔案的大小是否相同。
use std::fs::File;
use same_content::*;
assert!(!same_content_from_files(&mut File::open("tests/data/P1140310.jpg").unwrap(), &mut File::open("tests/data/P1140558.jpg").unwrap()).unwrap());
預設的緩衝空間大小為 256 個位元組。若您想要改變緩衝空間大小,可以使用 same_content_from_readers2 或是 same_content_from_files2 函數並且明確地定義要使用的長度(透過泛型)。
例如,要將緩衝空間大小改為 4096 個位元組的話,程式可以這樣寫:
use std::fs::File;
use same_content::*;
use same_content::generic_array::typenum::U4096;
assert!(!same_content_from_files2::<U4096>(&mut File::open("tests/data/P1140310.jpg").unwrap(), &mut File::open("tests/data/P1140558.jpg").unwrap()).unwrap());
