1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use std::fs::{metadata, File};
use std::io;
use std::io::{BufReader, Read};
use std::path::Path;
use difference;
pub type Differ = Box<Fn(&Path, &Path)>;
pub fn text_diff(old: &Path, new: &Path) {
difference::assert_diff!(&read_file(old), &read_file(new), "\n", 0);
}
pub fn binary_diff(old: &Path, new: &Path) {
let old_len = file_len(old);
let new_len = file_len(new);
if old_len != new_len {
panic!(
"File sizes differ: Old file is {} bytes, new file is {} bytes",
old_len, new_len
);
}
let first_difference = file_byte_iter(old)
.zip(file_byte_iter(new))
.position(|(old_byte, new_byte)| old_byte != new_byte);
if let Some(position) = first_difference {
panic!("Files differ at byte {}", position + 1);
}
}
fn open_file(path: &Path) -> File {
check_io(File::open(path), "opening file", path)
}
fn file_byte_iter<'a>(path: &'a Path) -> impl Iterator<Item = u8> + 'a {
BufReader::new(open_file(path))
.bytes()
.map(move |b| check_io(b, "reading file", path))
}
fn file_len(path: &Path) -> u64 {
check_io(metadata(path), "getting file length", path).len()
}
fn read_file(path: &Path) -> String {
let mut contents = String::new();
check_io(
open_file(path).read_to_string(&mut contents),
"reading file",
path,
);
contents
}
fn check_io<T>(x: Result<T, io::Error>, message: &str, path: &Path) -> T {
x.unwrap_or_else(|_| panic!("Error {}: {:?}", message, path))
}