Skip to main content

ftth_rsip/headers/auth/
algorithm.rs

1/// The `Algorithm`, as part of the SIP Authorization framework, found in headers like
2/// [Authorization](super::super::typed::Authorization) and
3/// [WwwAuthenticate](super::super::typed::WwwAuthenticate)
4#[derive(Debug, PartialEq, Eq, Clone, Copy)]
5pub enum Algorithm {
6    Md5,
7    Md5Sess,
8    Sha256,
9    Sha256Sess,
10    Sha512,
11    Sha512Sess,
12}
13
14impl Default for Algorithm {
15    fn default() -> Self {
16        Self::Sha256
17    }
18}
19
20impl std::fmt::Display for Algorithm {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            Self::Md5 => write!(f, "MD5"),
24            Self::Md5Sess => write!(f, "MD5-sess"),
25            Self::Sha256 => write!(f, "SHA256"),
26            Self::Sha256Sess => write!(f, "SHA256-sess"),
27            Self::Sha512 => write!(f, "SHA512"),
28            Self::Sha512Sess => write!(f, "SHA512-sess"),
29        }
30    }
31}
32
33impl std::str::FromStr for Algorithm {
34    type Err = crate::Error;
35
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        use std::convert::TryInto;
38
39        s.try_into()
40    }
41}
42
43impl std::convert::TryFrom<&str> for Algorithm {
44    type Error = crate::Error;
45
46    fn try_from(s: &str) -> Result<Self, Self::Error> {
47        match s {
48            s if s.eq_ignore_ascii_case("md5") => Ok(Self::Md5),
49            s if s.eq_ignore_ascii_case("md5-sess") => Ok(Self::Md5Sess),
50            s if s.eq_ignore_ascii_case("sha256") => Ok(Self::Sha256),
51            s if s.eq_ignore_ascii_case("sha256-sess") => Ok(Self::Sha256Sess),
52            s if s.eq_ignore_ascii_case("sha512") => Ok(Self::Sha512),
53            s if s.eq_ignore_ascii_case("sha512-sess") => Ok(Self::Sha512Sess),
54            s => Err(crate::Error::ParseError(format!(
55                "invalid Algorithm `{}`",
56                s
57            ))),
58        }
59    }
60}