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
151923629
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Hash)]
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
1063726
    pub fn new(contents: &[u8]) -> Self {
20
1063726
        Self::with_id(0, contents)
21
1063726
    }
22

            
23
    /// Creates a revision with `id` for a document with the SHA256 digest of the passed bytes.
24
    #[must_use]
25
1063726
    pub fn with_id(id: u32, contents: &[u8]) -> Self {
26
1063726
        Self {
27
1063726
            id,
28
1063726
            sha256: digest(contents),
29
1063726
        }
30
1063726
    }
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
231124
    pub fn next_revision(&self, new_contents: &[u8]) -> Option<Self> {
39
231124
        let sha256 = digest(new_contents);
40
231124
        if sha256 == self.sha256 {
41
642
            None
42
        } else {
43
230482
            Some(Self {
44
230482
                id: self
45
230482
                    .id
46
230482
                    .checked_add(1)
47
230482
                    .expect("need to implement revision id wrapping or increase revision id size"),
48
230482
                sha256,
49
230482
            })
50
        }
51
231124
    }
52
}
53

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

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

            
71
1294850
fn digest(payload: &[u8]) -> [u8; 32] {
72
1294850
    let mut hasher = Sha256::default();
73
1294850
    hasher.update(payload);
74
1294850
    hasher.finalize().into()
75
1294850
}
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
}