Skip to main content

compmd_host/
frames_hash.rs

1//! The frames' build's hash, which names its folder, `frames/<hash>/`.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::manifest_error::ManifestError;
9
10/// A frames' build's hash: the first 16 hex digits, lowercase, of a SHA-256 over each file's path and bytes, so it
11/// can't name another folder.
12#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(try_from = "String", into = "String")]
14pub struct FramesHash(String);
15
16impl FramesHash {
17    /// The hash `text`, when it is one.
18    ///
19    /// # Errors
20    ///
21    /// [`ManifestError::Hash`] when it isn't 16 lowercase hex digits.
22    pub fn new(text: impl Into<String>) -> Result<Self, ManifestError> {
23        let text = text.into();
24        let hex = text.len() == 16
25            && text
26                .bytes()
27                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
28        if hex {
29            Ok(Self(text))
30        } else {
31            Err(ManifestError::Hash(text))
32        }
33    }
34
35    /// The hash as written.
36    #[must_use]
37    pub fn as_str(&self) -> &str {
38        &self.0
39    }
40}
41
42impl FromStr for FramesHash {
43    type Err = ManifestError;
44
45    fn from_str(text: &str) -> Result<Self, Self::Err> {
46        Self::new(text)
47    }
48}
49
50impl TryFrom<String> for FramesHash {
51    type Error = ManifestError;
52
53    fn try_from(text: String) -> Result<Self, Self::Error> {
54        Self::new(text)
55    }
56}
57
58impl From<FramesHash> for String {
59    fn from(hash: FramesHash) -> Self {
60        hash.0
61    }
62}
63
64impl fmt::Display for FramesHash {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(&self.0)
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn a_hash_is_16_lowercase_hex_digits() {
76        let hash: FramesHash = "1df336e75685de8c".parse().expect("a hash");
77        assert_eq!(hash.as_str(), "1df336e75685de8c");
78        assert_eq!(hash.to_string(), "1df336e75685de8c");
79        assert_eq!(String::from(hash.clone()), "1df336e75685de8c");
80        assert_eq!(
81            FramesHash::try_from("1df336e75685de8c".to_owned()),
82            Ok(hash)
83        );
84        for text in [
85            "../secret",
86            "1DF336E75685DE8C",
87            "1df336e7",
88            "1df336e75685de8g",
89        ] {
90            assert_eq!(
91                FramesHash::new(text),
92                Err(ManifestError::Hash(text.to_owned())),
93                "{text}"
94            );
95        }
96    }
97}