1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use crate::prelude::*;

use alloc::vec::Vec;

pub use bytes::Bytes as OctetString;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FixedOctetString<const N: usize>([u8; N]);

impl<const N: usize> FixedOctetString<N> {
    pub fn new(value: [u8; N]) -> Self {
        Self(value)
    }
}

impl<const N: usize> From<[u8; N]> for FixedOctetString<N> {
    fn from(value: [u8; N]) -> Self {
        Self::new(value)
    }
}

impl<const N: usize> TryFrom<Vec<u8>> for FixedOctetString<N> {
    type Error = <[u8; N] as TryFrom<Vec<u8>>>::Error;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        value.try_into().map(Self)
    }
}

impl<const N: usize> TryFrom<&[u8]> for FixedOctetString<N> {
    type Error = <[u8; N] as TryFrom<&'static [u8]>>::Error;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        value.try_into().map(Self)
    }
}

impl<const N: usize> TryFrom<OctetString> for FixedOctetString<N> {
    type Error = <[u8; N] as TryFrom<&'static [u8]>>::Error;

    fn try_from(value: OctetString) -> Result<Self, Self::Error> {
        (&*value).try_into().map(Self)
    }
}

impl<const N: usize> core::ops::Deref for FixedOctetString<N> {
    type Target = [u8; N];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const N: usize> core::ops::DerefMut for FixedOctetString<N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const N: usize> AsnType for FixedOctetString<N> {
    const TAG: Tag = Tag::OCTET_STRING;
    const CONSTRAINTS: Constraints<'static> = Constraints::new(&[Constraint::Size(
        Extensible::new(constraints::Size::fixed(N)),
    )]);
}

impl<const N: usize> Decode for FixedOctetString<N> {
    fn decode_with_tag_and_constraints<D: Decoder>(
        decoder: &mut D,
        tag: Tag,
        constraints: Constraints,
    ) -> Result<Self, D::Error> {
        decoder
            .decode_octet_string(tag, constraints)?
            .try_into()
            .map(Self)
            .map_err(|vec| {
                D::Error::from(crate::error::DecodeError::fixed_string_conversion_failed(
                    Tag::OCTET_STRING,
                    vec.len(),
                    N,
                    decoder.codec(),
                ))
            })
    }
}

impl<const N: usize> Encode for FixedOctetString<N> {
    fn encode_with_tag_and_constraints<E: Encoder>(
        &self,
        encoder: &mut E,
        tag: Tag,
        constraints: Constraints,
    ) -> Result<(), E::Error> {
        encoder
            .encode_octet_string(tag, constraints, &self.0)
            .map(drop)
    }
}