graphfind_rs/petgraph/
file_io.rs

1use crate::graph::GraphReadWriter;
2use petgraph::stable_graph::DefaultIx;
3use serde::{de::DeserializeOwned, Serialize};
4use std::{fs::File, io::Error as IOError};
5
6/// Implementation of GraphReadWriter trait using serde_json.
7/// Nodes and Edges need to implement Serializable and Deserializable
8/// in order for serde to work.
9impl<NodeWeight, EdgeWeight, EdgeType> GraphReadWriter<NodeWeight, EdgeWeight>
10    for petgraph::Graph<NodeWeight, EdgeWeight, EdgeType, DefaultIx>
11where
12    NodeWeight: Serialize + DeserializeOwned,
13    EdgeWeight: Serialize + DeserializeOwned,
14    EdgeType: petgraph::EdgeType,
15{
16    /// Serializes the graph to JSON. This overwrites the file given under path.
17    /// If serde_json fails, packs the underlying error in an std::io::Error for examination.
18    fn serialize_graph_to_file(&self, path: &str) -> Result<(), IOError> {
19        let file = File::create(path)?;
20        serde_json::ser::to_writer(file, &self)
21            .map_err(|e| IOError::new(std::io::ErrorKind::Other, e))
22    }
23
24    /// Deserializes a graph stored as JSON, and packs it into a Box.
25    /// If serde_json fails, packs the underlying error in an std::io::Error for examination.
26    fn deserialize_graph_from_file(path: &str) -> Result<Box<Self>, IOError> {
27        let file = File::open(path)?;
28        serde_json::de::from_reader(file)
29            .map(Box::new)
30            .map_err(|e| IOError::new(std::io::ErrorKind::Other, e))
31    }
32}