1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use crate::{Result, RwBuilder};
use serde::{de::DeserializeOwned, Serialize};
/// Type returned by the `rmp_serde` function on the `RwBuilderExt` trait.
/// It acts as a sink/source for serde operations using `MessagePack`.
#[derive(Debug)]
#[must_use]
pub struct Builder<B>
where
B: RwBuilder,
{
/// Inner builder
builder: B,
}
impl<B> Builder<B>
where
B: RwBuilder,
{
/// Factory function to wrap an inner builder
pub const fn new(builder: B) -> Self {
Self { builder }
}
}
impl<B> Builder<B>
where
B: RwBuilder,
B::Reader: std::io::Read,
B::Writer: std::io::Write,
{
/// Load an item by executing the configured reader chain and decoding via `MessagePack`
/// # Errors
/// Returns an error if the underlying reader fails or if the deserialization fails.
pub fn load<T: DeserializeOwned>(&self) -> Result<T> {
let reader = self.builder.reader()?;
rmp_serde::from_read(reader).map_err(|e| crate::error::Error::Other(e.to_string()))
}
/// Save an item by executing the configured writer chain and encoding via `MessagePack`
/// # Errors
/// Returns an error if the underlying writer fails or if the serialization fails.
pub fn save<T: Serialize>(&self, item: &T) -> Result<()> {
let mut writer = self.builder.writer()?;
rmp_serde::encode::write(&mut writer, item)
.map_err(|e| crate::error::Error::Other(e.to_string()))
}
}