rust_logic_graph/io/
mod.rs1use 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 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 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 pub fn from_json(json: &str) -> Result<GraphDef> {
35 serde_json::from_str(json).with_context(|| "Failed to parse JSON string")
36 }
37
38 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}