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        let written = writer.write(self)?;
15        if written == LEN {
16            Ok(written)
17        } else {
18            Err(Error::InvalidWriteLength(format!(
19                "Expected to write {LEN} bytes but only {written} were written."
20            )))
21        }
22    }
23}
24
25impl<const LEN: usize> Deserialize for [u8; LEN] {
26    #[cfg(feature = "std")]
27    #[inline]
28    fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, Error> {
29        let mut out = [0u8; LEN];
30        bytes.read_exact(&mut out)?;
31        Ok(out)
32    }
33}
34
35impl<const LEN: usize> DeserializeBytes for [u8; LEN] {
36    #[inline]
37    fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
38        let out = bytes
39            .get(..LEN)
40            .ok_or(Error::EndOfStream)?
41            .try_into()
42            .map_err(|_| Error::EndOfStream)?;
43        Ok((out, &bytes[LEN..]))
44    }
45}
46
47impl<const LEN: usize> SerializeBytes for [u8; LEN] {
48    fn tls_serialize(&self) -> Result<Vec<u8>, Error> {
49        Ok(self.to_vec())
50    }
51}
52
53impl<const LEN: usize> Size for [u8; LEN] {
54    #[inline]
55    fn tls_serialized_len(&self) -> usize {
56        LEN
57    }
58}