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
3use serde::de::{Error, Visitor};
4use serde::{Deserializer, Serializer};
5use std::fmt;
6
7/// 24-byte XChaCha20 nonces stored in enrollment records.
8pub mod nonce_bytes {
9    use super::*;
10
11    pub fn serialize<S: Serializer>(bytes: &[u8; 24], s: S) -> Result<S::Ok, S::Error> {
12        s.serialize_bytes(bytes)
13    }
14
15    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 24], D::Error> {
16        struct V;
17        impl<'de> Visitor<'de> for V {
18            type Value = [u8; 24];
19            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
20                write!(f, "exactly 24 bytes")
21            }
22            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
23                v.try_into().map_err(|_| E::invalid_length(v.len(), &"24"))
24            }
25        }
26        d.deserialize_bytes(V)
27    }
28}
29
30pub mod sig_bytes {
31    use super::*;
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<'de> Visitor<'de> 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}