在开发程序尤其是撰写测试或脚本的时候,有时会需要判断两个文件的内容是否相同。可是由于文件体积可能会很大,不可能直接把两个文件都整个读进内存后再进行比对,所以要分段读取。不过 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());
