1
use std::fmt::{Debug, Display, Write};
2

            
3
use serde::{Deserialize, Serialize};
4
use sha2::{Digest, Sha256};
5

            
6
/// Information about a `Document`'s revision history.
7
9587298
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
8
pub struct Revision {
9
    /// The current revision id of the document. This value is sequentially incremented on each document update.
10
    pub id: u32,
11

            
12
    /// The SHA256 digest of the bytes contained within the `Document`.
13
    pub sha256: [u8; 32],
14
}
15

            
16
impl Revision {
17
    /// Creates the first revision for a document with the SHA256 digest of the passed bytes.
18
    #[must_use]
19
666319
    pub fn new(contents: &[u8]) -> Self {
20
666319
        Self::with_id(0, contents)
21
666319
    }
22

            
23
    /// Creates a revision with `id` for a document with the SHA256 digest of the passed bytes.
24
    #[must_use]
25
666319
    pub fn with_id(id: u32, contents: &[u8]) -> Self {
26
666319
        Self {
27
666319
            id,
28
666319
            sha256: digest(contents),
29
666319
        }
30
666319
    }
31

            
32
    /// Creates the next revision in sequence with an updated digest. If the digest doesn't change, None is returned.
33
    ///
34
    /// # Panics
35
    ///
36
    /// Panics if `id` overflows.
37
    #[must_use]
38
188763
    pub fn next_revision(&self, new_contents: &[u8]) -> Option<Self> {
39
188763
        let sha256 = digest(new_contents);
40
188763
        if sha256 == self.sha256 {
41
498
            None
42
        } else {
43
188265
            Some(Self {
44
188265
                id: self
45
188265
                    .id
46
188265
                    .checked_add(1)
47
188265
                    .expect("need to implement revision id wrapping or increase revision id size"),
48
188265
                sha256,
49
188265
            })
50
        }
51
188763
    }
52
}
53

            
54
impl Debug for Revision {
55
342
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56
342
        write!(f, "Revision({})", self)
57
342
    }
58
}
59

            
60
impl Display for Revision {
61
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62
344
        <u32 as Display>::fmt(&self.id, f)?;
63
344
        f.write_char('-')?;
64
11352
        for byte in self.sha256 {
65
11008
            f.write_fmt(format_args!("{:02x}", byte))?;
66
        }
67
344
        Ok(())
68
344
    }
69
}
70

            
71
855082
fn digest(payload: &[u8]) -> [u8; 32] {
72
855082
    let mut hasher = Sha256::default();
73
855082
    hasher.update(payload);
74
855082
    hasher.finalize().into()
75
855082
}
76

            
77
1
#[test]
78
1
fn revision_tests() {
79
1
    let original_contents = b"one";
80
1
    let first_revision = Revision::new(original_contents);
81
1
    let original_digest =
82
1
        hex_literal::hex!("7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed");
83
1
    assert_eq!(
84
1
        first_revision,
85
1
        Revision {
86
1
            id: 0,
87
1
            sha256: original_digest
88
1
        }
89
1
    );
90
1
    assert!(first_revision.next_revision(original_contents).is_none());
91

            
92
1
    let updated_contents = b"two";
93
1
    let next_revision = first_revision
94
1
        .next_revision(updated_contents)
95
1
        .expect("new contents should create a new revision");
96
1
    assert_eq!(
97
1
        next_revision,
98
1
        Revision {
99
1
            id: 1,
100
1
            sha256: hex_literal::hex!(
101
1
                "3fc4ccfe745870e2c0d99f71f30ff0656c8dedd41cc1d7d3d376b0dbe685e2f3"
102
1
            )
103
1
        }
104
1
    );
105
1
    assert!(next_revision.next_revision(updated_contents).is_none());
106

            
107
1
    assert_eq!(
108
1
        next_revision.next_revision(original_contents),
109
1
        Some(Revision {
110
1
            id: 2,
111
1
            sha256: original_digest
112
1
        })
113
1
    );
114
1
}
115

            
116
1
#[test]
117
1
fn revision_display_test() {
118
1
    let original_contents = b"one";
119
1
    let first_revision = Revision::new(original_contents);
120
1
    assert_eq!(
121
1
        first_revision.to_string(),
122
1
        "0-7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed"
123
1
    );
124
1
    assert_eq!(
125
1
        format!("{:?}", first_revision),
126
1
        "Revision(0-7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed)"
127
1
    );
128
1
}