Skip to main content

rw_builder/
serde_json.rs

1use crate::{Result, RwBuilder};
2use serde::{de::DeserializeOwned, Serialize};
3
4/// Type returned by the `serde_json` function on the `RwBuilderExt` trait.
5/// It acts as a sink/source for serde operations using JSON 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 JSON
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        serde_json::from_reader(reader).map_err(|e| crate::error::Error::Other(e.to_string()))
38    }
39
40    /// Save an item by executing the configured writer chain and encoding via JSON
41    /// # Errors
42    /// Returns an error if the underlying writer fails or if the serialization fails.
43    pub fn save<T: Serialize>(&self, item: &T) -> Result<()> {
44        let writer = self.builder.writer()?;
45        serde_json::to_writer(writer, item).map_err(|e| crate::error::Error::Other(e.to_string()))
46    }
47}