nix_compat/nixhash/
algos.rs1use std::fmt::Display;
2use std::str::FromStr;
3
4#[cfg(feature = "serde")]
5use serde_with::{DeserializeFromStr, SerializeDisplay};
6
7use crate::nixhash::Error;
8
9#[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 pub const fn digest_length(&self) -> usize {
22 match self {
23 HashAlgo::Sha1 => 20,
24 HashAlgo::Sha256 => 32,
25 HashAlgo::Sha512 => 64,
26 HashAlgo::Md5 => 16,
27 }
28 }
29}
30
31impl Display for HashAlgo {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 match &self {
34 HashAlgo::Md5 => write!(f, "md5"),
35 HashAlgo::Sha1 => write!(f, "sha1"),
36 HashAlgo::Sha256 => write!(f, "sha256"),
37 HashAlgo::Sha512 => write!(f, "sha512"),
38 }
39 }
40}
41
42#[cfg(feature = "serde")]
43pub const SUPPORTED_ALGOS: [&str; 4] = ["md5", "sha1", "sha256", "sha512"];
44
45impl FromStr for HashAlgo {
46 type Err = Error;
47
48 fn from_str(algo_str: &str) -> Result<Self, Self::Err> {
49 match algo_str {
50 "md5" => Ok(Self::Md5),
51 "sha1" => Ok(Self::Sha1),
52 "sha256" => Ok(Self::Sha256),
53 "sha512" => Ok(Self::Sha512),
54 _ => Err(Error::InvalidAlgo),
55 }
56 }
57}
58
59impl TryFrom<&str> for HashAlgo {
60 type Error = Error;
61 fn try_from(algo_str: &str) -> Result<Self, Self::Error> {
62 algo_str.parse()
63 }
64}