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

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

            
6
/// Information about a `Document`'s revision history.
7
5285561
#[derive(Debug, 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
507057
    pub fn new(contents: &[u8]) -> Self {
20
507057
        Self::with_id(0, contents)
21
507057
    }
22

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

            
54
impl Display for Revision {
55
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56
2
        self.id.fmt(f)?;
57
2
        f.write_char('-')?;
58
66
        for byte in self.sha256 {
59
64
            f.write_fmt(format_args!("{:02x}", byte))?;
60
        }
61
2
        Ok(())
62
2
    }
63
}
64

            
65
648215
fn digest(payload: &[u8]) -> [u8; 32] {
66
648215
    let mut hasher = Sha256::default();
67
648215
    hasher.update(payload);
68
648215
    hasher.finalize().into()
69
648215
}
70

            
71
1
#[test]
72
1
fn revision_tests() {
73
1
    let original_contents = b"one";
74
1
    let first_revision = Revision::new(original_contents);
75
1
    let original_digest =
76
1
        hex_literal::hex!("7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed");
77
1
    assert_eq!(
78
1
        first_revision,
79
1
        Revision {
80
1
            id: 0,
81
1
            sha256: original_digest
82
1
        }
83
1
    );
84
1
    assert!(first_revision.next_revision(original_contents).is_none());
85

            
86
1
    let updated_contents = b"two";
87
1
    let next_revision = first_revision
88
1
        .next_revision(updated_contents)
89
1
        .expect("new contents should create a new revision");
90
1
    assert_eq!(
91
1
        next_revision,
92
1
        Revision {
93
1
            id: 1,
94
1
            sha256: hex_literal::hex!(
95
1
                "3fc4ccfe745870e2c0d99f71f30ff0656c8dedd41cc1d7d3d376b0dbe685e2f3"
96
1
            )
97
1
        }
98
1
    );
99
1
    assert!(next_revision.next_revision(updated_contents).is_none());
100

            
101
1
    assert_eq!(
102
1
        next_revision.next_revision(original_contents),
103
1
        Some(Revision {
104
1
            id: 2,
105
1
            sha256: original_digest
106
1
        })
107
1
    );
108
1
}
109

            
110
1
#[test]
111
1
fn revision_display_test() {
112
1
    let original_contents = b"one";
113
1
    let first_revision = Revision::new(original_contents);
114
1
    assert_eq!(
115
1
        first_revision.to_string(),
116
1
        "0-7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed"
117
1
    );
118
1
}