rust_logic_graph/io/
mod.rs

1use anyhow::{Context, Result};
2use serde_json;
3use std::fs;
4use std::path::Path;
5
6use crate::core::GraphDef;
7
8pub struct GraphIO;
9
10impl GraphIO {
11    /// Load a graph definition from a JSON file
12    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<GraphDef> {
13        let data = fs::read_to_string(&path)
14            .with_context(|| format!("Failed to read file: {:?}", path.as_ref()))?;
15
16        let graph_def: GraphDef =
17            serde_json::from_str(&data).with_context(|| "Failed to parse JSON")?;
18
19        Ok(graph_def)
20    }
21
22    /// Save a graph definition to a JSON file
23    pub fn save_to_file<P: AsRef<Path>>(graph_def: &GraphDef, path: P) -> Result<()> {
24        let json = serde_json::to_string_pretty(graph_def)
25            .with_context(|| "Failed to serialize graph definition")?;
26
27        fs::write(&path, json)
28            .with_context(|| format!("Failed to write file: {:?}", path.as_ref()))?;
29
30        Ok(())
31    }
32
33    /// Load a graph definition from a JSON string
34    pub fn from_json(json: &str) -> Result<GraphDef> {
35        serde_json::from_str(json).with_context(|| "Failed to parse JSON string")
36    }
37
38    /// Convert a graph definition to JSON string
39    pub fn to_json(graph_def: &GraphDef) -> Result<String> {
40        serde_json::to_string_pretty(graph_def)
41            .with_context(|| "Failed to serialize graph definition")
42    }
43}