Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created May 15, 2024 22:55
Show Gist options
  • Save matthewjberger/55d1ab53219ff5cf753cc951f7de477f to your computer and use it in GitHub Desktop.
Save matthewjberger/55d1ab53219ff5cf753cc951f7de477f to your computer and use it in GitHub Desktop.
Create a newtype for equating petgraph graphs (use this if you want to #[derive(PartialEq)] but your struct has a petgraph::Graph field)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomGraph {
pub graph: petgraph::Graph<MakelineNode, ()>,
}
impl PartialEq for CustomGraph {
fn eq(&self, other: &Self) -> bool {
graph_eq(&self.graph, &other.graph)
}
}
fn graph_eq<N, E, Ty, Ix>(
a: &petgraph::Graph<N, E, Ty, Ix>,
b: &petgraph::Graph<N, E, Ty, Ix>,
) -> bool
where
N: PartialEq,
E: PartialEq,
Ty: petgraph::EdgeType,
Ix: petgraph::graph::IndexType + PartialEq,
{
let a_ns = a.raw_nodes().iter().map(|n| &n.weight);
let b_ns = b.raw_nodes().iter().map(|n| &n.weight);
let a_es = a
.raw_edges()
.iter()
.map(|e| (e.source(), e.target(), &e.weight));
let b_es = b
.raw_edges()
.iter()
.map(|e| (e.source(), e.target(), &e.weight));
a_ns.eq(b_ns) && a_es.eq(b_es)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment