nix_compat/nixhash/
algos.rs

1use std::fmt::Display;
2
3use serde::{Deserialize, Serialize};
4
5use crate::nixhash::Error;
6
7/// This are the hash algorithms supported by cppnix.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum HashAlgo {
10    Md5,
11    Sha1,
12    Sha256,
13    Sha512,
14}
15
16impl HashAlgo {
17    // return the number of bytes in the digest of the given hash algo.
18    pub fn digest_length(&self) -> usize {
19        match self {
20            HashAlgo::Sha1 => 20,
21            HashAlgo::Sha256 => 32,
22            HashAlgo::Sha512 => 64,
23            HashAlgo::Md5 => 16,
24        }
25    }
26}
27
28impl Display for HashAlgo {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match &self {
31            HashAlgo::Md5 => write!(f, "md5"),
32            HashAlgo::Sha1 => write!(f, "sha1"),
33            HashAlgo::Sha256 => write!(f, "sha256"),
34            HashAlgo::Sha512 => write!(f, "sha512"),
35        }
36    }
37}
38
39impl Serialize for HashAlgo {
40    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
41    where
42        S: serde::Serializer,
43    {
44        serializer.collect_str(&self)
45    }
46}
47
48impl<'de> Deserialize<'de> for HashAlgo {
49    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
50    where
51        D: serde::Deserializer<'de>,
52    {
53        let s: &str = Deserialize::deserialize(deserializer)?;
54        HashAlgo::try_from(s).map_err(serde::de::Error::custom)
55    }
56}
57
58/// TODO(Raito): this could be automated via macros, I suppose.
59/// But this may be more expensive than just doing it by hand
60/// and ensuring that is kept in sync.
61pub const SUPPORTED_ALGOS: [&str; 4] = ["md5", "sha1", "sha256", "sha512"];
62
63impl TryFrom<&str> for HashAlgo {
64    type Error = Error;
65
66    fn try_from(algo_str: &str) -> Result<Self, Self::Error> {
67        match algo_str {
68            "md5" => Ok(Self::Md5),
69            "sha1" => Ok(Self::Sha1),
70            "sha256" => Ok(Self::Sha256),
71            "sha512" => Ok(Self::Sha512),
72            _ => Err(Error::InvalidAlgo(algo_str.to_string())),
73        }
74    }
75}