Skip to main content

p2panda_core/
cbor.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Utility methods to encode or decode values in [CBOR] format.
4//!
5//! As per p2panda specification data-types like operation headers are encoded in the Concise
6//! Binary Object Representation (CBOR) format.
7//!
8//! [CBOR]: https://cbor.io/
9use std::io::Read;
10use std::sync::Arc;
11
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15/// Serializes a value into CBOR format.
16pub fn encode_cbor<T: Serialize>(value: &T) -> Result<Vec<u8>, EncodeError> {
17    let value = cbor_core::Value::serialized(&value)?;
18    Ok(value.encode())
19}
20
21/// Deserializes a value which was formatted in CBOR.
22pub fn decode_cbor<T: for<'a> Deserialize<'a>, R: Read>(reader: R) -> Result<T, DecodeError> {
23    let value =
24        cbor_core::Value::read_from(reader).map_err(|err| DecodeError::Io(Arc::new(err)))?;
25    Ok(cbor_core::Value::deserialized(&value)?)
26}
27
28/// An error occurred during CBOR serialization.
29#[derive(Debug, Error)]
30#[error(transparent)]
31pub struct EncodeError(#[from] cbor_core::SerdeError);
32
33/// An error occurred during CBOR deserialization.
34#[derive(Clone, Debug, Error)]
35pub enum DecodeError {
36    /// An error occurred while reading bytes.
37    ///
38    /// Contains the underlying error returned while reading.
39    #[error("an error occurred while reading bytes: {0}")]
40    Io(Arc<cbor_core::IoError>),
41
42    #[error(transparent)]
43    Serde(#[from] cbor_core::SerdeError),
44}