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 pot;
19
use serde::{de::DeserializeOwned, Deserialize, Serialize};
20
pub use transmog;
21
use transmog::{BorrowedDeserializer, Format, OwnedDeserializer};
22

            
23
/// Pot implementor of [`Format`].
24
26
#[derive(Clone, Default)]
25
pub struct Pot(pot::Config);
26

            
27
impl From<pot::Config> for Pot {
28
1
    fn from(config: pot::Config) -> Self {
29
1
        Self(config)
30
1
    }
31
}
32

            
33
impl<'a, T> Format<'a, T> for Pot
34
where
35
    T: Serialize,
36
{
37
    type Error = pot::Error;
38

            
39
6
    fn serialize(&self, value: &T) -> Result<Vec<u8>, Self::Error> {
40
6
        self.0.serialize(value)
41
6
    }
42

            
43
10
    fn serialize_into<W: Write>(&self, value: &T, writer: W) -> Result<(), Self::Error> {
44
10
        self.0.serialize_into(value, writer)
45
10
    }
46
}
47

            
48
impl<'a, T> BorrowedDeserializer<'a, T> for Pot
49
where
50
    T: Serialize + Deserialize<'a>,
51
{
52
1
    fn deserialize_borrowed(&self, data: &'a [u8]) -> Result<T, Self::Error> {
53
1
        self.0.deserialize(data)
54
1
    }
55
}
56

            
57
impl<T> OwnedDeserializer<T> for Pot
58
where
59
    T: Serialize + DeserializeOwned,
60
{
61
14
    fn deserialize_owned(&self, data: &[u8]) -> Result<T, Self::Error> {
62
14
        self.0.deserialize(data)
63
14
    }
64
2
    fn deserialize_from<R: Read>(&self, reader: R) -> Result<T, Self::Error> {
65
2
        self.0.deserialize_from(reader)
66
2
    }
67
}
68

            
69
1
#[test]
70
1
fn format_tests() {
71
1
    transmog::test_util::test_format(&Pot::default());
72
1
    transmog::test_util::test_format(&Pot::from(pot::Config::default().allocation_budget(64)));
73
1
}
74

            
75
1
#[test]
76
1
fn borrowed_deserialization() {
77
1
    use std::borrow::Cow;
78
4
    #[derive(Serialize, Deserialize)]
79
1
    struct Test<'a> {
80
1
        #[serde(borrow)]
81
1
        value: Cow<'a, str>,
82
1
    }
83
1
    let pot = Pot::default();
84
1
    let value: Test<'static> = Test {
85
1
        value: Cow::Owned(String::from("hello")),
86
1
    };
87
1
    let serialized = pot.serialize(&value).unwrap();
88
1
    let pot = Pot::default();
89
1
    let deserialized: Test<'_> = pot.deserialize_borrowed(&serialized).unwrap();
90
1
    assert_eq!(deserialized.value, "hello");
91
1
    assert!(matches!(deserialized.value, Cow::Borrowed(_)));
92
1
}