kyber_rs/encoding/
encodings.rs

1use serde::{Deserialize, Serialize};
2use std::{fmt::Debug, io};
3use thiserror::Error;
4
5use crate::cipher::Stream;
6
7/// [`Marshaling`] is a basic interface representing fixed-length (or known-length)
8/// cryptographic objects or structures having a built-in binary encoding.
9/// Implementors must ensure that calls to these methods do not modify
10/// the underlying object so that other users of the object can access
11/// it concurrently.
12pub trait Marshaling: BinaryMarshaler + BinaryUnmarshaler {
13    /// Encoded length of this object in bytes.
14    fn marshal_size(&self) -> usize;
15
16    /// Encode the contents of this object and write it to an [`io::Write`].
17    fn marshal_to(&self, w: &mut impl io::Write) -> Result<(), MarshallingError>;
18
19    /// Decode the content of this object by reading from a [`io::Read`].
20    /// If `r` is an [`XOF`], it uses `r` to pick a valid object pseudo-randomly,
21    /// which may entail reading more than `len` bytes due to retries.
22    fn unmarshal_from(&mut self, r: &mut impl io::Read) -> Result<(), MarshallingError>;
23    fn unmarshal_from_random(&mut self, r: &mut (impl io::Read + Stream));
24
25    /// [`marshal_id()`] returns the type tag used in encoding/decoding
26    fn marshal_id(&self) -> [u8; 8];
27}
28
29#[derive(Error, Debug)]
30pub enum MarshallingError {
31    #[error("could not serialize data")]
32    Serialization(bincode::Error),
33    #[error("could not deserialize data")]
34    Deserialization(bincode::Error),
35    #[error("input data is not valid")]
36    InvalidInput(String),
37    #[error("io error")]
38    IoError(#[from] std::io::Error),
39}
40
41pub trait BinaryMarshaler {
42    fn marshal_binary(&self) -> Result<Vec<u8>, MarshallingError>;
43}
44
45pub trait BinaryUnmarshaler {
46    fn unmarshal_binary(&mut self, data: &[u8]) -> Result<(), MarshallingError>;
47}
48
49pub fn marshal_binary<T: Serialize>(x: &T) -> Result<Vec<u8>, MarshallingError> {
50    bincode::serialize(x).map_err(MarshallingError::Serialization)
51}
52
53pub fn unmarshal_binary<'de, T: Deserialize<'de>>(
54    x: &mut T,
55    data: &'de [u8],
56) -> Result<(), MarshallingError> {
57    *x = bincode::deserialize(data).map_err(MarshallingError::Deserialization)?;
58    Ok(())
59}