1
#![doc = include_str!("./.crate-docs.md")]
2
#![forbid(unsafe_code)]
3
#![warn(
4
    clippy::cargo,
5
    missing_docs,
6
    // clippy::missing_docs_in_private_items,
7
    clippy::pedantic,
8
    future_incompatible,
9
    rust_2018_idioms,
10
)]
11
#![allow(
12
    clippy::missing_errors_doc, // TODO clippy::missing_errors_doc
13
    clippy::option_if_let_else,
14
)]
15

            
16
use std::io::{Read, Write};
17

            
18
pub use ciborium;
19
use serde::{de::DeserializeOwned, Serialize};
20
pub use transmog;
21
use transmog::{Format, OwnedDeserializer};
22

            
23
/// CBOR implementor of [`Format`].
24
1
#[derive(Clone, Default)]
25
pub struct Cbor;
26

            
27
impl<'a, T> Format<'a, T> for Cbor
28
where
29
    T: Serialize,
30
{
31
    type Error = Error;
32

            
33
3
    fn serialize_into<W: Write>(&self, value: &T, writer: W) -> Result<(), Self::Error> {
34
3
        ciborium::ser::into_writer(value, writer).map_err(Error::from)
35
3
    }
36
}
37

            
38
impl<T> OwnedDeserializer<T> for Cbor
39
where
40
    T: Serialize + DeserializeOwned,
41
{
42
2
    fn deserialize_owned(&self, data: &[u8]) -> Result<T, Self::Error> {
43
2
        self.deserialize_from(data)
44
2
    }
45

            
46
3
    fn deserialize_from<R: Read>(&self, reader: R) -> Result<T, Self::Error> {
47
3
        ciborium::de::from_reader(reader).map_err(Error::from)
48
3
    }
49
}
50

            
51
/// CBOR serialization and deserialization errors.
52
1
#[derive(thiserror::Error, Debug)]
53
pub enum Error {
54
    /// A serialization-related error.
55
    #[error("serialization error: {0}")]
56
    Serialization(#[from] ciborium::ser::Error<std::io::Error>),
57
    /// A deserialization-related error.
58
    #[error("serialization error: {0}")]
59
    Deserialization(#[from] ciborium::de::Error<std::io::Error>),
60
}
61

            
62
impl From<std::io::Error> for Error {
63
1
    fn from(err: std::io::Error) -> Self {
64
1
        Error::Serialization(ciborium::ser::Error::Io(err))
65
1
    }
66
}
67

            
68
1
#[test]
69
1
fn format_tests() {
70
1
    transmog::test_util::test_format(&Cbor);
71
1
}