ssri/
algorithm.rs

1use std::fmt;
2
3use crate::errors::Error;
4
5/**
6Valid algorithms for integrity strings.
7
8`Sha1` and `Xxh3` are special cases in this library--they're not allowed by the
9current SRI spec, but they're useful enough that having first-class support
10makes sense. They should also be completely harmless to have in your strings
11if you do use it in a browser context--they just won't be used.
12*/
13#[non_exhaustive]
14#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub enum Algorithm {
16    Sha512,
17    Sha384,
18    Sha256,
19    Sha1,
20    /// xxh3 is a non-cryptographic hash function that is very fast and can be
21    /// used to speed up integrity calculations, at the cost of
22    /// cryptographically-secure guarantees.
23    ///
24    /// `ssri` uses 128-bit xxh3 hashes, which have been shown to have no
25    /// conflicts even on billions of hashes.
26    Xxh3,
27}
28
29impl fmt::Display for Algorithm {
30    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31        write!(f, "{}", format!("{:?}", self).to_lowercase())
32    }
33}
34
35impl std::str::FromStr for Algorithm {
36    type Err = Error;
37
38    fn from_str(s: &str) -> Result<Algorithm, Self::Err> {
39        match s {
40            "sha1" => Ok(Algorithm::Sha1),
41            "sha256" => Ok(Algorithm::Sha256),
42            "sha384" => Ok(Algorithm::Sha384),
43            "sha512" => Ok(Algorithm::Sha512),
44            "xxh3" => Ok(Algorithm::Xxh3),
45            _ => Err(Error::ParseIntegrityError(s.into())),
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::Algorithm::*;
53
54    #[test]
55    fn algorithm_formatting() {
56        assert_eq!(format!("{}", Sha1), "sha1");
57        assert_eq!(format!("{}", Sha256), "sha256");
58        assert_eq!(format!("{}", Sha384), "sha384");
59        assert_eq!(format!("{}", Sha512), "sha512");
60        assert_eq!(format!("{}", Xxh3), "xxh3");
61    }
62
63    #[test]
64    fn ordering() {
65        let mut arr = [Sha1, Sha256, Sha384, Sha512, Xxh3];
66        arr.sort_unstable();
67        assert_eq!(arr, [Sha512, Sha384, Sha256, Sha1, Xxh3])
68    }
69}