xgraph 3.0.0

Graph algorithms for Rust: shortest paths, centrality, connectivity, spanning trees and community detection, over directed, undirected and heterogeneous multigraphs
Documentation
//! Serialisation helpers.
//!
//! Only compiled with the `serde` feature.

/// Serialises a map as a sequence of key/value pairs.
///
/// Self-describing formats that require string keys — JSON above all — cannot represent a
/// map keyed by a tuple. The edge index is keyed by a pair of node identifiers, so it is
/// written as a list instead. The index is derived data and could equally be rebuilt on
/// load; keeping it explicit means a deserialised graph is usable without a rebuild pass.
pub mod map_as_pairs {
    use serde::de::{Deserialize, Deserializer};
    use serde::ser::{Serialize, Serializer};
    use std::collections::HashMap;
    use std::hash::Hash;

    /// Writes the map as a sequence of pairs.
    pub fn serialize<K, V, S>(map: &HashMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
    where
        K: Serialize,
        V: Serialize,
        S: Serializer,
    {
        serializer.collect_seq(map.iter())
    }

    /// Reads a sequence of pairs back into a map.
    pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<HashMap<K, V>, D::Error>
    where
        K: Deserialize<'de> + Eq + Hash,
        V: Deserialize<'de>,
        D: Deserializer<'de>,
    {
        Ok(Vec::<(K, V)>::deserialize(deserializer)?
            .into_iter()
            .collect())
    }
}