kyber_rs/encoding/
encodings.rs1use serde::{Deserialize, Serialize};
2use std::{fmt::Debug, io};
3use thiserror::Error;
4
5use crate::cipher::Stream;
6
7pub trait Marshaling: BinaryMarshaler + BinaryUnmarshaler {
13 fn marshal_size(&self) -> usize;
15
16 fn marshal_to(&self, w: &mut impl io::Write) -> Result<(), MarshallingError>;
18
19 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 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}