Skip to main content

quichash_core/hash/
algorithm.rs

1use std::fmt;
2use std::str::FromStr;
3
4use super::hasher::{Hasher, bytes_to_hex};
5use super::registry::HashRegistry;
6use crate::error::HashUtilityError;
7
8/// Stable identifier for every algorithm understood by QuicHash.
9#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
10#[serde(rename_all = "kebab-case")]
11pub enum Algorithm {
12    /// MD5 with a 128-bit output.
13    Md5,
14    /// SHA-1 with a 160-bit output.
15    Sha1,
16    /// SHA-224 from the SHA-2 family.
17    Sha224,
18    /// SHA-256 from the SHA-2 family.
19    Sha256,
20    /// SHA-384 from the SHA-2 family.
21    Sha384,
22    /// SHA-512 from the SHA-2 family.
23    Sha512,
24    /// SHA3-224.
25    Sha3_224,
26    /// SHA3-256.
27    Sha3_256,
28    /// SHA3-384.
29    Sha3_384,
30    /// SHA3-512.
31    Sha3_512,
32    /// BLAKE2b with a 512-bit output.
33    Blake2b512,
34    /// BLAKE2s with a 256-bit output.
35    Blake2s256,
36    /// BLAKE3 with its standard 256-bit output.
37    Blake3,
38    /// XXH3 with a 64-bit output.
39    Xxh3,
40    /// XXH3 with a 128-bit output.
41    Xxh128,
42}
43
44impl Algorithm {
45    /// Every algorithm identifier understood by this version of the crate.
46    ///
47    /// The array includes algorithms that may have been disabled through Cargo
48    /// features. Use [`Algorithm::is_available`] to filter it.
49    pub const ALL: [Self; 15] = [
50        Self::Md5,
51        Self::Sha1,
52        Self::Sha224,
53        Self::Sha256,
54        Self::Sha384,
55        Self::Sha512,
56        Self::Sha3_224,
57        Self::Sha3_256,
58        Self::Sha3_384,
59        Self::Sha3_512,
60        Self::Blake2b512,
61        Self::Blake2s256,
62        Self::Blake3,
63        Self::Xxh3,
64        Self::Xxh128,
65    ];
66
67    /// Return the stable lowercase name used in manifests and string parsing.
68    pub const fn canonical_name(self) -> &'static str {
69        match self {
70            Self::Md5 => "md5",
71            Self::Sha1 => "sha1",
72            Self::Sha224 => "sha224",
73            Self::Sha256 => "sha256",
74            Self::Sha384 => "sha384",
75            Self::Sha512 => "sha512",
76            Self::Sha3_224 => "sha3-224",
77            Self::Sha3_256 => "sha3-256",
78            Self::Sha3_384 => "sha3-384",
79            Self::Sha3_512 => "sha3-512",
80            Self::Blake2b512 => "blake2b-512",
81            Self::Blake2s256 => "blake2s-256",
82            Self::Blake3 => "blake3",
83            Self::Xxh3 => "xxh3",
84            Self::Xxh128 => "xxh128",
85        }
86    }
87
88    /// Return a human-readable algorithm name.
89    pub const fn display_name(self) -> &'static str {
90        match self {
91            Self::Md5 => "MD5",
92            Self::Sha1 => "SHA1",
93            Self::Sha224 => "SHA-224",
94            Self::Sha256 => "SHA-256",
95            Self::Sha384 => "SHA-384",
96            Self::Sha512 => "SHA-512",
97            Self::Sha3_224 => "SHA3-224",
98            Self::Sha3_256 => "SHA3-256",
99            Self::Sha3_384 => "SHA3-384",
100            Self::Sha3_512 => "SHA3-512",
101            Self::Blake2b512 => "BLAKE2b-512",
102            Self::Blake2s256 => "BLAKE2s-256",
103            Self::Blake3 => "BLAKE3",
104            Self::Xxh3 => "XXH3",
105            Self::Xxh128 => "XXH128",
106        }
107    }
108
109    /// Return the digest size in bytes.
110    pub const fn output_size(self) -> usize {
111        match self {
112            Self::Md5 | Self::Xxh128 => 16,
113            Self::Sha1 => 20,
114            Self::Sha224 | Self::Sha3_224 => 28,
115            Self::Sha256 | Self::Sha3_256 | Self::Blake2s256 | Self::Blake3 => 32,
116            Self::Sha384 | Self::Sha3_384 => 48,
117            Self::Sha512 | Self::Sha3_512 | Self::Blake2b512 => 64,
118            Self::Xxh3 => 8,
119        }
120    }
121
122    /// Return the Cargo feature that provides this implementation.
123    pub const fn required_feature(self) -> &'static str {
124        match self {
125            Self::Md5 => "md5",
126            Self::Sha1 => "sha1",
127            Self::Sha224 | Self::Sha256 | Self::Sha384 | Self::Sha512 => "sha2",
128            Self::Sha3_224 | Self::Sha3_256 | Self::Sha3_384 | Self::Sha3_512 => "sha3",
129            Self::Blake2b512 | Self::Blake2s256 => "blake2",
130            Self::Blake3 => "blake3",
131            Self::Xxh3 | Self::Xxh128 => "xxhash",
132        }
133    }
134
135    /// Return whether this algorithm was compiled into the current build.
136    pub const fn is_available(self) -> bool {
137        match self {
138            Self::Md5 => cfg!(feature = "md5"),
139            Self::Sha1 => cfg!(feature = "sha1"),
140            Self::Sha224 | Self::Sha256 | Self::Sha384 | Self::Sha512 => cfg!(feature = "sha2"),
141            Self::Sha3_224 | Self::Sha3_256 | Self::Sha3_384 | Self::Sha3_512 => {
142                cfg!(feature = "sha3")
143            }
144            Self::Blake2b512 | Self::Blake2s256 => cfg!(feature = "blake2"),
145            Self::Blake3 => cfg!(feature = "blake3"),
146            Self::Xxh3 | Self::Xxh128 => cfg!(feature = "xxhash"),
147        }
148    }
149
150    /// Construct a fresh streaming hasher for this algorithm.
151    ///
152    /// Returns [`HashUtilityError::AlgorithmUnavailable`] when the corresponding
153    /// Cargo feature is disabled.
154    pub fn hasher(self) -> Result<Box<dyn Hasher>, HashUtilityError> {
155        HashRegistry::get_hasher(self.canonical_name())
156    }
157}
158
159impl fmt::Display for Algorithm {
160    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
161        formatter.write_str(self.canonical_name())
162    }
163}
164
165impl FromStr for Algorithm {
166    type Err = HashUtilityError;
167
168    fn from_str(value: &str) -> Result<Self, Self::Err> {
169        let trimmed = value.trim();
170        match trimmed {
171            "md5" => Ok(Self::Md5),
172            "sha1" | "sha-1" => Ok(Self::Sha1),
173            "sha224" | "sha-224" => Ok(Self::Sha224),
174            "sha256" | "sha-256" => Ok(Self::Sha256),
175            "sha384" | "sha-384" => Ok(Self::Sha384),
176            "sha512" | "sha-512" => Ok(Self::Sha512),
177            "sha3-224" => Ok(Self::Sha3_224),
178            "sha3-256" => Ok(Self::Sha3_256),
179            "sha3-384" => Ok(Self::Sha3_384),
180            "sha3-512" => Ok(Self::Sha3_512),
181            "blake2b" | "blake2b-512" => Ok(Self::Blake2b512),
182            "blake2s" | "blake2s-256" => Ok(Self::Blake2s256),
183            "blake3" => Ok(Self::Blake3),
184            "xxh3" => Ok(Self::Xxh3),
185            "xxh128" => Ok(Self::Xxh128),
186            _ => parse_algorithm_case_insensitive(trimmed, value),
187        }
188    }
189}
190
191fn parse_algorithm_case_insensitive(
192    trimmed: &str,
193    original: &str,
194) -> Result<Algorithm, HashUtilityError> {
195    for algorithm in Algorithm::ALL {
196        if trimmed.eq_ignore_ascii_case(algorithm.canonical_name())
197            || trimmed.eq_ignore_ascii_case(algorithm.display_name())
198        {
199            return Ok(algorithm);
200        }
201    }
202    Err(HashUtilityError::UnsupportedAlgorithm {
203        algorithm: original.to_owned(),
204    })
205}
206
207#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize)]
208#[serde(rename_all = "kebab-case")]
209/// Selects complete or sampled file hashing.
210pub enum HashMode {
211    /// Hash the complete contents of the file.
212    #[default]
213    Full,
214    /// Hash three fixed-size samples of a large file for quick identification.
215    Sampled,
216}
217
218/// A validated binary digest coupled to its algorithm.
219#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
220pub struct DigestValue {
221    /// Algorithm that produced the digest.
222    pub algorithm: Algorithm,
223    pub(crate) bytes: Vec<u8>,
224}
225
226impl DigestValue {
227    /// Validate raw digest bytes and associate them with `algorithm`.
228    ///
229    /// The byte length must equal [`Algorithm::output_size`].
230    pub fn from_bytes(algorithm: Algorithm, bytes: Vec<u8>) -> Result<Self, HashUtilityError> {
231        if bytes.len() != algorithm.output_size() {
232            return Err(HashUtilityError::InvalidDigest {
233                algorithm: algorithm.to_string(),
234                reason: format!(
235                    "expected {} bytes, found {}",
236                    algorithm.output_size(),
237                    bytes.len()
238                ),
239            });
240        }
241        Ok(Self { algorithm, bytes })
242    }
243
244    /// Decode and validate a hexadecimal digest for `algorithm`.
245    pub fn from_hex(algorithm: Algorithm, value: &str) -> Result<Self, HashUtilityError> {
246        if value.len() != algorithm.output_size() * 2 {
247            return Err(HashUtilityError::InvalidDigest {
248                algorithm: algorithm.to_string(),
249                reason: format!(
250                    "expected {} hexadecimal characters, found {}",
251                    algorithm.output_size() * 2,
252                    value.len()
253                ),
254            });
255        }
256        let bytes = value
257            .as_bytes()
258            .as_chunks::<2>()
259            .0
260            .iter()
261            .map(|pair| {
262                let text = std::str::from_utf8(pair).expect("hexadecimal text is ASCII");
263                u8::from_str_radix(text, 16).map_err(|_| HashUtilityError::InvalidDigest {
264                    algorithm: algorithm.to_string(),
265                    reason: "digest contains a non-hexadecimal character".to_owned(),
266                })
267            })
268            .collect::<Result<Vec<_>, _>>()?;
269        Ok(Self { algorithm, bytes })
270    }
271
272    /// Encode the digest as lowercase hexadecimal text.
273    pub fn to_hex(&self) -> String {
274        bytes_to_hex(&self.bytes)
275    }
276
277    /// Borrow the validated binary digest.
278    pub fn as_bytes(&self) -> &[u8] {
279        &self.bytes
280    }
281}
282
283/// Information about a hash algorithm
284#[derive(Debug, Clone, serde::Serialize)]
285#[non_exhaustive]
286pub struct AlgorithmInfo {
287    /// Human-readable algorithm name.
288    pub name: String,
289    /// Digest size in bits.
290    pub output_bits: usize,
291    /// Whether the registry classifies the algorithm as post-quantum resistant.
292    pub post_quantum: bool,
293    /// Whether the algorithm is intended to provide cryptographic hashing.
294    pub cryptographic: bool,
295}