Skip to main content

atomcode_core/graph/
persist.rs

1use std::path::Path;
2
3use anyhow::Result;
4
5use super::CodeGraph;
6
7/// Serialize a CodeGraph to bytes using bincode.
8pub fn serialize(graph: &CodeGraph) -> Result<Vec<u8>> {
9    let bytes = bincode::serialize(graph)?;
10    Ok(bytes)
11}
12
13/// Deserialize a CodeGraph from bytes.
14pub fn deserialize(bytes: &[u8]) -> Result<CodeGraph> {
15    let graph = bincode::deserialize(bytes)?;
16    Ok(graph)
17}
18
19/// Load a CodeGraph from a file path. Returns an empty graph if the file
20/// does not exist or cannot be parsed.
21pub fn load(path: &Path) -> CodeGraph {
22    match std::fs::read(path) {
23        Ok(bytes) => deserialize(&bytes).unwrap_or_else(|_| CodeGraph::new()),
24        Err(_) => CodeGraph::new(),
25    }
26}
27
28/// Save a CodeGraph to a file, creating parent directories if needed.
29pub fn save(graph: &CodeGraph, path: &Path) -> Result<()> {
30    if let Some(parent) = path.parent() {
31        std::fs::create_dir_all(parent)?;
32    }
33    let bytes = serialize(graph)?;
34    std::fs::write(path, bytes)?;
35    Ok(())
36}