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 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 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 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}