umbral_pre/
traits.rs

1#[cfg(feature = "default-serialization")]
2use alloc::boxed::Box;
3
4use core::fmt;
5
6#[cfg(feature = "default-serialization")]
7use serde::{Deserialize, Serialize};
8
9/// The provided bytestring is of an incorrect size.
10#[derive(Debug, PartialEq, Eq)]
11pub struct SizeMismatchError {
12    pub(crate) received_size: usize,
13    pub(crate) expected_size: usize,
14}
15
16impl SizeMismatchError {
17    /// Creates a new `SizeMismatchError`.
18    pub fn new(received_size: usize, expected_size: usize) -> Self {
19        Self {
20            received_size,
21            expected_size,
22        }
23    }
24}
25
26impl fmt::Display for SizeMismatchError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(
29            f,
30            "Bytestring size mismatch: expected {} bytes, got {}",
31            self.expected_size, self.received_size
32        )
33    }
34}
35
36/// A `fmt` implementation for types with secret data.
37pub(crate) fn fmt_secret(type_name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38    write!(f, "{type_name}:...")
39}
40
41/// A `fmt` implementation for types with public data.
42pub(crate) fn fmt_public(
43    type_name: &str,
44    data_to_show: &impl AsRef<[u8]>,
45    f: &mut fmt::Formatter<'_>,
46) -> fmt::Result {
47    let bytes = data_to_show.as_ref();
48    let bytes = if bytes.len() > 8 { &bytes[..8] } else { bytes };
49    write!(f, "{}:{}", type_name, hex::encode(bytes),)
50}
51
52/// Default serialization of an object that is used in all the bindings.
53/// Uses MessagePack format.
54#[cfg(feature = "default-serialization")]
55pub trait DefaultSerialize: Serialize {
56    /// Serializes this object.
57    fn to_bytes(&self) -> Result<Box<[u8]>, rmp_serde::encode::Error> {
58        rmp_serde::to_vec(self).map(|v| v.into_boxed_slice())
59    }
60}
61
62/// Default deserialization of an object that is used in all the bindings.
63/// Uses MessagePack format.
64#[cfg(feature = "default-serialization")]
65pub trait DefaultDeserialize<'de>: Deserialize<'de> {
66    /// Deserializes a bytestring into this object.
67    fn from_bytes(bytes: &'de [u8]) -> Result<Self, rmp_serde::decode::Error> {
68        rmp_serde::from_slice(bytes)
69    }
70}