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
155738180
#[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
1058046
    pub fn new(contents: &[u8]) -> Self {
20
1058046
        Self::with_id(0, contents)
21
1058046
    }
22

            
23
    /// Creates a revision with `id` for a document with the SHA256 digest of the passed bytes.
24
    #[must_use]
25
1058046
    pub fn with_id(id: u32, contents: &[u8]) -> Self {
26
1058046
        Self {
27
1058046
            id,
28
1058046
            sha256: digest(contents),
29
1058046
        }
30
1058046
    }
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
236884
    pub fn next_revision(&self, new_contents: &[u8]) -> Option<Self> {
39
236884
        let sha256 = digest(new_contents);
40
236884
        if sha256 == self.sha256 {
41
642
            None
42
        } else {
43
236242
            Some(Self {
44
236242
                id: self
45
236242
                    .id
46
236242
                    .checked_add(1)
47
236242
                    .expect("need to implement revision id wrapping or increase revision id size"),
48
236242
                sha256,
49
236242
            })
50
        }
51
236884
    }
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
    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
1294930
fn digest(payload: &[u8]) -> [u8; 32] {
72
1294930
    let mut hasher = Sha256::default();
73
1294930
    hasher.update(payload);
74
1294930
    hasher.finalize().into()
75
1294930
}
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
}