Skip to main content

torg_serde/
json.rs

1//! JSON serialization for TØR-G graphs.
2//!
3//! Provides human-readable JSON format for debugging and inspection.
4//! Uses serde_json with pretty printing enabled.
5
6use torg_core::Graph;
7
8use crate::error::SerdeError;
9
10/// Serialize a graph to pretty-printed JSON.
11///
12/// This format is intended for debugging and inspection.
13/// For production use, prefer the binary format which is more compact.
14pub fn to_json(graph: &Graph) -> String {
15    serde_json::to_string_pretty(graph).expect("Graph serialization should not fail")
16}
17
18/// Serialize a graph to compact JSON (no whitespace).
19pub fn to_json_compact(graph: &Graph) -> String {
20    serde_json::to_string(graph).expect("Graph serialization should not fail")
21}
22
23/// Deserialize a graph from JSON.
24pub fn from_json(json: &str) -> Result<Graph, SerdeError> {
25    Ok(serde_json::from_str(json)?)
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use torg_core::{BoolOp, Node, Source};
32
33    fn sample_graph() -> Graph {
34        Graph {
35            inputs: vec![0, 1],
36            nodes: vec![
37                Node::new(2, BoolOp::Or, Source::Id(0), Source::Id(1)),
38                Node::new(3, BoolOp::Nor, Source::Id(2), Source::True),
39            ],
40            outputs: vec![3],
41        }
42    }
43
44    #[test]
45    fn test_roundtrip() {
46        let graph = sample_graph();
47        let json = to_json(&graph);
48        let restored = from_json(&json).unwrap();
49        assert_eq!(graph, restored);
50    }
51
52    #[test]
53    fn test_compact_roundtrip() {
54        let graph = sample_graph();
55        let json = to_json_compact(&graph);
56        let restored = from_json(&json).unwrap();
57        assert_eq!(graph, restored);
58    }
59
60    #[test]
61    fn test_empty_graph() {
62        let graph = Graph::default();
63        let json = to_json(&graph);
64        let restored = from_json(&json).unwrap();
65        assert_eq!(graph, restored);
66    }
67
68    #[test]
69    fn test_json_is_readable() {
70        let graph = sample_graph();
71        let json = to_json(&graph);
72
73        // Should contain expected field names
74        assert!(json.contains("inputs"));
75        assert!(json.contains("nodes"));
76        assert!(json.contains("outputs"));
77        assert!(json.contains("Or"));
78        assert!(json.contains("Nor"));
79    }
80
81    #[test]
82    fn test_invalid_json() {
83        let result = from_json("not valid json");
84        assert!(matches!(result, Err(SerdeError::Json(_))));
85    }
86}