Skip to main content

zlicenser_protocol/wire/
bytes.rs

1// serde helpers for fixed-size byte arrays, keeps CBOR major type 2 (byte string) on the wire
2
3/// 24-byte XChaCha20 nonces stored in enrollment records.
4pub mod nonce_bytes {
5    use serde::de::{Error, Visitor};
6    use serde::{Deserializer, Serializer};
7    use std::fmt;
8
9    pub fn serialize<S: Serializer>(bytes: &[u8; 24], s: S) -> Result<S::Ok, S::Error> {
10        s.serialize_bytes(bytes)
11    }
12
13    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 24], D::Error> {
14        struct V;
15        impl Visitor<'_> for V {
16            type Value = [u8; 24];
17            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
18                write!(f, "exactly 24 bytes")
19            }
20            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
21                v.try_into().map_err(|_| E::invalid_length(v.len(), &"24"))
22            }
23        }
24        d.deserialize_bytes(V)
25    }
26}
27
28pub mod sig_bytes {
29    use serde::de::{Error, Visitor};
30    use serde::{Deserializer, Serializer};
31    use std::fmt;
32
33    pub fn serialize<S: Serializer>(bytes: &[u8; 64], s: S) -> Result<S::Ok, S::Error> {
34        s.serialize_bytes(bytes)
35    }
36
37    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 64], D::Error> {
38        struct V;
39        impl Visitor<'_> for V {
40            type Value = [u8; 64];
41            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
42                write!(f, "exactly 64 bytes")
43            }
44            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
45                v.try_into().map_err(|_| E::invalid_length(v.len(), &"64"))
46            }
47        }
48        d.deserialize_bytes(V)
49    }
50}