summaryrefslogtreecommitdiffstats
path: root/src/hash.rs
blob: 8a2d884110cead333a1bbe189f0a70c870539cb7 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use sha2::{Digest, Sha256};
use std::io::{self, Read, Write};

pub fn hex(bytes: &[u8]) -> String {
    let mut h = Sha256::new();
    h.update(bytes);
    hex::encode(h.finalize())
}

pub fn hex_str(s: &str) -> String {
    hex(s.as_bytes())
}

pub fn short(bytes: &[u8], n: usize) -> String {
    let h = hex(bytes);
    h[..n.min(h.len())].to_string()
}

pub fn digest_reader<R: Read>(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> {
    let mut h = Sha256::new();
    let mut buf = vec![0u8; 64 * 1024];
    let mut total = 0u64;
    loop {
        let n = r.read(&mut buf)?;
        if n == 0 {
            break;
        }
        h.update(&buf[..n]);
        if let Some(s) = sink.as_mut() {
            s.write_all(&buf[..n])?;
        }
        total += n as u64;
    }
    Ok((hex::encode(h.finalize()), total))
}

pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> {
    let f = std::fs::File::open(path)?;
    let mut br = io::BufReader::new(f);
    digest_reader(&mut br, None)
}

pub fn recipe_hash(entries: &[(String, String)]) -> String {
    let mut sorted: Vec<&(String, String)> = entries.iter().collect();
    sorted.sort_unstable_by(|a, b| a.0.cmp(&b.0));
    let mut h = Sha256::new();
    for (path, blob) in &sorted {
        h.update(path.as_bytes());
        h.update([0u8]);
        h.update(blob.as_bytes());
        h.update([0u8]);
    }
    hex::encode(h.finalize())
}

pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> {
    serde_json::to_string(&serde_json::to_value(v)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Unserializable;

    impl serde::Serialize for Unserializable {
        fn serialize<S: serde::Serializer>(&self, _s: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("this value cannot be serialized"))
        }
    }

    // Moved verbatim from tests/hash.rs. Both tests are a function of their
    // argument alone; the third test that file held was about `Identity`, not
    // about hashing, and moved to db::model where it belongs.

    #[test]
    fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() {
        let err = canonical_json(&Unserializable).unwrap_err();
        assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}");
        assert!(canonical_json(&Unserializable).is_err());
    }

    #[test]
    fn the_rendering_is_canonical_in_fact_not_in_name() {
        #[derive(serde::Serialize)]
        struct Ab {
            alpha: String,
            beta: String,
        }
        #[derive(serde::Serialize)]
        struct Ba {
            beta: String,
            alpha: String,
        }
        let ab = canonical_json(&Ab { alpha: "1".into(), beta: "2".into() }).unwrap();
        let ba = canonical_json(&Ba { beta: "2".into(), alpha: "1".into() }).unwrap();
        assert_eq!(ab, ba, "field declaration order leaked into the rendering: {ab} vs {ba}");
        assert_eq!(ab, r#"{"alpha":"1","beta":"2"}"#, "not the compact sorted rendering");

        let mut one = std::collections::HashMap::new();
        one.insert("z", 1);
        one.insert("m", 2);
        one.insert("a", 3);
        let mut two = std::collections::HashMap::new();
        two.insert("a", 3);
        two.insert("m", 2);
        two.insert("z", 1);
        assert_eq!(canonical_json(&one).unwrap(), canonical_json(&two).unwrap());
    }
}