Skip to main content

nix_compat/nixhash/
algos.rs

1use std::fmt::Display;
2use std::str::FromStr;
3
4#[cfg(feature = "serde")]
5use serde_with::{DeserializeFromStr, SerializeDisplay};
6
7use crate::nixhash::Error;
8
9/// This are the hash algorithms supported by cppnix.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11#[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
12pub enum HashAlgo {
13    Md5,
14    Sha1,
15    Sha256,
16    Sha512,
17}
18
19impl HashAlgo {
20    // return the algo name as a &'static str.
21    pub const fn as_str(&self) -> &'static str {
22        match self {
23            HashAlgo::Md5 => "md5",
24            HashAlgo::Sha1 => "sha1",
25            HashAlgo::Sha256 => "sha256",
26            HashAlgo::Sha512 => "sha512",
27        }
28    }
29
30    // return the prefix this would have in the SRI case.
31    pub const fn sri_prefix(&self) -> &'static str {
32        match self {
33            HashAlgo::Md5 => "md5-",
34            HashAlgo::Sha1 => "sha1-",
35            HashAlgo::Sha256 => "sha256-",
36            HashAlgo::Sha512 => "sha512-",
37        }
38    }
39
40    // return the number of bytes in the digest of the given hash algo.
41    pub const fn digest_length(&self) -> usize {
42        match self {
43            HashAlgo::Sha1 => 20,
44            HashAlgo::Sha256 => 32,
45            HashAlgo::Sha512 => 64,
46            HashAlgo::Md5 => 16,
47        }
48    }
49}
50
51impl Display for HashAlgo {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "{}", self.as_str())
54    }
55}
56
57impl FromStr for HashAlgo {
58    type Err = Error;
59
60    fn from_str(algo_str: &str) -> Result<Self, Self::Err> {
61        match algo_str {
62            "md5" => Ok(Self::Md5),
63            "sha1" => Ok(Self::Sha1),
64            "sha256" => Ok(Self::Sha256),
65            "sha512" => Ok(Self::Sha512),
66            _ => Err(Error::InvalidAlgo(algo_str.to_string())),
67        }
68    }
69}
70
71impl TryFrom<&str> for HashAlgo {
72    type Error = Error;
73    fn try_from(algo_str: &str) -> Result<Self, Self::Error> {
74        algo_str.parse()
75    }
76}