Skip to main content

tls_codec/
arrays.rs

1//! Implement the TLS codec for some byte arrays.
2
3use alloc::vec::Vec;
4
5use crate::{Deserialize, DeserializeBytes, Error, Serialize, SerializeBytes, Size};
6
7#[cfg(feature = "std")]
8use std::io::{Read, Write};
9
10impl<const LEN: usize> Serialize for [u8; LEN] {
11    #[cfg(feature = "std")]
12    #[inline]
13    fn tls_serialize<W: Write>(&self, writer: &mut W) -> Result<usize, Error> {
14        writer.write_all(self)?;
15        Ok(LEN)
16    }
17}
18
19impl<const LEN: usize> Deserialize for [u8; LEN] {
20    #[cfg(feature = "std")]
21    #[inline]
22    fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, Error> {
23        let mut out = [0u8; LEN];
24        bytes.read_exact(&mut out)?;
25        Ok(out)
26    }
27}
28
29impl<const LEN: usize> DeserializeBytes for [u8; LEN] {
30    #[inline]
31    fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
32        let out = bytes
33            .get(..LEN)
34            .ok_or(Error::EndOfStream)?
35            .try_into()
36            .map_err(|_| Error::EndOfStream)?;
37        Ok((out, &bytes[LEN..]))
38    }
39}
40
41impl<const LEN: usize> SerializeBytes for [u8; LEN] {
42    fn tls_serialize_bytes(&self) -> Result<Vec<u8>, Error> {
43        Ok(self.to_vec())
44    }
45}
46
47impl<const LEN: usize> Size for [u8; LEN] {
48    #[inline]
49    fn tls_serialized_len(&self) -> usize {
50        LEN
51    }
52}