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