koit/
format.rs

1//! Formats handle transforming structured data to and from bytes for persisting.
2
3/// Trait implementable by format providers.
4///
5/// By implementing this trait, a type becomes a marker for the specified format.
6/// That type can then be used for formatting (without instantiating an object of that type).
7pub trait Format<T>: Sized {
8    type Error: std::error::Error + Send + Sync + 'static;
9
10    /// Convert data to bytes.
11    ///
12    /// # Errors
13    ///
14    /// If the data failed to be encoded by the format, an error variant is returned.
15    fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error>;
16
17    /// Convert bytes to data.
18    ///
19    /// # Errors
20    ///
21    /// If the bytes failed to be decoded by the format, an error variant is returned.
22    fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error>;
23}
24
25#[cfg(feature = "json-format")]
26pub use self::json::Json;
27
28#[cfg(feature = "bincode-format")]
29pub use self::bincode::Bincode;
30
31
32#[cfg(feature = "json-format")]
33mod json {
34    use serde::{de::DeserializeOwned, Serialize};
35
36    use super::Format;
37
38    #[cfg_attr(docsrs, doc(cfg(feature = "json-format")))]
39    /// A pretty-printed JSON [`Format`](crate::format::Format).
40    #[derive(Debug, std::default::Default)]
41    pub struct Json;
42
43    impl<T: DeserializeOwned + Serialize> Format<T> for Json {
44        type Error = serde_json::Error;
45
46        fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
47            Ok(serde_json::to_vec_pretty(value)?)
48        }
49        fn from_bytes(data: Vec<u8>) -> Result<T, serde_json::Error> {
50            Ok(serde_json::from_slice(&data)?)
51        }
52    }
53}
54
55#[cfg(feature = "bincode-format")]
56mod bincode {
57    use serde::{de::DeserializeOwned, Serialize};
58
59    use super::Format;
60
61    #[cfg_attr(docsrs, doc(cfg(feature = "bincode-format")))]
62    /// A Bincode [`Format`](crate::format::Format).
63    #[derive(Debug, std::default::Default)]
64    pub struct Bincode;
65
66    impl<T: Serialize + DeserializeOwned> Format<T> for Bincode {
67        type Error = bincode::Error;
68
69        fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
70            Ok(bincode::serialize(value)?)
71        }
72        fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error> {
73            Ok(bincode::deserialize(&data)?)
74        }
75    }
76}