Skip to main content

ssh_key/certificate/
cert_type.rs

1//! OpenSSH certificate types.
2
3use crate::{Error, Result};
4use encoding::{Decode, Encode, Reader, Writer};
5
6/// Types of OpenSSH certificates: user or host.
7#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
8#[repr(u32)]
9#[derive(Default)]
10pub enum CertType {
11    /// User certificate
12    #[default]
13    User = 1,
14
15    /// Host certificate
16    Host = 2,
17}
18
19impl CertType {
20    /// Is this a host certificate?
21    #[must_use]
22    pub fn is_host(self) -> bool {
23        self == CertType::Host
24    }
25
26    /// Is this a user certificate?
27    #[must_use]
28    pub fn is_user(self) -> bool {
29        self == CertType::User
30    }
31}
32
33impl Decode for CertType {
34    type Error = Error;
35
36    fn decode(reader: &mut impl Reader) -> Result<Self> {
37        u32::decode(reader)?.try_into()
38    }
39}
40
41impl Encode for CertType {
42    fn encoded_len(&self) -> encoding::Result<usize> {
43        Ok(4)
44    }
45
46    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
47        u32::from(*self).encode(writer)?;
48        Ok(())
49    }
50}
51
52impl From<CertType> for u32 {
53    #[allow(clippy::as_conversions, reason = "repr(u32) enum")]
54    fn from(cert_type: CertType) -> u32 {
55        cert_type as u32
56    }
57}
58
59impl TryFrom<u32> for CertType {
60    type Error = Error;
61
62    fn try_from(n: u32) -> Result<CertType> {
63        match n {
64            1 => Ok(CertType::User),
65            2 => Ok(CertType::Host),
66            _ => Err(Error::FormatEncoding),
67        }
68    }
69}