singlefile_formats/data/
cbor_serde.rs

1#![cfg_attr(docsrs, doc(cfg(feature = "cbor-serde")))]
2#![cfg(feature = "cbor-serde")]
3
4//! Defines a [`FileFormat`] using the CBOR binary data format.
5
6pub extern crate ciborium as original;
7
8use serde::ser::Serialize;
9use serde::de::DeserializeOwned;
10use singlefile::FileFormat;
11use thiserror::Error;
12
13use std::io::{Read, Write};
14
15/// An error that can occur while using [`Cbor`].
16#[derive(Debug, Error)]
17pub enum CborError {
18  /// An error occurred while serializing.
19  #[error(transparent)]
20  SerializeError(#[from] ciborium::ser::Error<std::io::Error>),
21  /// An error occurred while deserializing.
22  #[error(transparent)]
23  DeserializeError(#[from] ciborium::de::Error<std::io::Error>)
24}
25
26/// A [`FileFormat`] corresponding to the CBOR binary data format.
27/// Implemented using the [`ciborium`] crate, only compatible with [`serde`] types.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub struct Cbor;
30
31impl<T> FileFormat<T> for Cbor
32where T: Serialize + DeserializeOwned {
33  type FormatError = CborError;
34
35  fn from_reader<R: Read>(&self, reader: R) -> Result<T, Self::FormatError> {
36    ciborium::de::from_reader(reader).map_err(From::from)
37  }
38
39  fn to_writer<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError> {
40    ciborium::ser::into_writer(value, writer).map_err(From::from)
41  }
42}
43
44/// A shortcut type to a [`Compressed`][crate::compression::Compressed] [`Cbor`].
45/// Provides a single parameter for compression format.
46#[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
47#[cfg(feature = "compression")]
48pub type CompressedCbor<C> = crate::compression::Compressed<C, Cbor>;