Skip to main content

rw_builder/
postcard.rs

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