1use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::invalid::Invalid;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub enum Algorithm {
13 Sha256,
15 Sha384,
17 Sha512,
19}
20
21impl Algorithm {
22 #[must_use]
24 pub const fn name(self) -> &'static str {
25 match self {
26 Self::Sha256 => "sha256",
27 Self::Sha384 => "sha384",
28 Self::Sha512 => "sha512",
29 }
30 }
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
35#[serde(try_from = "String", into = "String")]
36pub struct Integrity {
37 algorithm: Algorithm,
38 digest: String,
39}
40
41impl Integrity {
42 pub fn new(text: &str) -> Result<Self, Invalid> {
50 let invalid = || Invalid::Integrity(text.to_owned());
51 let (name, digest) = text.split_once('-').ok_or_else(invalid)?;
52 let algorithm = [Algorithm::Sha256, Algorithm::Sha384, Algorithm::Sha512]
53 .into_iter()
54 .find(|algorithm| algorithm.name() == name)
55 .ok_or_else(invalid)?;
56 let visible = !digest.is_empty() && !digest.chars().any(char::is_whitespace);
57 if visible {
58 Ok(Self {
59 algorithm,
60 digest: digest.to_owned(),
61 })
62 } else {
63 Err(invalid())
64 }
65 }
66
67 #[must_use]
69 pub const fn algorithm(&self) -> Algorithm {
70 self.algorithm
71 }
72
73 #[must_use]
75 pub fn digest(&self) -> &str {
76 &self.digest
77 }
78}
79
80impl fmt::Display for Integrity {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "{}-{}", self.algorithm.name(), self.digest)
83 }
84}
85
86impl FromStr for Integrity {
87 type Err = Invalid;
88
89 fn from_str(text: &str) -> Result<Self, Self::Err> {
90 Self::new(text)
91 }
92}
93
94impl TryFrom<String> for Integrity {
95 type Error = Invalid;
96
97 fn try_from(text: String) -> Result<Self, Self::Error> {
98 Self::new(&text)
99 }
100}
101
102impl From<Integrity> for String {
103 fn from(integrity: Integrity) -> Self {
104 integrity.to_string()
105 }
106}
107
108#[cfg(test)]
109mod tests {
110 use super::*;
111
112 #[test]
113 fn an_integrity_is_an_algorithm_and_a_digest() {
114 for (text, algorithm) in [
115 ("sha256-abc=", Algorithm::Sha256),
116 ("sha384-a+b/c", Algorithm::Sha384),
117 ("sha512-9c1fQe0=", Algorithm::Sha512),
118 ] {
119 let integrity: Integrity = text.parse().expect(text);
120 assert_eq!(integrity.algorithm(), algorithm);
121 assert_eq!(integrity.to_string(), text);
122 }
123 assert_eq!(Integrity::new("sha512-xyz").expect("one").digest(), "xyz");
124 assert_eq!(
125 Integrity::new("sha512-9c1fQe…")
126 .expect("as the spec shortens it")
127 .digest(),
128 "9c1fQe…"
129 );
130 }
131
132 #[test]
133 fn what_isnt_an_integrity_is_refused() {
134 for text in [
135 "",
136 "sha512",
137 "sha512-",
138 "md5-abc",
139 "sha512-a b",
140 "sha512-a\tb",
141 ] {
142 assert_eq!(
143 Integrity::new(text),
144 Err(Invalid::Integrity(text.to_owned())),
145 "{text}"
146 );
147 }
148 assert!(
149 Invalid::Integrity("x".to_owned())
150 .to_string()
151 .contains("base64")
152 );
153 }
154
155 #[test]
156 fn an_integrity_is_a_string_in_json() {
157 let integrity: Integrity = serde_json::from_str(r#""sha512-abc""#).expect("one");
158 assert_eq!(
159 serde_json::to_string(&integrity).expect("JSON"),
160 r#""sha512-abc""#
161 );
162 assert!(serde_json::from_str::<Integrity>(r#""md5-abc""#).is_err());
163 assert_eq!(String::from(integrity), "sha512-abc");
164 }
165}