Skip to main content

synapse_core/
persistence.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use std::fs::File;
4use std::io::{BufReader, BufWriter};
5use std::path::Path;
6
7/// Load a serializable struct from a bincode file
8pub fn load_bincode<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
9    let file = File::open(path)?;
10    let reader = BufReader::new(file);
11    let data = bincode::deserialize_from(reader)?;
12    Ok(data)
13}
14
15/// Save a serializable struct to a bincode file (atomically via rename)
16pub fn save_bincode<T: Serialize>(path: &Path, data: &T) -> Result<()> {
17    // Write to a temporary file first
18    let tmp_path = path.with_extension("tmp");
19    {
20        let file = File::create(&tmp_path)?;
21        let writer = BufWriter::new(file);
22        bincode::serialize_into(writer, data)?;
23    }
24    // Rename to target path (atomic)
25    std::fs::rename(tmp_path, path)?;
26    Ok(())
27}