Apply cargo fmt
diff --git a/benches/common/factories.rs b/benches/common/factories.rs
index f20e7bf..8ab8068 100644
--- a/benches/common/factories.rs
+++ b/benches/common/factories.rs
@@ -1,8 +1,8 @@
use std::marker::PhantomData;
+use petgraph::data::Build;
use petgraph::prelude::*;
use petgraph::visit::NodeIndexable;
-use petgraph::data::Build;
use petgraph::EdgeType;
@@ -154,17 +154,15 @@
/// Parse a text adjacency matrix format into a directed graph
fn parse_graph<Ty, G>(s: &str) -> G
- where Ty: EdgeType,
- G: Default + Build<NodeWeight=(), EdgeWeight=()> + NodeIndexable,
+where
+ Ty: EdgeType,
+ G: Default + Build<NodeWeight = (), EdgeWeight = ()> + NodeIndexable,
{
let mut g: G = Default::default();
let s = s.trim();
let lines = s.lines().filter(|l| !l.is_empty());
for (row, line) in lines.enumerate() {
- for (col, word) in line.split(' ')
- .filter(|s| !s.is_empty())
- .enumerate()
- {
+ for (col, word) in line.split(' ').filter(|s| !s.is_empty()).enumerate() {
let has_edge = word.parse::<i32>().unwrap();
assert!(has_edge == 0 || has_edge == 1);
if has_edge == 0 {
@@ -187,8 +185,9 @@
}
impl<Ty, G> GraphFactory<Ty, G>
- where Ty: EdgeType,
- G: Default + Build<NodeWeight=(), EdgeWeight=()> + NodeIndexable,
+where
+ Ty: EdgeType,
+ G: Default + Build<NodeWeight = (), EdgeWeight = ()> + NodeIndexable,
{
fn new() -> Self {
GraphFactory {
diff --git a/benches/iso.rs b/benches/iso.rs
index 008de39..f0875c1 100644
--- a/benches/iso.rs
+++ b/benches/iso.rs
@@ -1,7 +1,7 @@
#![feature(test)]
-extern crate test;
extern crate petgraph;
+extern crate test;
use test::Bencher;
diff --git a/benches/matrix_graph.rs b/benches/matrix_graph.rs
index 6877a89..72f5aae 100644
--- a/benches/matrix_graph.rs
+++ b/benches/matrix_graph.rs
@@ -5,9 +5,9 @@
use test::Bencher;
-use petgraph::{EdgeType, Directed, Outgoing, Incoming};
use petgraph::algo;
-use petgraph::matrix_graph::{MatrixGraph, node_index};
+use petgraph::matrix_graph::{node_index, MatrixGraph};
+use petgraph::{Directed, EdgeType, Incoming, Outgoing};
#[bench]
fn add_100_nodes(b: &mut test::Bencher) {
@@ -41,7 +41,8 @@
let nodes: Vec<_> = (0..100).map(|_| g.add_node(())).collect();
let g = g;
- let edges_to_add: Vec<_> = nodes.iter()
+ let edges_to_add: Vec<_> = nodes
+ .iter()
.enumerate()
.map(|(i, &node)| {
let edges: Vec<_> = (0..5)
@@ -156,10 +157,7 @@
let s = s.trim();
let lines = s.lines().filter(|l| !l.is_empty());
for (row, line) in lines.enumerate() {
- for (col, word) in line.split(' ')
- .filter(|s| !s.is_empty())
- .enumerate()
- {
+ for (col, word) in line.split(' ').filter(|s| !s.is_empty()).enumerate() {
let has_edge = word.parse::<i32>().unwrap();
assert!(has_edge == 0 || has_edge == 1);
if has_edge == 0 {
diff --git a/benches/ograph.rs b/benches/ograph.rs
index 23ac271..d3f2986 100644
--- a/benches/ograph.rs
+++ b/benches/ograph.rs
@@ -13,9 +13,7 @@
let n = og.add_node(x);
og.add_edge(fst, n, ());
}
- b.iter(|| {
- og.add_node(1)
- })
+ b.iter(|| og.add_node(1))
}
#[bench]
@@ -47,7 +45,7 @@
}
//println!("{}", og);
b.iter(|| {
- for _ in 0 .. 100 {
+ for _ in 0..100 {
og.remove_node(fst);
}
})
diff --git a/benches/stable_graph.rs b/benches/stable_graph.rs
index ca4aed8..9dffd91 100644
--- a/benches/stable_graph.rs
+++ b/benches/stable_graph.rs
@@ -3,8 +3,8 @@
extern crate petgraph;
extern crate test;
-use test::Bencher;
use petgraph::prelude::*;
+use test::Bencher;
#[allow(dead_code)]
mod common;
diff --git a/benches/unionfind.rs b/benches/unionfind.rs
index cf7066e..dd4446a 100644
--- a/benches/unionfind.rs
+++ b/benches/unionfind.rs
@@ -1,7 +1,7 @@
#![feature(test)]
-extern crate test;
extern crate petgraph;
+extern crate test;
use test::Bencher;
@@ -16,9 +16,7 @@
let a = ungraph().praust_a();
let b = ungraph().praust_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -26,9 +24,7 @@
let a = digraph().praust_a();
let b = digraph().praust_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -36,9 +32,7 @@
let a = ungraph().full_a();
let b = ungraph().full_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -46,9 +40,7 @@
let a = digraph().full_a();
let b = digraph().full_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -56,9 +48,7 @@
let a = ungraph().petersen_a();
let b = ungraph().petersen_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -66,9 +56,7 @@
let a = digraph().petersen_a();
let b = digraph().petersen_b();
- bench.iter(|| {
- (connected_components(&a), connected_components(&b))
- });
+ bench.iter(|| (connected_components(&a), connected_components(&b)));
}
#[bench]
@@ -76,9 +64,7 @@
let a = ungraph().praust_a();
let b = ungraph().praust_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -86,9 +72,7 @@
let a = digraph().praust_a();
let b = digraph().praust_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -96,9 +80,7 @@
let a = ungraph().full_a();
let b = ungraph().full_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -106,9 +88,7 @@
let a = digraph().full_a();
let b = digraph().full_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -116,9 +96,7 @@
let a = ungraph().petersen_a();
let b = ungraph().petersen_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -126,9 +104,7 @@
let a = digraph().petersen_a();
let b = digraph().petersen_b();
- bench.iter(|| {
- (is_cyclic_undirected(&a), is_cyclic_undirected(&b))
- });
+ bench.iter(|| (is_cyclic_undirected(&a), is_cyclic_undirected(&b)));
}
#[bench]
@@ -136,9 +112,7 @@
let a = ungraph().praust_a();
let b = ungraph().praust_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
#[bench]
@@ -146,9 +120,7 @@
let a = digraph().praust_a();
let b = digraph().praust_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
#[bench]
@@ -156,9 +128,7 @@
let a = ungraph().full_a();
let b = ungraph().full_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
#[bench]
@@ -166,9 +136,7 @@
let a = digraph().full_a();
let b = digraph().full_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
#[bench]
@@ -176,9 +144,7 @@
let a = ungraph().petersen_a();
let b = ungraph().petersen_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
#[bench]
@@ -186,7 +152,5 @@
let a = digraph().petersen_a();
let b = digraph().petersen_b();
- bench.iter(|| {
- (min_spanning_tree(&a), min_spanning_tree(&b))
- });
+ bench.iter(|| (min_spanning_tree(&a), min_spanning_tree(&b)));
}
diff --git a/serialization-tests/src/lib.rs b/serialization-tests/src/lib.rs
index e69de29..8b13789 100644
--- a/serialization-tests/src/lib.rs
+++ b/serialization-tests/src/lib.rs
@@ -0,0 +1 @@
+
diff --git a/serialization-tests/tests/serialization.rs b/serialization-tests/tests/serialization.rs
index a82ff88..e4d13c4 100644
--- a/serialization-tests/tests/serialization.rs
+++ b/serialization-tests/tests/serialization.rs
@@ -1,24 +1,25 @@
-
extern crate petgraph;
-#[macro_use] extern crate quickcheck;
+#[macro_use]
+extern crate quickcheck;
+extern crate bincode;
extern crate itertools;
extern crate serde_json;
-extern crate bincode;
-#[macro_use] extern crate defmac;
+#[macro_use]
+extern crate defmac;
use std::collections::HashSet;
use std::fmt::Debug;
use std::iter::FromIterator;
-use itertools::{Itertools, repeat_n};
use itertools::assert_equal;
+use itertools::{repeat_n, Itertools};
+use petgraph::graph::{edge_index, node_index, IndexType};
use petgraph::prelude::*;
-use petgraph::EdgeType;
-use petgraph::graph::{node_index, edge_index, IndexType};
use petgraph::visit::EdgeRef;
-use petgraph::visit::NodeIndexable;
use petgraph::visit::IntoEdgeReferences;
+use petgraph::visit::NodeIndexable;
+use petgraph::EdgeType;
// graphs are the equal, down to graph indices
// this is a strict notion of graph equivalence:
@@ -26,20 +27,27 @@
// * Requires equal node and edge indices, equal weights
// * Does not require: edge for node order
pub fn assert_graph_eq<N, N2, E, Ty, Ix>(g: &Graph<N, E, Ty, Ix>, h: &Graph<N2, E, Ty, Ix>)
- where N: PartialEq<N2> + Debug, N2: PartialEq<N2> + Debug, E: PartialEq + Debug,
- Ty: EdgeType,
- Ix: IndexType,
+where
+ N: PartialEq<N2> + Debug,
+ N2: PartialEq<N2> + Debug,
+ E: PartialEq + Debug,
+ Ty: EdgeType,
+ Ix: IndexType,
{
assert_eq!(g.node_count(), h.node_count());
assert_eq!(g.edge_count(), h.edge_count());
// same node weigths
- assert_equal(g.raw_nodes().iter().map(|n| &n.weight),
- h.raw_nodes().iter().map(|n| &n.weight));
+ assert_equal(
+ g.raw_nodes().iter().map(|n| &n.weight),
+ h.raw_nodes().iter().map(|n| &n.weight),
+ );
// same edge weigths
- assert_equal(g.raw_edges().iter().map(|n| &n.weight),
- h.raw_edges().iter().map(|n| &n.weight));
+ assert_equal(
+ g.raw_edges().iter().map(|n| &n.weight),
+ h.raw_edges().iter().map(|n| &n.weight),
+ );
for e1 in g.edge_references() {
let (a2, b2) = h.edge_endpoints(e1.id()).unwrap();
@@ -63,7 +71,9 @@
// * Requires equal node and edge indices, equal weights
// * Does not require: edge for node order
pub fn assert_stable_graph_eq<N, E>(g: &StableGraph<N, E>, h: &StableGraph<N, E>)
- where N: PartialEq + Debug, E: PartialEq + Debug,
+where
+ N: PartialEq + Debug,
+ E: PartialEq + Debug,
{
assert_eq!(g.node_count(), h.node_count());
assert_eq!(g.edge_count(), h.edge_count());
@@ -71,7 +81,8 @@
// same node weigths
assert_equal(
(0..g.node_bound()).map(|i| g.node_weight(node_index(i))),
- (0..h.node_bound()).map(|i| h.node_weight(node_index(i))));
+ (0..h.node_bound()).map(|i| h.node_weight(node_index(i))),
+ );
let last_edge_g = g.edge_references().next_back();
let last_edge_h = h.edge_references().next_back();
@@ -83,7 +94,8 @@
// same edge weigths
assert_equal(
(0..lgi).map(|i| g.edge_weight(edge_index(i))),
- (0..lhi).map(|i| h.edge_weight(edge_index(i))));
+ (0..lhi).map(|i| h.edge_weight(edge_index(i))),
+ );
}
for e1 in g.edge_references() {
@@ -102,10 +114,10 @@
}
}
-
fn make_graph<Ty, Ix>() -> Graph<&'static str, i32, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
let mut g = Graph::default();
let a = g.add_node("A");
@@ -131,8 +143,9 @@
}
fn make_stable_graph<Ty, Ix>() -> StableGraph<&'static str, i32, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
let mut g = StableGraph::default();
let a = g.add_node("A");
@@ -203,7 +216,6 @@
"edges":[[0,1,7],[2,0,9],[0,3,14],[1,2,10],[3,2,2],[3,4,9],[1,5,15],[2,5,11],[4,5,6]]
}"#;
-
type DiGraphNils = DiGraph<(), ()>;
type UnGraphNils = UnGraph<(), ()>;
type DiGraphNilsU8 = DiGraph<(), (), u8>;
@@ -215,19 +227,19 @@
}
#[test]
-#[should_panic(expected="edge property mismatch")]
+#[should_panic(expected = "edge property mismatch")]
fn from_json_graph_nils_edge_property_mismatch() {
let _: UnGraphNils = fromjson!(DIGRAPH_NILS);
}
#[test]
-#[should_panic(expected="does not exist")]
+#[should_panic(expected = "does not exist")]
fn from_json_graph_nils_index_oob() {
let _: DiGraphNils = fromjson!(DIGRAPH_NILS_INDEX_OOB);
}
#[test]
-#[should_panic(expected="expected u8")]
+#[should_panic(expected = "expected u8")]
fn from_json_graph_nils_index_too_large() {
let _: DiGraphNilsU8 = fromjson!(DIGRAPH_NILS_INDEX_OUTSIDE_U8);
}
@@ -238,21 +250,31 @@
}
#[test]
-#[should_panic(expected="expected unit")]
+#[should_panic(expected = "expected unit")]
fn from_json_graph_from_edge_type_1() {
let _: DiGraphNils = fromjson!(DIGRAPH_STRI32);
}
#[test]
-#[should_panic(expected="expected a string")]
+#[should_panic(expected = "expected a string")]
fn from_json_graph_from_edge_type_2() {
let _: DiGraphStrI32 = fromjson!(DIGRAPH_NILS);
}
#[test]
fn from_json_digraph_str_i32() {
- let g4nodes = ["A","B","C","D","E","F"];
- let g4edges = [[0,1,7],[2,0,9],[0,3,14],[1,2,10],[3,2,2],[3,4,9],[1,5,15],[2,5,11],[4,5,6]];
+ let g4nodes = ["A", "B", "C", "D", "E", "F"];
+ let g4edges = [
+ [0, 1, 7],
+ [2, 0, 9],
+ [0, 3, 14],
+ [1, 2, 10],
+ [3, 2, 2],
+ [3, 4, 9],
+ [1, 5, 15],
+ [2, 5, 11],
+ [4, 5, 6],
+ ];
type GSI = DiGraph<String, i32>;
type GSISmall = DiGraph<String, i32, u8>;
@@ -280,17 +302,19 @@
// ensure we fail if node or edge count exceeds index max
use serde_json::from_str;
- let j1_big = &format!("{}{}{}",
- r#"
+ let j1_big = &format!(
+ "{}{}{}",
+ r#"
{"nodes": [
"#,
- repeat_n(0, 300).format(", "),
- r#"
+ repeat_n(0, 300).format(", "),
+ r#"
],
"edge_property": "directed",
"edges": []
}
- "#);
+ "#
+ );
type G8 = DiGraph<i32, (), u8>;
type G16 = DiGraph<i32, (), u16>;
@@ -313,13 +337,15 @@
// ensure we fail if node or edge count exceeds index max
use serde_json::from_str;
- let j1_big = format!("{}{}{}",
- r#"
+ let j1_big = format!(
+ "{}{}{}",
+ r#"
{"nodes": [0],
"edge_property": "directed",
"edges": ["#,
- repeat_n("[0, 0, 1]", (1 << 16) - 1).format(", "),
- "]}");
+ repeat_n("[0, 0, 1]", (1 << 16) - 1).format(", "),
+ "]}"
+ );
type G8 = DiGraph<i32, i32, u8>;
type G16 = DiGraph<i32, i32, u16>;
@@ -350,7 +376,6 @@
assert_stable_graph_eq(&g1, &g2);
}
-
// bincode macros
defmac!(encode ref g => bincode::serialize(g).unwrap());
defmac!(decode ref data => bincode::deserialize(data).unwrap());
diff --git a/src/algo/dominators.rs b/src/algo/dominators.rs
index 4d39f2e..85c2b63 100644
--- a/src/algo/dominators.rs
+++ b/src/algo/dominators.rs
@@ -21,14 +21,16 @@
/// The dominance relation for some graph and root.
#[derive(Debug, Clone)]
pub struct Dominators<N>
- where N: Copy + Eq + Hash
+where
+ N: Copy + Eq + Hash,
{
root: N,
dominators: HashMap<N, N>,
}
impl<N> Dominators<N>
- where N: Copy + Eq + Hash
+where
+ N: Copy + Eq + Hash,
{
/// Get the root node used to construct these dominance relations.
pub fn root(&self) -> N {
@@ -81,14 +83,16 @@
/// Iterator for a node's dominators.
pub struct DominatorsIter<'a, N>
- where N: 'a + Copy + Eq + Hash
+where
+ N: 'a + Copy + Eq + Hash,
{
dominators: &'a Dominators<N>,
node: Option<N>,
}
impl<'a, N> Iterator for DominatorsIter<'a, N>
- where N: 'a + Copy + Eq + Hash
+where
+ N: 'a + Copy + Eq + Hash,
{
type Item = N;
@@ -115,8 +119,9 @@
///
/// [0]: http://www.cs.rice.edu/~keith/EMBED/dom.pdf
pub fn simple_fast<G>(graph: G, root: G::NodeId) -> Dominators<G::NodeId>
- where G: IntoNeighbors + Visitable,
- <G as GraphBase>::NodeId: Eq + Hash
+where
+ G: IntoNeighbors + Visitable,
+ <G as GraphBase>::NodeId: Eq + Hash,
{
let (post_order, predecessor_sets) = simple_fast_post_order(graph, root);
let length = post_order.len();
@@ -129,7 +134,8 @@
// convert our data structures to play along first.
// Maps a node to its index into `post_order`.
- let node_to_post_order_idx: HashMap<_, _> = post_order.iter()
+ let node_to_post_order_idx: HashMap<_, _> = post_order
+ .iter()
.enumerate()
.map(|(idx, &node)| (node, idx))
.collect();
@@ -156,12 +162,14 @@
// node.
let new_idom_idx = {
- let mut predecessors =
- idx_to_predecessor_vec[idx].iter().filter(|&&p| dominators[p] != UNDEFINED);
- let new_idom_idx = predecessors.next()
- .expect("Because the root is initialized to dominate itself, and is the \
+ let mut predecessors = idx_to_predecessor_vec[idx]
+ .iter()
+ .filter(|&&p| dominators[p] != UNDEFINED);
+ let new_idom_idx = predecessors.next().expect(
+ "Because the root is initialized to dominate itself, and is the \
first node in every path, there must exist a predecessor to this \
- node that also has a dominator");
+ node that also has a dominator",
+ );
predecessors.fold(*new_idom_idx, |new_idom_idx, &predecessor_idx| {
intersect(&dominators, new_idom_idx, predecessor_idx)
})
@@ -182,7 +190,8 @@
Dominators {
root,
- dominators: dominators.into_iter()
+ dominators: dominators
+ .into_iter()
.enumerate()
.map(|(idx, dom_idx)| (post_order[idx], post_order[dom_idx]))
.collect(),
@@ -199,17 +208,22 @@
}
}
-fn predecessor_sets_to_idx_vecs<N>(post_order: &[N],
- node_to_post_order_idx: &HashMap<N, usize>,
- mut predecessor_sets: HashMap<N, HashSet<N>>)
- -> Vec<Vec<usize>>
- where N: Copy + Eq + Hash
+fn predecessor_sets_to_idx_vecs<N>(
+ post_order: &[N],
+ node_to_post_order_idx: &HashMap<N, usize>,
+ mut predecessor_sets: HashMap<N, HashSet<N>>,
+) -> Vec<Vec<usize>>
+where
+ N: Copy + Eq + Hash,
{
- post_order.iter()
+ post_order
+ .iter()
.map(|node| {
- predecessor_sets.remove(node)
+ predecessor_sets
+ .remove(node)
.map(|predecessors| {
- predecessors.into_iter()
+ predecessors
+ .into_iter()
.map(|p| *node_to_post_order_idx.get(&p).unwrap())
.collect()
})
@@ -218,11 +232,13 @@
.collect()
}
-fn simple_fast_post_order<G>(graph: G,
- root: G::NodeId)
- -> (Vec<G::NodeId>, HashMap<G::NodeId, HashSet<G::NodeId>>)
- where G: IntoNeighbors + Visitable,
- <G as GraphBase>::NodeId: Eq + Hash
+fn simple_fast_post_order<G>(
+ graph: G,
+ root: G::NodeId,
+) -> (Vec<G::NodeId>, HashMap<G::NodeId, HashSet<G::NodeId>>)
+where
+ G: IntoNeighbors + Visitable,
+ <G as GraphBase>::NodeId: Eq + Hash,
{
let mut post_order = vec![];
let mut predecessor_sets = HashMap::new();
@@ -231,7 +247,8 @@
post_order.push(node);
for successor in graph.neighbors(node) {
- predecessor_sets.entry(successor)
+ predecessor_sets
+ .entry(successor)
.or_insert_with(HashSet::new)
.insert(node);
}
@@ -248,10 +265,7 @@
fn test_iter_dominators() {
let doms: Dominators<u32> = Dominators {
root: 0,
- dominators: [(2, 1), (1, 0), (0, 0)]
- .iter()
- .cloned()
- .collect(),
+ dominators: [(2, 1), (1, 0), (0, 0)].iter().cloned().collect(),
};
let all_doms: Vec<_> = doms.dominators(2).unwrap().collect();
@@ -262,6 +276,9 @@
let strict_doms: Vec<_> = doms.strict_dominators(2).unwrap().collect();
assert_eq!(vec![1, 0], strict_doms);
- assert_eq!(None::<()>, doms.strict_dominators(99).map(|_| unreachable!()));
+ assert_eq!(
+ None::<()>,
+ doms.strict_dominators(99).map(|_| unreachable!())
+ );
}
}
diff --git a/src/algo/mod.rs b/src/algo/mod.rs
index 6163a2b..aa54405 100644
--- a/src/algo/mod.rs
+++ b/src/algo/mod.rs
@@ -6,46 +6,27 @@
pub mod dominators;
-use std::collections::{BinaryHeap, HashMap};
use std::cmp::min;
+use std::collections::{BinaryHeap, HashMap};
use crate::prelude::*;
-use super::{
- EdgeType,
-};
-use crate::scored::MinScored;
-use super::visit::{
- GraphRef,
- GraphBase,
- Visitable,
- VisitMap,
- IntoNeighbors,
- IntoNeighborsDirected,
- IntoNodeIdentifiers,
- NodeCount,
- NodeIndexable,
- NodeCompactIndexable,
- IntoEdgeReferences,
- IntoEdges,
- Reversed,
-};
+use super::graph::IndexType;
use super::unionfind::UnionFind;
-use super::graph::{
- IndexType,
+use super::visit::{
+ GraphBase, GraphRef, IntoEdgeReferences, IntoEdges, IntoNeighbors, IntoNeighborsDirected,
+ IntoNodeIdentifiers, NodeCompactIndexable, NodeCount, NodeIndexable, Reversed, VisitMap,
+ Visitable,
};
-use crate::visit::{Data, NodeRef, IntoNodeReferences};
+use super::EdgeType;
+use crate::data::Element;
+use crate::scored::MinScored;
use crate::visit::Walker;
-use crate::data::{
- Element,
-};
+use crate::visit::{Data, IntoNodeReferences, NodeRef};
-pub use super::isomorphism::{
- is_isomorphic,
- is_isomorphic_matching,
-};
-pub use super::dijkstra::dijkstra;
pub use super::astar::astar;
+pub use super::dijkstra::dijkstra;
+pub use super::isomorphism::{is_isomorphic, is_isomorphic_matching};
pub use super::simple_paths::all_simple_paths;
/// \[Generic\] Return the number of connected components of the graph.
@@ -87,7 +68,8 @@
/// assert_eq!(connected_components(&graph),1);
/// ```
pub fn connected_components<G>(g: G) -> usize
- where G: NodeCompactIndexable + IntoEdgeReferences,
+where
+ G: NodeCompactIndexable + IntoEdgeReferences,
{
let mut vertex_sets = UnionFind::new(g.node_bound());
for edge in g.edge_references() {
@@ -102,12 +84,12 @@
labels.len()
}
-
/// \[Generic\] Return `true` if the input graph contains a cycle.
///
/// Always treats the input graph as if undirected.
pub fn is_cyclic_undirected<G>(g: G) -> bool
- where G: NodeIndexable + IntoEdgeReferences
+where
+ G: NodeIndexable + IntoEdgeReferences,
{
let mut edge_sets = UnionFind::new(g.node_bound());
for edge in g.edge_references() {
@@ -116,13 +98,12 @@
// union the two vertices of the edge
// -- if they were already the same, then we have a cycle
if !edge_sets.union(g.to_index(a), g.to_index(b)) {
- return true
+ return true;
}
}
false
}
-
/// \[Generic\] Perform a topological sort of a directed graph.
///
/// If the graph was acyclic, return a vector of nodes in topological order:
@@ -134,9 +115,12 @@
///
/// If `space` is not `None`, it is used instead of creating a new workspace for
/// graph traversal. The implementation is iterative.
-pub fn toposort<G>(g: G, space: Option<&mut DfsSpace<G::NodeId, G::Map>>)
- -> Result<Vec<G::NodeId>, Cycle<G::NodeId>>
- where G: IntoNeighborsDirected + IntoNodeIdentifiers + Visitable,
+pub fn toposort<G>(
+ g: G,
+ space: Option<&mut DfsSpace<G::NodeId, G::Map>>,
+) -> Result<Vec<G::NodeId>, Cycle<G::NodeId>>
+where
+ G: IntoNeighborsDirected + IntoNodeIdentifiers + Visitable,
{
// based on kosaraju scc
with_dfs(g, space, |dfs| {
@@ -193,16 +177,16 @@
/// This implementation is recursive; use `toposort` if an alternative is
/// needed.
pub fn is_cyclic_directed<G>(g: G) -> bool
- where G: IntoNodeIdentifiers + IntoNeighbors + Visitable,
+where
+ G: IntoNodeIdentifiers + IntoNeighbors + Visitable,
{
use crate::visit::{depth_first_search, DfsEvent};
- depth_first_search(g, g.node_identifiers(), |event| {
- match event {
- DfsEvent::BackEdge(_, _) => Err(()),
- _ => Ok(()),
- }
- }).is_err()
+ depth_first_search(g, g.node_identifiers(), |event| match event {
+ DfsEvent::BackEdge(_, _) => Err(()),
+ _ => Ok(()),
+ })
+ .is_err()
}
type DfsSpaceType<G> = DfsSpace<<G as GraphBase>::NodeId, <G as Visitable>::Map>;
@@ -214,38 +198,42 @@
}
impl<N, VM> DfsSpace<N, VM>
- where N: Copy + PartialEq,
- VM: VisitMap<N>,
+where
+ N: Copy + PartialEq,
+ VM: VisitMap<N>,
{
pub fn new<G>(g: G) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>,
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
- DfsSpace {
- dfs: Dfs::empty(g)
- }
+ DfsSpace { dfs: Dfs::empty(g) }
}
}
impl<N, VM> Default for DfsSpace<N, VM>
- where VM: VisitMap<N> + Default,
+where
+ VM: VisitMap<N> + Default,
{
fn default() -> Self {
DfsSpace {
dfs: Dfs {
stack: <_>::default(),
discovered: <_>::default(),
- }
+ },
}
}
}
/// Create a Dfs if it's needed
fn with_dfs<G, F, R>(g: G, space: Option<&mut DfsSpaceType<G>>, f: F) -> R
- where G: GraphRef + Visitable,
- F: FnOnce(&mut Dfs<G::NodeId, G::Map>) -> R
+where
+ G: GraphRef + Visitable,
+ F: FnOnce(&mut Dfs<G::NodeId, G::Map>) -> R,
{
let mut local_visitor;
- let dfs = if let Some(v) = space { &mut v.dfs } else {
+ let dfs = if let Some(v) = space {
+ &mut v.dfs
+ } else {
local_visitor = Dfs::empty(g);
&mut local_visitor
};
@@ -258,10 +246,14 @@
///
/// If `space` is not `None`, it is used instead of creating a new workspace for
/// graph traversal.
-pub fn has_path_connecting<G>(g: G, from: G::NodeId, to: G::NodeId,
- space: Option<&mut DfsSpace<G::NodeId, G::Map>>)
- -> bool
- where G: IntoNeighbors + Visitable,
+pub fn has_path_connecting<G>(
+ g: G,
+ from: G::NodeId,
+ to: G::NodeId,
+ space: Option<&mut DfsSpace<G::NodeId, G::Map>>,
+) -> bool
+where
+ G: IntoNeighbors + Visitable,
{
with_dfs(g, space, |dfs| {
dfs.reset(g);
@@ -273,7 +265,8 @@
/// Renamed to `kosaraju_scc`.
#[deprecated(note = "renamed to kosaraju_scc")]
pub fn scc<G>(g: G) -> Vec<Vec<G::NodeId>>
- where G: IntoNeighborsDirected + Visitable + IntoNodeIdentifiers,
+where
+ G: IntoNeighborsDirected + Visitable + IntoNodeIdentifiers,
{
kosaraju_scc(g)
}
@@ -290,7 +283,8 @@
///
/// This implementation is iterative and does two passes over the nodes.
pub fn kosaraju_scc<G>(g: G) -> Vec<Vec<G::NodeId>>
- where G: IntoNeighborsDirected + Visitable + IntoNodeIdentifiers,
+where
+ G: IntoNeighborsDirected + Visitable + IntoNodeIdentifiers,
{
let mut dfs = DfsPostOrder::empty(g);
@@ -299,7 +293,7 @@
let mut finish_order = Vec::with_capacity(0);
for i in g.node_identifiers() {
if dfs.discovered.is_visited(&i) {
- continue
+ continue;
}
dfs.move_to(i);
@@ -341,10 +335,10 @@
///
/// This implementation is recursive and does one pass over the nodes.
pub fn tarjan_scc<G>(g: G) -> Vec<Vec<G::NodeId>>
- where G: IntoNodeIdentifiers + IntoNeighbors + NodeIndexable
+where
+ G: IntoNodeIdentifiers + IntoNeighbors + NodeIndexable,
{
- #[derive(Copy, Clone)]
- #[derive(Debug)]
+ #[derive(Copy, Clone, Debug)]
struct NodeData {
index: Option<usize>,
lowlink: usize,
@@ -353,8 +347,9 @@
#[derive(Debug)]
struct Data<'a, G>
- where G: NodeIndexable,
- G::NodeId: 'a
+ where
+ G: NodeIndexable,
+ G::NodeId: 'a,
{
index: usize,
nodes: Vec<NodeData>,
@@ -363,10 +358,13 @@
}
fn scc_visit<G>(v: G::NodeId, g: G, data: &mut Data<G>)
- where G: IntoNeighbors + NodeIndexable
+ where
+ G: IntoNeighbors + NodeIndexable,
{
macro_rules! node {
- ($node:expr) => (data.nodes[g.to_index($node)])
+ ($node:expr) => {
+ data.nodes[g.to_index($node)]
+ };
}
if node![v].index.is_some() {
@@ -405,7 +403,9 @@
let w = data.stack.pop().unwrap();
node![w].on_stack = false;
cur_scc.push(w);
- if g.to_index(w) == g.to_index(v) { break; }
+ if g.to_index(w) == g.to_index(v) {
+ break;
+ }
}
data.sccs.push(cur_scc);
}
@@ -414,7 +414,14 @@
let mut sccs = Vec::new();
{
- let map = vec![NodeData { index: None, lowlink: !0, on_stack: false }; g.node_bound()];
+ let map = vec![
+ NodeData {
+ index: None,
+ lowlink: !0,
+ on_stack: false
+ };
+ g.node_bound()
+ ];
let mut data = Data {
index: 0,
@@ -510,9 +517,13 @@
/// assert_eq!(acyclic_condensed_graph.edge_count(), 1);
/// assert_eq!(acyclic_condensed_graph.neighbors(B).collect::<Vec<_>>(), vec![A]);
/// ```
-pub fn condensation<N, E, Ty, Ix>(g: Graph<N, E, Ty, Ix>, make_acyclic: bool) -> Graph<Vec<N>, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+pub fn condensation<N, E, Ty, Ix>(
+ g: Graph<N, E, Ty, Ix>,
+ make_acyclic: bool,
+) -> Graph<Vec<N>, E, Ty, Ix>
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
let sccs = kosaraju_scc(&g);
let mut condensed: Graph<Vec<N>, E, Ty, Ix> = Graph::with_capacity(sccs.len(), g.edge_count());
@@ -558,11 +569,11 @@
///
/// Use `from_elements` to create a graph from the resulting iterator.
pub fn min_spanning_tree<G>(g: G) -> MinSpanningTree<G>
- where G::NodeWeight: Clone,
- G::EdgeWeight: Clone + PartialOrd,
- G: IntoNodeReferences + IntoEdgeReferences + NodeIndexable,
+where
+ G::NodeWeight: Clone,
+ G::EdgeWeight: Clone + PartialOrd,
+ G: IntoNodeReferences + IntoEdgeReferences + NodeIndexable,
{
-
// Initially each vertex is its own disjoint subgraph, track the connectedness
// of the pre-MST with a union & find datastructure.
let subgraphs = UnionFind::new(g.node_bound());
@@ -570,7 +581,10 @@
let edges = g.edge_references();
let mut sort_edges = BinaryHeap::with_capacity(edges.size_hint().0);
for edge in edges {
- sort_edges.push(MinScored(edge.weight().clone(), (edge.source(), edge.target())));
+ sort_edges.push(MinScored(
+ edge.weight().clone(),
+ (edge.source(), edge.target()),
+ ));
}
MinSpanningTree {
@@ -581,12 +595,12 @@
node_map: HashMap::new(),
node_count: 0,
}
-
}
/// An iterator producing a minimum spanning forest of a graph.
pub struct MinSpanningTree<G>
- where G: Data + IntoNodeReferences,
+where
+ G: Data + IntoNodeReferences,
{
graph: G,
node_ids: Option<G::NodeReferences>,
@@ -596,11 +610,11 @@
node_count: usize,
}
-
impl<G> Iterator for MinSpanningTree<G>
- where G: IntoNodeReferences + NodeIndexable,
- G::NodeWeight: Clone,
- G::EdgeWeight: PartialOrd,
+where
+ G: IntoNodeReferences + NodeIndexable,
+ G::NodeWeight: Clone,
+ G::EdgeWeight: PartialOrd,
{
type Item = Element<G::NodeWeight, G::EdgeWeight>;
@@ -610,7 +624,9 @@
if let Some(node) = iter.next() {
self.node_map.insert(g.to_index(node.id()), self.node_count);
self.node_count += 1;
- return Some(Element::Node { weight: node.weight().clone() });
+ return Some(Element::Node {
+ weight: node.weight().clone(),
+ });
}
}
self.node_ids = None;
@@ -628,11 +644,11 @@
// check if the edge would connect two disjoint parts
let (a_index, b_index) = (g.to_index(a), g.to_index(b));
if self.subgraphs.union(a_index, b_index) {
- let (&a_order, &b_order) = match (self.node_map.get(&a_index),
- self.node_map.get(&b_index)) {
- (Some(a_id), Some(b_id)) => (a_id, b_id),
- _ => panic!("Edge references unknown node"),
- };
+ let (&a_order, &b_order) =
+ match (self.node_map.get(&a_index), self.node_map.get(&b_index)) {
+ (Some(a_id), Some(b_id)) => (a_id, b_id),
+ _ => panic!("Edge references unknown node"),
+ };
return Some(Element::Edge {
source: a_order,
target: b_order,
@@ -651,7 +667,8 @@
impl<N> Cycle<N> {
/// Return a node id that participates in the cycle
pub fn node_id(&self) -> N
- where N: Copy
+ where
+ N: Copy,
{
self.0
}
@@ -725,10 +742,13 @@
///
/// assert!(bellman_ford(&graph_with_neg_cycle, NodeIndex::new(0)).is_err());
/// ```
-pub fn bellman_ford<G>(g: G, source: G::NodeId)
- -> Result<(Vec<G::EdgeWeight>, Vec<Option<G::NodeId>>), NegativeCycle>
- where G: NodeCount + IntoNodeIdentifiers + IntoEdges + NodeIndexable,
- G::EdgeWeight: FloatMeasure,
+pub fn bellman_ford<G>(
+ g: G,
+ source: G::NodeId,
+) -> Result<(Vec<G::EdgeWeight>, Vec<Option<G::NodeId>>), NegativeCycle>
+where
+ G: NodeCount + IntoNodeIdentifiers + IntoEdges + NodeIndexable,
+ G::EdgeWeight: FloatMeasure,
{
let mut predecessor = vec![None; g.node_bound()];
let mut distance = vec![<_>::infinite(); g.node_bound()];
@@ -771,29 +791,34 @@
Ok((distance, predecessor))
}
-use std::ops::Add;
use std::fmt::Debug;
+use std::ops::Add;
/// Associated data that can be used for measures (such as length).
-pub trait Measure : Debug + PartialOrd + Add<Self, Output=Self> + Default + Clone {
-}
+pub trait Measure: Debug + PartialOrd + Add<Self, Output = Self> + Default + Clone {}
-impl<M> Measure for M
- where M: Debug + PartialOrd + Add<M, Output=M> + Default + Clone,
-{ }
+impl<M> Measure for M where M: Debug + PartialOrd + Add<M, Output = M> + Default + Clone {}
/// A floating-point measure.
-pub trait FloatMeasure : Measure + Copy {
+pub trait FloatMeasure: Measure + Copy {
fn zero() -> Self;
fn infinite() -> Self;
}
impl FloatMeasure for f32 {
- fn zero() -> Self { 0. }
- fn infinite() -> Self { 1./0. }
+ fn zero() -> Self {
+ 0.
+ }
+ fn infinite() -> Self {
+ 1. / 0.
+ }
}
impl FloatMeasure for f64 {
- fn zero() -> Self { 0. }
- fn infinite() -> Self { 1./0. }
+ fn zero() -> Self {
+ 0.
+ }
+ fn infinite() -> Self {
+ 1. / 0.
+ }
}
diff --git a/src/astar.rs b/src/astar.rs
index b9435f5..56b3e2e 100644
--- a/src/astar.rs
+++ b/src/astar.rs
@@ -1,22 +1,10 @@
-use std::collections::{
- HashMap,
- BinaryHeap,
-};
-use std::collections::hash_map::Entry::{
- Occupied,
- Vacant,
-};
+use std::collections::hash_map::Entry::{Occupied, Vacant};
+use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
+use super::visit::{EdgeRef, GraphBase, IntoEdges, VisitMap, Visitable};
use crate::scored::MinScored;
-use super::visit::{
- EdgeRef,
- GraphBase,
- IntoEdges,
- VisitMap,
- Visitable,
-};
use crate::algo::Measure;
@@ -75,15 +63,20 @@
///
/// Returns the total cost + the path of subsequent `NodeId` from start to finish, if one was
/// found.
-pub fn astar<G, F, H, K, IsGoal>(graph: G, start: G::NodeId, mut is_goal: IsGoal,
- mut edge_cost: F, mut estimate_cost: H)
- -> Option<(K, Vec<G::NodeId>)>
- where G: IntoEdges + Visitable,
- IsGoal: FnMut(G::NodeId) -> bool,
- G::NodeId: Eq + Hash,
- F: FnMut(G::EdgeRef) -> K,
- H: FnMut(G::NodeId) -> K,
- K: Measure + Copy,
+pub fn astar<G, F, H, K, IsGoal>(
+ graph: G,
+ start: G::NodeId,
+ mut is_goal: IsGoal,
+ mut edge_cost: F,
+ mut estimate_cost: H,
+) -> Option<(K, Vec<G::NodeId>)>
+where
+ G: IntoEdges + Visitable,
+ IsGoal: FnMut(G::NodeId) -> bool,
+ G::NodeId: Eq + Hash,
+ F: FnMut(G::EdgeRef) -> K,
+ H: FnMut(G::NodeId) -> K,
+ K: Measure + Copy,
{
let mut visited = graph.visit_map();
let mut visit_next = BinaryHeap::new();
@@ -104,7 +97,7 @@
// Don't visit the same node several times, as the first time it was visited it was using
// the shortest available path.
if !visited.visit(node) {
- continue
+ continue;
}
// This lookup can be unwrapped without fear of panic since the node was necessarily scored
@@ -114,7 +107,7 @@
for edge in graph.edges(node) {
let next = edge.target();
if visited.is_visited(&next) {
- continue
+ continue;
}
let mut next_score = node_score + edge_cost(edge);
@@ -128,7 +121,7 @@
} else {
next_score = old_score;
}
- },
+ }
Vacant(ent) => {
ent.insert(next_score);
path_tracker.set_predecessor(next, node);
@@ -144,15 +137,17 @@
}
struct PathTracker<G>
- where G: GraphBase,
- G::NodeId: Eq + Hash,
+where
+ G: GraphBase,
+ G::NodeId: Eq + Hash,
{
came_from: HashMap<G::NodeId, G::NodeId>,
}
impl<G> PathTracker<G>
- where G: GraphBase,
- G::NodeId: Eq + Hash,
+where
+ G: GraphBase,
+ G::NodeId: Eq + Hash,
{
fn new() -> PathTracker<G> {
PathTracker {
diff --git a/src/csr.rs b/src/csr.rs
index a8ffcb0..8a75e3f 100644
--- a/src/csr.rs
+++ b/src/csr.rs
@@ -1,25 +1,21 @@
//! Compressed Sparse Row (CSR) is a sparse adjacency matrix graph.
-use std::marker::PhantomData;
use std::cmp::max;
-use std::ops::{Range, Index, IndexMut};
use std::iter::{Enumerate, Zip};
+use std::marker::PhantomData;
+use std::ops::{Index, IndexMut, Range};
use std::slice::Windows;
-use crate::visit::{EdgeRef, GraphBase, IntoNeighbors, NodeIndexable, IntoEdges};
-use crate::visit::{NodeCompactIndexable, IntoNodeIdentifiers, Visitable};
-use crate::visit::{Data, IntoEdgeReferences, NodeCount, GraphProp};
+use crate::visit::{Data, GraphProp, IntoEdgeReferences, NodeCount};
+use crate::visit::{EdgeRef, GraphBase, IntoEdges, IntoNeighbors, NodeIndexable};
+use crate::visit::{IntoNodeIdentifiers, NodeCompactIndexable, Visitable};
use crate::util::zip;
#[doc(no_inline)]
-pub use crate::graph::{IndexType, DefaultIx};
+pub use crate::graph::{DefaultIx, IndexType};
-use crate::{
- EdgeType,
- Directed,
- IntoWeightedEdge,
-};
+use crate::{Directed, EdgeType, IntoWeightedEdge};
/// Csr node index type, a plain integer.
pub type NodeIndex<Ix = DefaultIx> = Ix;
@@ -60,8 +56,9 @@
}
impl<N, E, Ty, Ix> Default for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn default() -> Self {
Self::new()
@@ -82,8 +79,9 @@
}
impl<N, E, Ty, Ix> Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// Create an empty `Csr`.
pub fn new() -> Self {
@@ -115,7 +113,8 @@
/// assert_eq!(graph[4],0);
/// ```
pub fn with_nodes(n: usize) -> Self
- where N: Default,
+ where
+ N: Default,
{
Csr {
column: Vec::new(),
@@ -135,9 +134,9 @@
}
impl<N, E, Ix> Csr<N, E, Directed, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
-
/// Create a new `Csr` from a sorted sequence of edges
///
/// Edges **must** be sorted and unique, where the sort order is the default
@@ -157,13 +156,17 @@
/// ]);
/// ```
pub fn from_sorted_edges<Edge>(edges: &[Edge]) -> Result<Self, EdgesNotSorted>
- where Edge: Clone + IntoWeightedEdge<E, NodeId=NodeIndex<Ix>>,
- N: Default,
+ where
+ Edge: Clone + IntoWeightedEdge<E, NodeId = NodeIndex<Ix>>,
+ N: Default,
{
- let max_node_id = match edges.iter().map(|edge|
- match edge.clone().into_weighted_edge() {
- (x, y, _) => max(x.index(), y.index())
- }).max() {
+ let max_node_id = match edges
+ .iter()
+ .map(|edge| match edge.clone().into_weighted_edge() {
+ (x, y, _) => max(x.index(), y.index()),
+ })
+ .max()
+ {
None => return Ok(Self::with_nodes(0)),
Some(x) => x,
};
@@ -229,10 +232,10 @@
}
impl<N, E, Ty, Ix> Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
-
pub fn node_count(&self) -> usize {
self.row.len() - 1
}
@@ -276,7 +279,8 @@
///
/// **Panics** if `a` or `b` are out of bounds.
pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> bool
- where E: Clone,
+ where
+ E: Clone,
{
let ret = self.add_edge_(a, b, weight.clone());
if ret && !self.is_directed() {
@@ -336,7 +340,11 @@
fn neighbors_range(&self, a: NodeIndex<Ix>) -> Range<usize> {
let index = self.row[a.index()];
- let end = self.row.get(a.index() + 1).cloned().unwrap_or_else(|| self.column.len());
+ let end = self
+ .row
+ .get(a.index() + 1)
+ .cloned()
+ .unwrap_or_else(|| self.column.len());
index..end
}
@@ -408,35 +416,48 @@
}
}
-impl<'a, E, Ty, Ix: Copy> Copy for EdgeReference<'a, E, Ty, Ix> { }
+impl<'a, E, Ty, Ix: Copy> Copy for EdgeReference<'a, E, Ty, Ix> {}
impl<'a, Ty, E, Ix> EdgeReference<'a, E, Ty, Ix>
- where Ty: EdgeType,
+where
+ Ty: EdgeType,
{
/// Access the edge’s weight.
///
/// **NOTE** that this method offers a longer lifetime
/// than the trait (unfortunately they don't match yet).
- pub fn weight(&self) -> &'a E { self.weight }
+ pub fn weight(&self) -> &'a E {
+ self.weight
+ }
}
impl<'a, E, Ty, Ix> EdgeRef for EdgeReference<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeId = NodeIndex<Ix>;
type EdgeId = EdgeIndex;
type Weight = E;
- fn source(&self) -> Self::NodeId { self.source }
- fn target(&self) -> Self::NodeId { self.target }
- fn weight(&self) -> &E { self.weight }
- fn id(&self) -> Self::EdgeId { self.index }
+ fn source(&self) -> Self::NodeId {
+ self.source
+ }
+ fn target(&self) -> Self::NodeId {
+ self.target
+ }
+ fn weight(&self) -> &E {
+ self.weight
+ }
+ fn id(&self) -> Self::EdgeId {
+ self.index
+ }
}
impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ty, Ix>;
fn next(&mut self) -> Option<Self::Item> {
@@ -455,16 +476,18 @@
}
impl<N, E, Ty, Ix> Data for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeWeight = N;
type EdgeWeight = E;
}
impl<'a, N, E, Ty, Ix> IntoEdgeReferences for &'a Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeRef = EdgeReference<'a, E, Ty, Ix>;
type EdgeReferences = EdgeReferences<'a, E, Ty, Ix>;
@@ -492,8 +515,9 @@
}
impl<'a, E, Ty, Ix> Iterator for EdgeReferences<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ty, Ix>;
fn next(&mut self) -> Option<Self::Item> {
@@ -507,7 +531,7 @@
target: j,
weight: w,
ty: PhantomData,
- })
+ });
}
if let Some((i, w)) = self.edge_ranges.next() {
let a = w[0];
@@ -522,8 +546,9 @@
}
impl<'a, N, E, Ty, Ix> IntoEdges for &'a Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Edges = Edges<'a, E, Ty, Ix>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
@@ -532,8 +557,9 @@
}
impl<N, E, Ty, Ix> GraphBase for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeId = NodeIndex<Ix>;
type EdgeId = EdgeIndex; // index into edges vector
@@ -542,8 +568,9 @@
use fixedbitset::FixedBitSet;
impl<N, E, Ty, Ix> Visitable for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Map = FixedBitSet;
fn visit_map(&self) -> FixedBitSet {
@@ -563,7 +590,8 @@
}
impl<'a, Ix> Iterator for Neighbors<'a, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type Item = NodeIndex<Ix>;
@@ -577,8 +605,9 @@
}
impl<'a, N, E, Ty, Ix> IntoNeighbors for &'a Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Neighbors = Neighbors<'a, Ix>;
@@ -597,23 +626,32 @@
}
impl<N, E, Ty, Ix> NodeIndexable for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
- fn node_bound(&self) -> usize { self.node_count() }
- fn to_index(&self, a: Self::NodeId) -> usize { a.index() }
- fn from_index(&self, ix: usize) -> Self::NodeId { Ix::new(ix) }
+ fn node_bound(&self) -> usize {
+ self.node_count()
+ }
+ fn to_index(&self, a: Self::NodeId) -> usize {
+ a.index()
+ }
+ fn from_index(&self, ix: usize) -> Self::NodeId {
+ Ix::new(ix)
+ }
}
impl<N, E, Ty, Ix> NodeCompactIndexable for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
}
impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Output = N;
@@ -623,8 +661,9 @@
}
impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn index_mut(&mut self, ix: NodeIndex<Ix>) -> &mut N {
&mut self.node_weights[ix.index()]
@@ -637,7 +676,8 @@
}
impl<Ix> Iterator for NodeIdentifiers<Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type Item = NodeIndex<Ix>;
@@ -651,8 +691,9 @@
}
impl<'a, N, E, Ty, Ix> IntoNodeIdentifiers for &'a Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeIdentifiers = NodeIdentifiers<Ix>;
fn node_identifiers(self) -> Self::NodeIdentifiers {
@@ -664,8 +705,9 @@
}
impl<N, E, Ty, Ix> NodeCount for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_count(&self) -> usize {
(*self).node_count()
@@ -673,8 +715,9 @@
}
impl<N, E, Ty, Ix> GraphProp for Csr<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeType = Ty;
}
@@ -696,11 +739,11 @@
#[cfg(test)]
mod tests {
use super::Csr;
- use crate::Undirected;
+ use crate::algo::bellman_ford;
+ use crate::algo::tarjan_scc;
use crate::visit::Dfs;
use crate::visit::VisitMap;
- use crate::algo::tarjan_scc;
- use crate::algo::bellman_ford;
+ use crate::Undirected;
#[test]
fn csr1() {
@@ -727,11 +770,11 @@
#[test]
fn csr_undirected() {
- /*
- [ 1 . 1
- . . 1
- 1 1 1 ]
- */
+ /*
+ [ 1 . 1
+ . . 1
+ 1 1 1 ]
+ */
let mut m: Csr<(), (), Undirected> = Csr::with_nodes(3);
m.add_edge(0, 0, ());
@@ -749,11 +792,7 @@
#[test]
fn csr_from_error_1() {
// not sorted in source
- let m: Csr = Csr::from_sorted_edges(&[
- (0, 1),
- (1, 0),
- (0, 2),
- ]).unwrap();
+ let m: Csr = Csr::from_sorted_edges(&[(0, 1), (1, 0), (0, 2)]).unwrap();
println!("{:?}", m);
}
@@ -761,25 +800,14 @@
#[test]
fn csr_from_error_2() {
// not sorted in target
- let m: Csr = Csr::from_sorted_edges(&[
- (0, 1),
- (1, 0),
- (1, 2),
- (1, 1),
- ]).unwrap();
+ let m: Csr = Csr::from_sorted_edges(&[(0, 1), (1, 0), (1, 2), (1, 1)]).unwrap();
println!("{:?}", m);
}
#[test]
fn csr_from() {
- let m: Csr = Csr::from_sorted_edges(&[
- (0, 1),
- (0, 2),
- (1, 0),
- (1, 1),
- (2, 2),
- (2, 4),
- ]).unwrap();
+ let m: Csr =
+ Csr::from_sorted_edges(&[(0, 1), (0, 2), (1, 0), (1, 1), (2, 2), (2, 4)]).unwrap();
println!("{:?}", m);
assert_eq!(m.neighbors_slice(0), &[1, 2]);
assert_eq!(m.neighbors_slice(1), &[0, 1]);
@@ -797,15 +825,14 @@
(1, 1),
(1, 3),
(2, 2),
-
// disconnected subgraph
(4, 4),
(4, 5),
- ]).unwrap();
+ ])
+ .unwrap();
println!("{:?}", m);
let mut dfs = Dfs::new(&m, 0);
- while let Some(_) = dfs.next(&m) {
- }
+ while let Some(_) = dfs.next(&m) {}
for i in 0..m.node_count() - 2 {
assert!(dfs.discovered.is_visited(&i), "visited {}", i)
}
@@ -817,8 +844,7 @@
dfs.reset(&m);
dfs.move_to(0);
- while let Some(_) = dfs.next(&m) {
- }
+ while let Some(_) = dfs.next(&m) {}
for i in 0..m.node_count() {
assert!(dfs.discovered[i], "visited {}", i)
@@ -838,7 +864,8 @@
(4, 4),
(4, 5),
(5, 2),
- ]).unwrap();
+ ])
+ .unwrap();
println!("{:?}", m);
println!("{:?}", tarjan_scc(&m));
}
@@ -853,12 +880,12 @@
(1, 2, 1.),
(1, 3, 1.),
(2, 3, 3.),
-
(4, 5, 1.),
(5, 7, 2.),
(6, 7, 1.),
(7, 8, 3.),
- ]).unwrap();
+ ])
+ .unwrap();
println!("{:?}", m);
let result = bellman_ford(&m, 0).unwrap();
println!("{:?}", result);
@@ -877,7 +904,8 @@
(1, 2, 1.),
(1, 3, 1.),
(2, 3, 3.),
- ]).unwrap();
+ ])
+ .unwrap();
let result = bellman_ford(&m, 0);
assert!(result.is_err());
}
@@ -894,12 +922,12 @@
(1, 2, 1.),
(1, 3, 1.),
(2, 3, 3.),
-
(4, 5, 1.),
(5, 7, 2.),
(6, 7, 1.),
(7, 8, 3.),
- ]).unwrap();
+ ])
+ .unwrap();
let mut copy = Vec::new();
for e in m.edge_references() {
copy.push((e.source(), e.target(), *e.weight()));
diff --git a/src/data.rs b/src/data.rs
index bfe528d..7bb5411 100644
--- a/src/data.rs
+++ b/src/data.rs
@@ -1,23 +1,15 @@
//! Graph traits for associated data and graph construction.
-
-use crate::Graph;
-#[cfg(feature = "stable_graph")]
-use crate::stable_graph::StableGraph;
-use crate::{
- EdgeType,
-};
use crate::graph::IndexType;
#[cfg(feature = "graphmap")]
use crate::graphmap::{GraphMap, NodeTrait};
-use crate::visit::{
- Data,
- NodeCount,
- NodeIndexable,
- Reversed,
-};
+#[cfg(feature = "stable_graph")]
+use crate::stable_graph::StableGraph;
+use crate::visit::{Data, NodeCount, NodeIndexable, Reversed};
+use crate::EdgeType;
+use crate::Graph;
-trait_template!{
+trait_template! {
/// Access node and edge weights (associated data).
pub trait DataMap : Data {
@section self
@@ -27,12 +19,14 @@
}
macro_rules! access0 {
- ($e:expr) => ($e.0);
+ ($e:expr) => {
+ $e.0
+ };
}
-DataMap!{delegate_impl []}
-DataMap!{delegate_impl [['a, G], G, &'a mut G, deref_twice]}
-DataMap!{delegate_impl [[G], G, Reversed<G>, access0]}
+DataMap! {delegate_impl []}
+DataMap! {delegate_impl [['a, G], G, &'a mut G, deref_twice]}
+DataMap! {delegate_impl [[G], G, Reversed<G>, access0]}
trait_template! {
/// Access node and edge weights mutably.
@@ -43,43 +37,49 @@
}
}
-DataMapMut!{delegate_impl [['a, G], G, &'a mut G, deref_twice]}
-DataMapMut!{delegate_impl [[G], G, Reversed<G>, access0]}
+DataMapMut! {delegate_impl [['a, G], G, &'a mut G, deref_twice]}
+DataMapMut! {delegate_impl [[G], G, Reversed<G>, access0]}
/// A graph that can be extended with further nodes and edges
-pub trait Build : Data + NodeCount {
+pub trait Build: Data + NodeCount {
fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId;
/// Add a new edge. If parallel edges (duplicate) are not allowed and
/// the edge already exists, return `None`.
- fn add_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Option<Self::EdgeId> {
+ fn add_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Option<Self::EdgeId> {
Some(self.update_edge(a, b, weight))
}
/// Add or update the edge from `a` to `b`. Return the id of the affected
/// edge.
- fn update_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Self::EdgeId;
+ fn update_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Self::EdgeId;
}
/// A graph that can be created
-pub trait Create : Build + Default {
+pub trait Create: Build + Default {
fn with_capacity(nodes: usize, edges: usize) -> Self;
}
impl<N, E, Ty, Ix> Data for Graph<N, E, Ty, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
type NodeWeight = N;
type EdgeWeight = E;
}
impl<N, E, Ty, Ix> DataMap for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_weight(&self, id: Self::NodeId) -> Option<&Self::NodeWeight> {
self.node_weight(id)
@@ -90,8 +90,9 @@
}
impl<N, E, Ty, Ix> DataMapMut for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_weight_mut(&mut self, id: Self::NodeId) -> Option<&mut Self::NodeWeight> {
self.node_weight_mut(id)
@@ -103,8 +104,9 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> DataMap for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_weight(&self, id: Self::NodeId) -> Option<&Self::NodeWeight> {
self.node_weight(id)
@@ -116,8 +118,9 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> DataMapMut for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_weight_mut(&mut self, id: Self::NodeId) -> Option<&mut Self::NodeWeight> {
self.node_weight_mut(id)
@@ -128,65 +131,73 @@
}
impl<N, E, Ty, Ix> Build for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId {
self.add_node(weight)
}
- fn add_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Option<Self::EdgeId>
- {
+ fn add_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Option<Self::EdgeId> {
Some(self.add_edge(a, b, weight))
}
- fn update_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Self::EdgeId
- {
+ fn update_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Self::EdgeId {
self.update_edge(a, b, weight)
}
}
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> Build for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId {
self.add_node(weight)
}
- fn add_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Option<Self::EdgeId>
- {
+ fn add_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Option<Self::EdgeId> {
Some(self.add_edge(a, b, weight))
}
- fn update_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Self::EdgeId
- {
+ fn update_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Self::EdgeId {
self.update_edge(a, b, weight)
}
}
#[cfg(feature = "graphmap")]
impl<N, E, Ty> Build for GraphMap<N, E, Ty>
- where Ty: EdgeType,
- N: NodeTrait,
+where
+ Ty: EdgeType,
+ N: NodeTrait,
{
fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId {
self.add_node(weight)
}
- fn add_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Option<Self::EdgeId>
- {
+ fn add_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Option<Self::EdgeId> {
if self.contains_edge(a, b) {
None
} else {
@@ -195,20 +206,21 @@
Some((a, b))
}
}
- fn update_edge(&mut self,
- a: Self::NodeId,
- b: Self::NodeId,
- weight: Self::EdgeWeight) -> Self::EdgeId
- {
+ fn update_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Self::EdgeId {
self.add_edge(a, b, weight);
(a, b)
}
}
-
impl<N, E, Ty, Ix> Create for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn with_capacity(nodes: usize, edges: usize) -> Self {
Self::with_capacity(nodes, edges)
@@ -217,8 +229,9 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> Create for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn with_capacity(nodes: usize, edges: usize) -> Self {
Self::with_capacity(nodes, edges)
@@ -227,8 +240,9 @@
#[cfg(feature = "graphmap")]
impl<N, E, Ty> Create for GraphMap<N, E, Ty>
- where Ty: EdgeType,
- N: NodeTrait,
+where
+ Ty: EdgeType,
+ N: NodeTrait,
{
fn with_capacity(nodes: usize, edges: usize) -> Self {
Self::with_capacity(nodes, edges)
@@ -243,22 +257,21 @@
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Element<N, E> {
/// A graph node.
- Node {
- weight: N,
- },
+ Node { weight: N },
/// A graph edge.
Edge {
source: usize,
target: usize,
weight: E,
- }
+ },
}
/// Create a graph from an iterator of elements.
-pub trait FromElements : Create {
+pub trait FromElements: Create {
fn from_elements<I>(iterable: I) -> Self
- where Self: Sized,
- I: IntoIterator<Item=Element<Self::NodeWeight, Self::EdgeWeight>>,
+ where
+ Self: Sized,
+ I: IntoIterator<Item = Element<Self::NodeWeight, Self::EdgeWeight>>,
{
let mut gr = Self::with_capacity(0, 0);
// usize -> NodeId map
@@ -268,19 +281,23 @@
Element::Node { weight } => {
map.push(gr.add_node(weight));
}
- Element::Edge { source, target, weight } => {
+ Element::Edge {
+ source,
+ target,
+ weight,
+ } => {
gr.add_edge(map[source], map[target], weight);
}
}
}
gr
}
-
}
fn from_elements_indexable<G, I>(iterable: I) -> G
- where G: Create + NodeIndexable,
- I: IntoIterator<Item=Element<G::NodeWeight, G::EdgeWeight>>,
+where
+ G: Create + NodeIndexable,
+ I: IntoIterator<Item = Element<G::NodeWeight, G::EdgeWeight>>,
{
let mut gr = G::with_capacity(0, 0);
let map = |gr: &G, i| gr.from_index(i);
@@ -289,7 +306,11 @@
Element::Node { weight } => {
gr.add_node(weight);
}
- Element::Edge { source, target, weight } => {
+ Element::Edge {
+ source,
+ target,
+ weight,
+ } => {
let from = map(&gr, source);
let to = map(&gr, target);
gr.add_edge(from, to, weight);
@@ -300,12 +321,14 @@
}
impl<N, E, Ty, Ix> FromElements for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn from_elements<I>(iterable: I) -> Self
- where Self: Sized,
- I: IntoIterator<Item=Element<Self::NodeWeight, Self::EdgeWeight>>,
+ where
+ Self: Sized,
+ I: IntoIterator<Item = Element<Self::NodeWeight, Self::EdgeWeight>>,
{
from_elements_indexable(iterable)
}
@@ -313,12 +336,14 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> FromElements for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn from_elements<I>(iterable: I) -> Self
- where Self: Sized,
- I: IntoIterator<Item=Element<Self::NodeWeight, Self::EdgeWeight>>,
+ where
+ Self: Sized,
+ I: IntoIterator<Item = Element<Self::NodeWeight, Self::EdgeWeight>>,
{
from_elements_indexable(iterable)
}
@@ -326,19 +351,21 @@
#[cfg(feature = "graphmap")]
impl<N, E, Ty> FromElements for GraphMap<N, E, Ty>
- where Ty: EdgeType,
- N: NodeTrait,
+where
+ Ty: EdgeType,
+ N: NodeTrait,
{
fn from_elements<I>(iterable: I) -> Self
- where Self: Sized,
- I: IntoIterator<Item=Element<Self::NodeWeight, Self::EdgeWeight>>,
+ where
+ Self: Sized,
+ I: IntoIterator<Item = Element<Self::NodeWeight, Self::EdgeWeight>>,
{
from_elements_indexable(iterable)
}
}
/// Iterator adaptors for iterators of `Element`.
-pub trait ElementIterator<N, E> : Iterator<Item=Element<N, E>> {
+pub trait ElementIterator<N, E>: Iterator<Item = Element<N, E>> {
/// Create an iterator adaptor that filters graph elements.
///
/// The function `f` is called with each element and if its return value
@@ -349,8 +376,9 @@
/// This filter adapts the edge source and target indices in the
/// stream so that they are correct after the removals.
fn filter_elements<F>(self, f: F) -> FilterElements<Self, F>
- where Self: Sized,
- F: FnMut(Element<&mut N, &mut E>) -> bool,
+ where
+ Self: Sized,
+ F: FnMut(Element<&mut N, &mut E>) -> bool,
{
FilterElements {
iter: self,
@@ -361,8 +389,7 @@
}
}
-impl<N, E, I: ?Sized> ElementIterator<N, E> for I
- where I: Iterator<Item=Element<N, E>> { }
+impl<N, E, I: ?Sized> ElementIterator<N, E> for I where I: Iterator<Item = Element<N, E>> {}
/// An iterator that filters graph elements.
///
@@ -377,8 +404,9 @@
}
impl<I, F, N, E> Iterator for FilterElements<I, F>
- where I: Iterator<Item=Element<N, E>>,
- F: FnMut(Element<&mut N, &mut E>) -> bool,
+where
+ I: Iterator<Item = Element<N, E>>,
+ F: FnMut(Element<&mut N, &mut E>) -> bool,
{
type Item = Element<N, E>;
@@ -390,10 +418,21 @@
};
let keep = (self.f)(match elt {
Element::Node { ref mut weight } => Element::Node { weight },
- Element::Edge { source, target, ref mut weight }
- => Element::Edge { source, target, weight },
+ Element::Edge {
+ source,
+ target,
+ ref mut weight,
+ } => Element::Edge {
+ source,
+ target,
+ weight,
+ },
});
- let is_node = if let Element::Node { .. } = elt { true } else { false };
+ let is_node = if let Element::Node { .. } = elt {
+ true
+ } else {
+ false
+ };
if !keep && is_node {
self.map.push(self.node_index);
}
@@ -427,7 +466,7 @@
Err(i) => *target -= i,
}
}
- Element::Node { .. } => { }
+ Element::Node { .. } => {}
}
return Some(elt);
}
diff --git a/src/dijkstra.rs b/src/dijkstra.rs
index b856e60..77852b9 100644
--- a/src/dijkstra.rs
+++ b/src/dijkstra.rs
@@ -1,22 +1,11 @@
-use std::collections::{
- HashMap,
- BinaryHeap,
-};
-use std::collections::hash_map::Entry::{
- Occupied,
- Vacant,
-};
+use std::collections::hash_map::Entry::{Occupied, Vacant};
+use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
-use crate::scored::MinScored;
-use super::visit::{
- Visitable,
- VisitMap,
- IntoEdges,
- EdgeRef,
-};
+use super::visit::{EdgeRef, IntoEdges, VisitMap, Visitable};
use crate::algo::Measure;
+use crate::scored::MinScored;
/// \[Generic\] Dijkstra's shortest path algorithm.
///
@@ -80,13 +69,17 @@
/// assert_eq!(res, expected_res);
/// // z is not inside res because there is not path from b to z.
/// ```
-pub fn dijkstra<G, F, K>(graph: G, start: G::NodeId, goal: Option<G::NodeId>,
- mut edge_cost: F)
- -> HashMap<G::NodeId, K>
- where G: IntoEdges + Visitable,
- G::NodeId: Eq + Hash,
- F: FnMut(G::EdgeRef) -> K,
- K: Measure + Copy,
+pub fn dijkstra<G, F, K>(
+ graph: G,
+ start: G::NodeId,
+ goal: Option<G::NodeId>,
+ mut edge_cost: F,
+) -> HashMap<G::NodeId, K>
+where
+ G: IntoEdges + Visitable,
+ G::NodeId: Eq + Hash,
+ F: FnMut(G::EdgeRef) -> K,
+ K: Measure + Copy,
{
let mut visited = graph.visit_map();
let mut scores = HashMap::new();
@@ -97,24 +90,26 @@
visit_next.push(MinScored(zero_score, start));
while let Some(MinScored(node_score, node)) = visit_next.pop() {
if visited.is_visited(&node) {
- continue
+ continue;
}
if goal.as_ref() == Some(&node) {
- break
+ break;
}
for edge in graph.edges(node) {
let next = edge.target();
if visited.is_visited(&next) {
- continue
+ continue;
}
let mut next_score = node_score + edge_cost(edge);
match scores.entry(next) {
- Occupied(ent) => if next_score < *ent.get() {
- *ent.into_mut() = next_score;
+ Occupied(ent) => {
+ if next_score < *ent.get() {
+ *ent.into_mut() = next_score;
//predecessor.insert(next.clone(), node.clone());
- } else {
- next_score = *ent.get();
- },
+ } else {
+ next_score = *ent.get();
+ }
+ }
Vacant(ent) => {
ent.insert(next_score);
//predecessor.insert(next.clone(), node.clone());
diff --git a/src/dot.rs b/src/dot.rs
index 3ee079e..b9f44dc 100644
--- a/src/dot.rs
+++ b/src/dot.rs
@@ -2,7 +2,7 @@
use std::fmt::{self, Display, Write};
-use crate::visit::{GraphRef};
+use crate::visit::GraphRef;
/// `Dot` implements output to graphviz .dot format for a graph.
///
@@ -54,7 +54,10 @@
static EDGE: [&str; 2] = ["--", "->"];
static INDENT: &str = " ";
-impl<'a, G> Dot<'a, G> where G: GraphRef {
+impl<'a, G> Dot<'a, G>
+where
+ G: GraphRef,
+{
/// Create a `Dot` formatting wrapper with default configuration.
pub fn new(graph: G) -> Self {
Self::with_config(graph, &[])
@@ -62,10 +65,7 @@
/// Create a `Dot` formatting wrapper with custom configuration.
pub fn with_config(graph: G, config: &'a [Config]) -> Self {
- Dot {
- graph,
- config,
- }
+ Dot { graph, config }
}
}
@@ -86,18 +86,23 @@
_Incomplete(()),
}
-use crate::visit::{ IntoNodeReferences, NodeIndexable, IntoEdgeReferences, EdgeRef};
-use crate::visit::{ Data, NodeRef, GraphProp, };
+use crate::visit::{Data, GraphProp, NodeRef};
+use crate::visit::{EdgeRef, IntoEdgeReferences, IntoNodeReferences, NodeIndexable};
-impl<'a, G> Dot<'a, G>
-{
- fn graph_fmt<NF, EF, NW, EW>(&self, g: G, f: &mut fmt::Formatter,
- mut node_fmt: NF, mut edge_fmt: EF) -> fmt::Result
- where G: NodeIndexable + IntoNodeReferences + IntoEdgeReferences,
- G: GraphProp,
- G: Data<NodeWeight=NW, EdgeWeight=EW>,
- NF: FnMut(&NW, &mut dyn FnMut(&dyn Display) -> fmt::Result) -> fmt::Result,
- EF: FnMut(&EW, &mut dyn FnMut(&dyn Display) -> fmt::Result) -> fmt::Result,
+impl<'a, G> Dot<'a, G> {
+ fn graph_fmt<NF, EF, NW, EW>(
+ &self,
+ g: G,
+ f: &mut fmt::Formatter,
+ mut node_fmt: NF,
+ mut edge_fmt: EF,
+ ) -> fmt::Result
+ where
+ G: NodeIndexable + IntoNodeReferences + IntoEdgeReferences,
+ G: GraphProp,
+ G: Data<NodeWeight = NW, EdgeWeight = EW>,
+ NF: FnMut(&NW, &mut dyn FnMut(&dyn Display) -> fmt::Result) -> fmt::Result,
+ EF: FnMut(&EW, &mut dyn FnMut(&dyn Display) -> fmt::Result) -> fmt::Result,
{
if !self.config.contains(&Config::GraphContentOnly) {
writeln!(f, "{} {{", TYPE[g.is_directed() as usize])?;
@@ -113,15 +118,17 @@
node_fmt(node.weight(), &mut |d| Escaped(d).fmt(f))?;
writeln!(f, "\"]")?;
}
-
}
// output all edges
for (i, edge) in g.edge_references().enumerate() {
- write!(f, "{}{} {} {}",
- INDENT,
- g.to_index(edge.source()),
- EDGE[g.is_directed() as usize],
- g.to_index(edge.target()))?;
+ write!(
+ f,
+ "{}{} {} {}",
+ INDENT,
+ g.to_index(edge.source()),
+ EDGE[g.is_directed() as usize],
+ g.to_index(edge.target())
+ )?;
if self.config.contains(&Config::EdgeNoLabel) {
writeln!(f)?;
} else if self.config.contains(&Config::EdgeIndexLabel) {
@@ -141,9 +148,10 @@
}
impl<'a, G> fmt::Display for Dot<'a, G>
- where G: IntoEdgeReferences + IntoNodeReferences + NodeIndexable + GraphProp,
- G::EdgeWeight: fmt::Display,
- G::NodeWeight: fmt::Display,
+where
+ G: IntoEdgeReferences + IntoNodeReferences + NodeIndexable + GraphProp,
+ G::EdgeWeight: fmt::Display,
+ G::NodeWeight: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.graph_fmt(self.graph, f, |n, cb| cb(n), |e, cb| cb(e))
@@ -151,14 +159,18 @@
}
impl<'a, G> fmt::Debug for Dot<'a, G>
- where G: IntoEdgeReferences + IntoNodeReferences + NodeIndexable + GraphProp,
- G::EdgeWeight: fmt::Debug,
- G::NodeWeight: fmt::Debug,
+where
+ G: IntoEdgeReferences + IntoNodeReferences + NodeIndexable + GraphProp,
+ G::EdgeWeight: fmt::Debug,
+ G::NodeWeight: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.graph_fmt(self.graph, f,
- |n, cb| cb(&DebugFmt(n)),
- |e, cb| cb(&DebugFmt(e)))
+ self.graph_fmt(
+ self.graph,
+ f,
+ |n, cb| cb(&DebugFmt(n)),
+ |e, cb| cb(&DebugFmt(e)),
+ )
}
}
@@ -166,7 +178,8 @@
struct Escaper<W>(W);
impl<W> fmt::Write for Escaper<W>
- where W: fmt::Write
+where
+ W: fmt::Write,
{
fn write_str(&mut self, s: &str) -> fmt::Result {
for c in s.chars() {
@@ -190,7 +203,8 @@
struct Escaped<T>(T);
impl<T> fmt::Display for Escaped<T>
- where T: fmt::Display
+where
+ T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
@@ -205,7 +219,8 @@
struct DebugFmt<T>(T);
impl<T> fmt::Display for DebugFmt<T>
- where T: fmt::Debug
+where
+ T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
diff --git a/src/generate.rs b/src/generate.rs
index e717239..9dc7dbf 100644
--- a/src/generate.rs
+++ b/src/generate.rs
@@ -3,8 +3,8 @@
//! ***Unstable: API may change at any time.*** Depends on `feature = "generate"`.
//!
-use crate::{Graph, Directed, EdgeType};
use crate::graph::NodeIndex;
+use crate::{Directed, EdgeType, Graph};
// A DAG has the property that the adjacency matrix is lower triangular,
// diagonal zero.
@@ -46,7 +46,7 @@
acyclic: true,
selfloops: false,
nodes: nodes,
- nedges:nedges,
+ nedges: nedges,
bits: !0,
g: Graph::with_capacity(nodes, nedges),
}
@@ -92,7 +92,11 @@
// d 3 4 5 x
let mut bit = 0;
for i in 0..self.nodes {
- let start = if self.acyclic || !self.g.is_directed() { i } else { 0 };
+ let start = if self.acyclic || !self.g.is_directed() {
+ i
+ } else {
+ 0
+ };
for j in start..self.nodes {
if i == j && !self.selfloops {
continue;
diff --git a/src/graph_impl/frozen.rs b/src/graph_impl/frozen.rs
index bb96618..1ba06d9 100644
--- a/src/graph_impl/frozen.rs
+++ b/src/graph_impl/frozen.rs
@@ -1,18 +1,15 @@
-
use std::ops::{Deref, Index, IndexMut};
-use crate::graph::Graph;
use super::Frozen;
-use crate::graph::{IndexType, GraphIndex};
-use crate::{
- Direction,
- EdgeType,
-};
-use crate::visit::{Data, IntoNodeIdentifiers, GraphProp, NodeIndexable, IntoNeighborsDirected};
-use crate::visit::{IntoNeighbors, IntoNodeReferences, IntoEdgeReferences, Visitable};
-use crate::visit::{NodeCompactIndexable, GetAdjacencyMatrix, NodeCount, IntoEdges, IntoEdgesDirected};
use crate::data::{DataMap, DataMapMut};
-
+use crate::graph::Graph;
+use crate::graph::{GraphIndex, IndexType};
+use crate::visit::{Data, GraphProp, IntoNeighborsDirected, IntoNodeIdentifiers, NodeIndexable};
+use crate::visit::{
+ GetAdjacencyMatrix, IntoEdges, IntoEdgesDirected, NodeCompactIndexable, NodeCount,
+};
+use crate::visit::{IntoEdgeReferences, IntoNeighbors, IntoNodeReferences, Visitable};
+use crate::{Direction, EdgeType};
impl<'a, G> Frozen<'a, G> {
/// Create a new `Frozen` from a mutable reference to a graph.
@@ -25,61 +22,75 @@
/// functionality in the underlying graph.
impl<'a, G> Deref for Frozen<'a, G> {
type Target = G;
- fn deref(&self) -> &G { self.0 }
+ fn deref(&self) -> &G {
+ self.0
+ }
}
impl<'a, G, I> Index<I> for Frozen<'a, G>
- where G: Index<I>
+where
+ G: Index<I>,
{
type Output = G::Output;
- fn index(&self, i: I) -> &G::Output { self.0.index(i) }
+ fn index(&self, i: I) -> &G::Output {
+ self.0.index(i)
+ }
}
impl<'a, G, I> IndexMut<I> for Frozen<'a, G>
- where G: IndexMut<I>
+where
+ G: IndexMut<I>,
{
- fn index_mut(&mut self, i: I) -> &mut G::Output { self.0.index_mut(i) }
+ fn index_mut(&mut self, i: I) -> &mut G::Output {
+ self.0.index_mut(i)
+ }
}
impl<'a, N, E, Ty, Ix> Frozen<'a, Graph<N, E, Ty, Ix>>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// Index the `Graph` by two indices, any combination of
/// node or edge indices is fine.
///
/// **Panics** if the indices are equal or if they are out of bounds.
- pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
- -> (&mut <Graph<N, E, Ty, Ix> as Index<T>>::Output,
- &mut <Graph<N, E, Ty, Ix> as Index<U>>::Output)
- where Graph<N, E, Ty, Ix>: IndexMut<T> + IndexMut<U>,
- T: GraphIndex,
- U: GraphIndex,
+ pub fn index_twice_mut<T, U>(
+ &mut self,
+ i: T,
+ j: U,
+ ) -> (
+ &mut <Graph<N, E, Ty, Ix> as Index<T>>::Output,
+ &mut <Graph<N, E, Ty, Ix> as Index<U>>::Output,
+ )
+ where
+ Graph<N, E, Ty, Ix>: IndexMut<T> + IndexMut<U>,
+ T: GraphIndex,
+ U: GraphIndex,
{
self.0.index_twice_mut(i, j)
}
}
macro_rules! access0 {
- ($e:expr) => ($e.0);
+ ($e:expr) => {
+ $e.0
+ };
}
-Data!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-DataMap!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-DataMapMut!{delegate_impl [['a, G], G, Frozen<'a, G>, access0]}
-GetAdjacencyMatrix!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-IntoEdgeReferences!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoEdges!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoEdgesDirected!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoNeighbors!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoNeighborsDirected!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoNodeIdentifiers!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-IntoNodeReferences!{delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
-NodeCompactIndexable!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-NodeCount!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-NodeIndexable!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-GraphProp!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-Visitable!{delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
-
-
-
+Data! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+DataMap! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+DataMapMut! {delegate_impl [['a, G], G, Frozen<'a, G>, access0]}
+GetAdjacencyMatrix! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+IntoEdgeReferences! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoEdges! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoEdgesDirected! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoNeighbors! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoNeighborsDirected! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoNodeIdentifiers! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+IntoNodeReferences! {delegate_impl [['a, 'b, G], G, &'b Frozen<'a, G>, deref_twice]}
+NodeCompactIndexable! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+NodeCount! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+NodeIndexable! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+GraphProp! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
+Visitable! {delegate_impl [['a, G], G, Frozen<'a, G>, deref_twice]}
diff --git a/src/graph_impl/mod.rs b/src/graph_impl/mod.rs
index 0d7a2ed..9fb43b3 100644
--- a/src/graph_impl/mod.rs
+++ b/src/graph_impl/mod.rs
@@ -7,28 +7,17 @@
use std::ops::{Index, IndexMut, Range};
use std::slice;
-use crate::{
- Direction, Outgoing, Incoming,
- Undirected,
- Directed,
- EdgeType,
- IntoWeightedEdge,
-};
+use crate::{Directed, Direction, EdgeType, Incoming, IntoWeightedEdge, Outgoing, Undirected};
-use crate::iter_format::{
- IterFormatExt,
- NoPretty,
- DebugMap,
-};
+use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
-use crate::visit::EdgeRef;
-use crate::visit::{IntoNodeReferences, IntoEdges, IntoEdgesDirected};
use crate::util::enumerate;
+use crate::visit::EdgeRef;
+use crate::visit::{IntoEdges, IntoEdgesDirected, IntoNodeReferences};
#[cfg(feature = "serde-1")]
mod serialization;
-
/// The default integer type for graph indices.
/// `u32` is the default to reduce the size of the graph's data and improve
/// performance in the common case.
@@ -41,8 +30,7 @@
///
/// Marked `unsafe` because: the trait must faithfully preserve
/// and convert index values.
-pub unsafe trait IndexType : Copy + Default + Hash + Ord + fmt::Debug + 'static
-{
+pub unsafe trait IndexType: Copy + Default + Hash + Ord + fmt::Debug + 'static {
fn new(x: usize) -> Self;
fn index(&self) -> usize;
fn max() -> Self;
@@ -50,60 +38,81 @@
unsafe impl IndexType for usize {
#[inline(always)]
- fn new(x: usize) -> Self { x }
+ fn new(x: usize) -> Self {
+ x
+ }
#[inline(always)]
- fn index(&self) -> Self { *self }
+ fn index(&self) -> Self {
+ *self
+ }
#[inline(always)]
- fn max() -> Self { ::std::usize::MAX }
+ fn max() -> Self {
+ ::std::usize::MAX
+ }
}
unsafe impl IndexType for u32 {
#[inline(always)]
- fn new(x: usize) -> Self { x as u32 }
+ fn new(x: usize) -> Self {
+ x as u32
+ }
#[inline(always)]
- fn index(&self) -> usize { *self as usize }
+ fn index(&self) -> usize {
+ *self as usize
+ }
#[inline(always)]
- fn max() -> Self { ::std::u32::MAX }
+ fn max() -> Self {
+ ::std::u32::MAX
+ }
}
unsafe impl IndexType for u16 {
#[inline(always)]
- fn new(x: usize) -> Self { x as u16 }
+ fn new(x: usize) -> Self {
+ x as u16
+ }
#[inline(always)]
- fn index(&self) -> usize { *self as usize }
+ fn index(&self) -> usize {
+ *self as usize
+ }
#[inline(always)]
- fn max() -> Self { ::std::u16::MAX }
+ fn max() -> Self {
+ ::std::u16::MAX
+ }
}
unsafe impl IndexType for u8 {
#[inline(always)]
- fn new(x: usize) -> Self { x as u8 }
+ fn new(x: usize) -> Self {
+ x as u8
+ }
#[inline(always)]
- fn index(&self) -> usize { *self as usize }
+ fn index(&self) -> usize {
+ *self as usize
+ }
#[inline(always)]
- fn max() -> Self { ::std::u8::MAX }
+ fn max() -> Self {
+ ::std::u8::MAX
+ }
}
/// Node identifier.
#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
-pub struct NodeIndex<Ix=DefaultIx>(Ix);
+pub struct NodeIndex<Ix = DefaultIx>(Ix);
-impl<Ix: IndexType> NodeIndex<Ix>
-{
+impl<Ix: IndexType> NodeIndex<Ix> {
#[inline]
pub fn new(x: usize) -> Self {
NodeIndex(IndexType::new(x))
}
#[inline]
- pub fn index(self) -> usize
- {
+ pub fn index(self) -> usize {
self.0.index()
}
#[inline]
- pub fn end() -> Self
- {
+ pub fn end() -> Self {
NodeIndex(IndexType::max())
}
@@ -113,36 +122,39 @@
}
impl<Ix: IndexType> From<Ix> for NodeIndex<Ix> {
- fn from(ix: Ix) -> Self { NodeIndex(ix) }
+ fn from(ix: Ix) -> Self {
+ NodeIndex(ix)
+ }
}
-impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix>
-{
+impl<Ix: fmt::Debug> fmt::Debug for NodeIndex<Ix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "NodeIndex({:?})", self.0)
}
}
/// Short version of `NodeIndex::new`
-pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> { NodeIndex::new(index) }
+pub fn node_index<Ix: IndexType>(index: usize) -> NodeIndex<Ix> {
+ NodeIndex::new(index)
+}
/// Short version of `EdgeIndex::new`
-pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> { EdgeIndex::new(index) }
+pub fn edge_index<Ix: IndexType>(index: usize) -> EdgeIndex<Ix> {
+ EdgeIndex::new(index)
+}
/// Edge identifier.
#[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
-pub struct EdgeIndex<Ix=DefaultIx>(Ix);
+pub struct EdgeIndex<Ix = DefaultIx>(Ix);
-impl<Ix: IndexType> EdgeIndex<Ix>
-{
+impl<Ix: IndexType> EdgeIndex<Ix> {
#[inline]
pub fn new(x: usize) -> Self {
EdgeIndex(IndexType::new(x))
}
#[inline]
- pub fn index(self) -> usize
- {
+ pub fn index(self) -> usize {
self.0.index()
}
@@ -159,11 +171,12 @@
}
impl<Ix: IndexType> From<Ix> for EdgeIndex<Ix> {
- fn from(ix: Ix) -> Self { EdgeIndex(ix) }
+ fn from(ix: Ix) -> Self {
+ EdgeIndex(ix)
+ }
}
-impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix>
-{
+impl<Ix: fmt::Debug> fmt::Debug for EdgeIndex<Ix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EdgeIndex({:?})", self.0)
}
@@ -195,24 +208,21 @@
next: [EdgeIndex<Ix>; 2],
}
-impl<E, Ix> Clone for Node<E, Ix> where E: Clone, Ix: Copy {
- clone_fields!(Node,
- weight,
- next,
- );
+impl<E, Ix> Clone for Node<E, Ix>
+where
+ E: Clone,
+ Ix: Copy,
+{
+ clone_fields!(Node, weight, next,);
}
-
-impl<N, Ix: IndexType> Node<N, Ix>
-{
+impl<N, Ix: IndexType> Node<N, Ix> {
/// Accessor for data structure internals: the first edge in the given direction.
- pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix>
- {
+ pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
self.next[dir.index()]
}
}
-
/// The graph's edge type.
#[derive(Debug)]
pub struct Edge<E, Ix = DefaultIx> {
@@ -224,31 +234,27 @@
node: [NodeIndex<Ix>; 2],
}
-impl<E, Ix> Clone for Edge<E, Ix> where E: Clone, Ix: Copy {
- clone_fields!(Edge,
- weight,
- next,
- node,
- );
+impl<E, Ix> Clone for Edge<E, Ix>
+where
+ E: Clone,
+ Ix: Copy,
+{
+ clone_fields!(Edge, weight, next, node,);
}
-impl<E, Ix: IndexType> Edge<E, Ix>
-{
+impl<E, Ix: IndexType> Edge<E, Ix> {
/// Accessor for data structure internals: the next edge for the given direction.
- pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix>
- {
+ pub fn next_edge(&self, dir: Direction) -> EdgeIndex<Ix> {
self.next[dir.index()]
}
/// Return the source node index.
- pub fn source(&self) -> NodeIndex<Ix>
- {
+ pub fn source(&self) -> NodeIndex<Ix> {
self.node[0]
}
/// Return the target node index.
- pub fn target(&self) -> NodeIndex<Ix>
- {
+ pub fn target(&self) -> NodeIndex<Ix> {
self.node[1]
}
}
@@ -341,10 +347,11 @@
/// *2* and *1*.
pub type UnGraph<N, E, Ix = DefaultIx> = Graph<N, E, Undirected, Ix>;
-
/// The resulting cloned graph has the same graph indices as `self`.
impl<N, E, Ty, Ix: IndexType> Clone for Graph<N, E, Ty, Ix>
- where N: Clone, E: Clone,
+where
+ N: Clone,
+ E: Clone,
{
fn clone(&self) -> Self {
Graph {
@@ -362,34 +369,44 @@
}
impl<N, E, Ty, Ix> fmt::Debug for Graph<N, E, Ty, Ix>
- where N: fmt::Debug,
- E: fmt::Debug,
- Ty: EdgeType,
- Ix: IndexType,
+where
+ N: fmt::Debug,
+ E: fmt::Debug,
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- let etype = if self.is_directed() { "Directed" } else { "Undirected" };
+ let etype = if self.is_directed() {
+ "Directed"
+ } else {
+ "Undirected"
+ };
let mut fmt_struct = f.debug_struct("Graph");
fmt_struct.field("Ty", &etype);
fmt_struct.field("node_count", &self.node_count());
fmt_struct.field("edge_count", &self.edge_count());
if self.edge_count() > 0 {
- fmt_struct.field("edges",
- &self.edges
- .iter()
- .map(|e| NoPretty((e.source().index(), e.target().index())))
- .format(", "));
+ fmt_struct.field(
+ "edges",
+ &self
+ .edges
+ .iter()
+ .map(|e| NoPretty((e.source().index(), e.target().index())))
+ .format(", "),
+ );
}
// skip weights if they are ZST!
if size_of::<N>() != 0 {
- fmt_struct.field("node weights", &DebugMap(|| self.nodes.iter()
- .map(|n| &n.weight)
- .enumerate()));
+ fmt_struct.field(
+ "node weights",
+ &DebugMap(|| self.nodes.iter().map(|n| &n.weight).enumerate()),
+ );
}
if size_of::<E>() != 0 {
- fmt_struct.field("edge weights", &DebugMap(|| self.edges.iter()
- .map(|n| &n.weight)
- .enumerate()));
+ fmt_struct.field(
+ "edge weights",
+ &DebugMap(|| self.edges.iter().map(|n| &n.weight).enumerate()),
+ );
}
fmt_struct.finish()
}
@@ -419,63 +436,65 @@
}
}
-impl<N, E> Graph<N, E, Directed>
-{
+impl<N, E> Graph<N, E, Directed> {
/// Create a new `Graph` with directed edges.
///
/// This is a convenience method. Use `Graph::with_capacity` or `Graph::default` for
/// a constructor that is generic in all the type parameters of `Graph`.
- pub fn new() -> Self
- {
- Graph{nodes: Vec::new(), edges: Vec::new(),
- ty: PhantomData}
+ pub fn new() -> Self {
+ Graph {
+ nodes: Vec::new(),
+ edges: Vec::new(),
+ ty: PhantomData,
+ }
}
}
-impl<N, E> Graph<N, E, Undirected>
-{
+impl<N, E> Graph<N, E, Undirected> {
/// Create a new `Graph` with undirected edges.
///
/// This is a convenience method. Use `Graph::with_capacity` or `Graph::default` for
/// a constructor that is generic in all the type parameters of `Graph`.
- pub fn new_undirected() -> Self
- {
- Graph{nodes: Vec::new(), edges: Vec::new(),
- ty: PhantomData}
+ pub fn new_undirected() -> Self {
+ Graph {
+ nodes: Vec::new(),
+ edges: Vec::new(),
+ ty: PhantomData,
+ }
}
}
impl<N, E, Ty, Ix> Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// Create a new `Graph` with estimated capacity.
- pub fn with_capacity(nodes: usize, edges: usize) -> Self
- {
- Graph{nodes: Vec::with_capacity(nodes), edges: Vec::with_capacity(edges),
- ty: PhantomData}
+ pub fn with_capacity(nodes: usize, edges: usize) -> Self {
+ Graph {
+ nodes: Vec::with_capacity(nodes),
+ edges: Vec::with_capacity(edges),
+ ty: PhantomData,
+ }
}
/// Return the number of nodes (vertices) in the graph.
///
/// Computes in **O(1)** time.
- pub fn node_count(&self) -> usize
- {
+ pub fn node_count(&self) -> usize {
self.nodes.len()
}
/// Return the number of edges in the graph.
///
/// Computes in **O(1)** time.
- pub fn edge_count(&self) -> usize
- {
+ pub fn edge_count(&self) -> usize {
self.edges.len()
}
/// Whether the graph has directed edges or not.
#[inline]
- pub fn is_directed(&self) -> bool
- {
+ pub fn is_directed(&self) -> bool {
Ty::is_directed()
}
@@ -487,9 +506,11 @@
///
/// **Panics** if the Graph is at the maximum number of nodes for its index
/// type (N/A if usize).
- pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix>
- {
- let node = Node{weight, next: [EdgeIndex::end(), EdgeIndex::end()]};
+ pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
+ let node = Node {
+ weight,
+ next: [EdgeIndex::end(), EdgeIndex::end()],
+ };
let node_idx = NodeIndex::new(self.nodes.len());
// check for max capacity, except if we use usize
assert!(<Ix as IndexType>::max().index() == !0 || NodeIndex::end() != node_idx);
@@ -500,16 +521,14 @@
/// Access the weight for node `a`.
///
/// Also available with indexing syntax: `&graph[a]`.
- pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N>
- {
+ pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
self.nodes.get(a.index()).map(|n| &n.weight)
}
/// Access the weight for node `a`, mutably.
///
/// Also available with indexing syntax: `&mut graph[a]`.
- pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N>
- {
+ pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
self.nodes.get_mut(a.index()).map(|n| &mut n.weight)
}
@@ -526,8 +545,7 @@
///
/// **Note:** `Graph` allows adding parallel (“duplicate”) edges. If you want
/// to avoid this, use [`.update_edge(a, b, weight)`](#method.update_edge) instead.
- pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>
- {
+ pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
let edge_idx = EdgeIndex::new(self.edges.len());
assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
let mut edge = Edge {
@@ -562,8 +580,7 @@
/// connected to `a` (and `b`, if the graph edges are undirected).
///
/// **Panics** if any of the nodes don't exist.
- pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix>
- {
+ pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
if let Some(ix) = self.find_edge(a, b) {
if let Some(ed) = self.edge_weight_mut(ix) {
*ed = weight;
@@ -576,24 +593,22 @@
/// Access the weight for edge `e`.
///
/// Also available with indexing syntax: `&graph[e]`.
- pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E>
- {
+ pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
self.edges.get(e.index()).map(|ed| &ed.weight)
}
/// Access the weight for edge `e`, mutably.
///
/// Also available with indexing syntax: `&mut graph[e]`.
- pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E>
- {
+ pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
self.edges.get_mut(e.index()).map(|ed| &mut ed.weight)
}
/// Access the source and target nodes for `e`.
- pub fn edge_endpoints(&self, e: EdgeIndex<Ix>)
- -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>
- {
- self.edges.get(e.index()).map(|ed| (ed.source(), ed.target()))
+ pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
+ self.edges
+ .get(e.index())
+ .map(|ed| (ed.source(), ed.target()))
}
/// Remove `a` from the graph if it exists, and return its weight.
@@ -608,8 +623,7 @@
/// edges, including *n* calls to `.remove_edge()` where *n* is the number
/// of edges with an endpoint in `a`, and including the edges with an
/// endpoint in the displaced node.
- pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N>
- {
+ pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
self.nodes.get(a.index())?;
for d in &DIRECTIONS {
let k = d.index();
@@ -618,7 +632,7 @@
loop {
let next = self.nodes[a.index()].next[k];
if next == EdgeIndex::end() {
- break
+ break;
}
let ret = self.remove_edge(next);
debug_assert!(ret.is_some());
@@ -656,17 +670,23 @@
/// For edge `e` with endpoints `edge_node`, replace links to it,
/// with links to `edge_next`.
- fn change_edge_links(&mut self, edge_node: [NodeIndex<Ix>; 2], e: EdgeIndex<Ix>,
- edge_next: [EdgeIndex<Ix>; 2])
- {
+ fn change_edge_links(
+ &mut self,
+ edge_node: [NodeIndex<Ix>; 2],
+ e: EdgeIndex<Ix>,
+ edge_next: [EdgeIndex<Ix>; 2],
+ ) {
for &d in &DIRECTIONS {
let k = d.index();
let node = match self.nodes.get_mut(edge_node[k].index()) {
Some(r) => r,
None => {
- debug_assert!(false, "Edge's endpoint dir={:?} index={:?} not found",
- d, edge_node[k]);
- return
+ debug_assert!(
+ false,
+ "Edge's endpoint dir={:?} index={:?} not found",
+ d, edge_node[k]
+ );
+ return;
}
};
let fst = node.next[k];
@@ -692,8 +712,7 @@
///
/// Computes in **O(e')** time, where **e'** is the size of four particular edge lists, for
/// the vertices of `e` and the vertices of another affected edge.
- pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E>
- {
+ pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
// every edge is part of two lists,
// outgoing and incoming edges.
// Remove it from both
@@ -707,8 +726,7 @@
self.remove_edge_adjust_indices(e)
}
- fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E>
- {
+ fn remove_edge_adjust_indices(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
// swap_remove the edge -- only the removed edge
// and the edge swapped into place are affected and need updating
// indices.
@@ -738,8 +756,7 @@
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
- pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
- {
+ pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
self.neighbors_directed(a, Outgoing)
}
@@ -762,8 +779,7 @@
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
- pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix>
- {
+ pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
let mut iter = self.neighbors_undirected(a);
if self.is_directed() {
let k = dir.index();
@@ -787,15 +803,14 @@
///
/// [1]: struct.Neighbors.html#method.detach
///
- pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
- {
+ pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
Neighbors {
skip_start: a,
edges: &self.edges,
next: match self.nodes.get(a.index()) {
None => [EdgeIndex::end(), EdgeIndex::end()],
Some(n) => n.next,
- }
+ },
}
}
@@ -821,8 +836,7 @@
///
/// Produces an empty iterator if the node `a` doesn't exist.<br>
/// Iterator element type is `EdgeReference<E, Ix>`.
- pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>
- {
+ pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
Edges {
skip_start: a,
edges: &self.edges,
@@ -841,8 +855,11 @@
/// - `Undirected`: All edges connected to `a`.
///
/// Iterator element type is `EdgeReference<E, Ix>`.
- pub fn edges_connecting(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> EdgesConnecting<E, Ty, Ix>
- {
+ pub fn edges_connecting(
+ &self,
+ a: NodeIndex<Ix>,
+ b: NodeIndex<Ix>,
+ ) -> EdgesConnecting<E, Ty, Ix> {
EdgesConnecting {
target_node: b,
edges: self.edges_directed(a, Direction::Outgoing),
@@ -862,25 +879,26 @@
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to `a` (and `b`, if the graph edges are undirected).
- pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>
- {
+ pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
if !self.is_directed() {
self.find_edge_undirected(a, b).map(|(ix, _)| ix)
} else {
match self.nodes.get(a.index()) {
None => None,
- Some(node) => self.find_edge_directed_from_node(node, b)
+ Some(node) => self.find_edge_directed_from_node(node, b),
}
}
}
- fn find_edge_directed_from_node(&self, node: &Node<N, Ix>, b: NodeIndex<Ix>)
- -> Option<EdgeIndex<Ix>>
- {
+ fn find_edge_directed_from_node(
+ &self,
+ node: &Node<N, Ix>,
+ b: NodeIndex<Ix>,
+ ) -> Option<EdgeIndex<Ix>> {
let mut edix = node.next[0];
while let Some(edge) = self.edges.get(edix.index()) {
if edge.node[1] == b {
- return Some(edix)
+ return Some(edix);
}
edix = edge.next[0];
}
@@ -894,23 +912,28 @@
/// Return the edge index and its directionality, with `Outgoing` meaning
/// from `a` to `b` and `Incoming` the reverse,
/// or `None` if the edge does not exist.
- pub fn find_edge_undirected(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<(EdgeIndex<Ix>, Direction)>
- {
+ pub fn find_edge_undirected(
+ &self,
+ a: NodeIndex<Ix>,
+ b: NodeIndex<Ix>,
+ ) -> Option<(EdgeIndex<Ix>, Direction)> {
match self.nodes.get(a.index()) {
None => None,
Some(node) => self.find_edge_undirected_from_node(node, b),
}
}
- fn find_edge_undirected_from_node(&self, node: &Node<N, Ix>, b: NodeIndex<Ix>)
- -> Option<(EdgeIndex<Ix>, Direction)>
- {
+ fn find_edge_undirected_from_node(
+ &self,
+ node: &Node<N, Ix>,
+ b: NodeIndex<Ix>,
+ ) -> Option<(EdgeIndex<Ix>, Direction)> {
for &d in &DIRECTIONS {
let k = d.index();
let mut edix = node.next[k];
while let Some(edge) = self.edges.get(edix.index()) {
if edge.node[1 - k] == b {
- return Some((edix, d))
+ return Some((edix, d));
}
edix = edge.next[k];
}
@@ -929,9 +952,12 @@
/// just the nodes without edges.
///
/// The whole iteration computes in **O(|V|)** time.
- pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix>
- {
- Externals{iter: self.nodes.iter().enumerate(), dir, ty: PhantomData}
+ pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
+ Externals {
+ iter: self.nodes.iter().enumerate(),
+ dir,
+ ty: PhantomData,
+ }
}
/// Return an iterator over the node indices of the graph.
@@ -947,21 +973,28 @@
/// let index = g.node_indices().find(|i| g[*i] == "book").unwrap();
/// ```
pub fn node_indices(&self) -> NodeIndices<Ix> {
- NodeIndices { r: 0..self.node_count(), ty: PhantomData }
+ NodeIndices {
+ r: 0..self.node_count(),
+ ty: PhantomData,
+ }
}
/// Return an iterator yielding mutable access to all node weights.
///
/// The order in which weights are yielded matches the order of their
/// node indices.
- pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix>
- {
- NodeWeightsMut { nodes: self.nodes.iter_mut() }
+ pub fn node_weights_mut(&mut self) -> NodeWeightsMut<N, Ix> {
+ NodeWeightsMut {
+ nodes: self.nodes.iter_mut(),
+ }
}
/// Return an iterator over the edge indices of the graph
pub fn edge_indices(&self) -> EdgeIndices<Ix> {
- EdgeIndices { r: 0..self.edge_count(), ty: PhantomData }
+ EdgeIndices {
+ r: 0..self.edge_count(),
+ ty: PhantomData,
+ }
}
/// Create an iterator over all edges, in indexed order.
@@ -969,7 +1002,7 @@
/// Iterator element type is `EdgeReference<E, Ix>`.
pub fn edge_references(&self) -> EdgeReferences<E, Ix> {
EdgeReferences {
- iter: self.edges.iter().enumerate()
+ iter: self.edges.iter().enumerate(),
}
}
@@ -977,23 +1010,22 @@
///
/// The order in which weights are yielded matches the order of their
/// edge indices.
- pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix>
- {
- EdgeWeightsMut { edges: self.edges.iter_mut() }
+ pub fn edge_weights_mut(&mut self) -> EdgeWeightsMut<E, Ix> {
+ EdgeWeightsMut {
+ edges: self.edges.iter_mut(),
+ }
}
// Remaining methods are of the more internal flavour, read-only access to
// the data structure's internals.
/// Access the internal node array.
- pub fn raw_nodes(&self) -> &[Node<N, Ix>]
- {
+ pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
&self.nodes
}
/// Access the internal edge array.
- pub fn raw_edges(&self) -> &[Edge<E, Ix>]
- {
+ pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
&self.edges
}
@@ -1003,29 +1035,31 @@
}
/// Accessor for data structure internals: the first edge in the given direction.
- pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>>
- {
+ pub fn first_edge(&self, a: NodeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
match self.nodes.get(a.index()) {
None => None,
Some(node) => {
let edix = node.next[dir.index()];
if edix == EdgeIndex::end() {
None
- } else { Some(edix) }
+ } else {
+ Some(edix)
+ }
}
}
}
/// Accessor for data structure internals: the next edge for the given direction.
- pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>>
- {
+ pub fn next_edge(&self, e: EdgeIndex<Ix>, dir: Direction) -> Option<EdgeIndex<Ix>> {
match self.edges.get(e.index()) {
None => None,
Some(node) => {
let edix = node.next[dir.index()];
if edix == EdgeIndex::end() {
None
- } else { Some(edix) }
+ } else {
+ Some(edix)
+ }
}
}
}
@@ -1063,21 +1097,28 @@
/// assert_eq!(gr[b], 4.);
/// assert_eq!(gr[c], 2.);
/// ```
- pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
- -> (&mut <Self as Index<T>>::Output,
- &mut <Self as Index<U>>::Output)
- where Self: IndexMut<T> + IndexMut<U>,
- T: GraphIndex,
- U: GraphIndex,
+ pub fn index_twice_mut<T, U>(
+ &mut self,
+ i: T,
+ j: U,
+ ) -> (
+ &mut <Self as Index<T>>::Output,
+ &mut <Self as Index<U>>::Output,
+ )
+ where
+ Self: IndexMut<T> + IndexMut<U>,
+ T: GraphIndex,
+ U: GraphIndex,
{
- assert!(T::is_node_index() != U::is_node_index() ||
- i.index() != j.index());
+ assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
// Allow two mutable indexes here -- they are nonoverlapping
unsafe {
let self_mut = self as *mut _;
- (<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
- <Self as IndexMut<U>>::index_mut(&mut *self_mut, j))
+ (
+ <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
+ <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
+ )
}
}
@@ -1176,7 +1217,8 @@
///
/// The order nodes are visited is not specified.
pub fn retain_nodes<F>(&mut self, mut visit: F)
- where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool
+ where
+ F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
{
for index in self.node_indices().rev() {
if !visit(Frozen(self), index) {
@@ -1195,7 +1237,8 @@
///
/// The order edges are visited is not specified.
pub fn retain_edges<F>(&mut self, mut visit: F)
- where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool
+ where
+ F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
{
for index in self.edge_indices().rev() {
if !visit(Frozen(self), index) {
@@ -1206,7 +1249,6 @@
}
}
-
/// Create a new `Graph` from an iterable of edges.
///
/// Node weights `N` are set to default values.
@@ -1225,10 +1267,11 @@
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
let mut g = Self::with_capacity(0, 0);
g.extend_with_edges(iterable);
@@ -1243,10 +1286,11 @@
///
/// Nodes are inserted automatically to match the edges.
pub fn extend_with_edges<I>(&mut self, iterable: I)
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
@@ -1263,29 +1307,30 @@
}
}
-
/// Create a new `Graph` by mapping node and
/// edge weights to new values.
///
/// The resulting graph has the same structure and the same
/// graph indices as `self`.
- pub fn map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
- -> Graph<N2, E2, Ty, Ix>
- where F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
- G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
+ pub fn map<'a, F, G, N2, E2>(
+ &'a self,
+ mut node_map: F,
+ mut edge_map: G,
+ ) -> Graph<N2, E2, Ty, Ix>
+ where
+ F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
+ G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
{
let mut g = Graph::with_capacity(self.node_count(), self.edge_count());
- g.nodes.extend(enumerate(&self.nodes).map(|(i, node)|
- Node {
- weight: node_map(NodeIndex::new(i), &node.weight),
- next: node.next,
- }));
- g.edges.extend(enumerate(&self.edges).map(|(i, edge)|
- Edge {
- weight: edge_map(EdgeIndex::new(i), &edge.weight),
- next: edge.next,
- node: edge.node,
- }));
+ g.nodes.extend(enumerate(&self.nodes).map(|(i, node)| Node {
+ weight: node_map(NodeIndex::new(i), &node.weight),
+ next: node.next,
+ }));
+ g.edges.extend(enumerate(&self.edges).map(|(i, edge)| Edge {
+ weight: edge_map(EdgeIndex::new(i), &edge.weight),
+ next: edge.next,
+ node: edge.node,
+ }));
g
}
@@ -1301,10 +1346,14 @@
/// If no nodes are removed, the resulting graph has compatible node
/// indices; if neither nodes nor edges are removed, the result has
/// the same graph indices as `self`.
- pub fn filter_map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
- -> Graph<N2, E2, Ty, Ix>
- where F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
- G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
+ pub fn filter_map<'a, F, G, N2, E2>(
+ &'a self,
+ mut node_map: F,
+ mut edge_map: G,
+ ) -> Graph<N2, E2, Ty, Ix>
+ where
+ F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
+ G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
{
let mut g = Graph::with_capacity(0, 0);
// mapping from old node index to new node index, end represents removed.
@@ -1331,14 +1380,17 @@
/// are done, so you may want to go over the result to remove or add edges.
///
/// Computes in **O(1)** time.
- pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix> where
- NewTy: EdgeType
+ pub fn into_edge_type<NewTy>(self) -> Graph<N, E, NewTy, Ix>
+ where
+ NewTy: EdgeType,
{
- Graph{nodes: self.nodes, edges: self.edges,
- ty: PhantomData}
+ Graph {
+ nodes: self.nodes,
+ edges: self.edges,
+ ty: PhantomData,
+ }
}
-
//
// internal methods
//
@@ -1375,26 +1427,26 @@
ty: PhantomData<Ty>,
}
-impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix> where
+impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
type Item = NodeIndex<Ix>;
- fn next(&mut self) -> Option<NodeIndex<Ix>>
- {
+ fn next(&mut self) -> Option<NodeIndex<Ix>> {
let k = self.dir.index();
loop {
match self.iter.next() {
None => return None,
Some((index, node)) => {
- if node.next[k] == EdgeIndex::end() &&
- (Ty::is_directed() ||
- node.next[1-k] == EdgeIndex::end()) {
- return Some(NodeIndex::new(index))
+ if node.next[k] == EdgeIndex::end()
+ && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
+ {
+ return Some(NodeIndex::new(index));
} else {
- continue
+ continue;
}
- },
+ }
}
}
}
@@ -1410,15 +1462,15 @@
/// [1]: struct.Graph.html#method.neighbors
/// [2]: struct.Graph.html#method.neighbors_directed
/// [3]: struct.Graph.html#method.neighbors_undirected
-pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx>
-{
+pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
/// starting node to skip over
skip_start: NodeIndex<Ix>,
edges: &'a [Edge<E, Ix>],
next: [EdgeIndex<Ix>; 2],
}
-impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix> where
+impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
+where
Ix: IndexType,
{
type Item = NodeIndex<Ix>;
@@ -1446,19 +1498,16 @@
}
}
-
impl<'a, E, Ix> Clone for Neighbors<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
- clone_fields!(Neighbors,
- skip_start,
- edges,
- next,
- );
+ clone_fields!(Neighbors, skip_start, edges, next,);
}
impl<'a, E, Ix> Neighbors<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
/// Return a “walker” object that can be used to step through the
/// neighbors and edges from the origin node.
@@ -1468,7 +1517,7 @@
pub fn detach(&self) -> WalkNeighbors<Ix> {
WalkNeighbors {
skip_start: self.skip_start,
- next: self.next
+ next: self.next,
}
}
}
@@ -1479,18 +1528,19 @@
dir: Direction,
}
-fn edges_walker_mut<E, Ix>(edges: &mut [Edge<E, Ix>], next: EdgeIndex<Ix>, dir: Direction)
- -> EdgesWalkerMut<E, Ix>
- where Ix: IndexType,
+fn edges_walker_mut<E, Ix>(
+ edges: &mut [Edge<E, Ix>],
+ next: EdgeIndex<Ix>,
+ dir: Direction,
+) -> EdgesWalkerMut<E, Ix>
+where
+ Ix: IndexType,
{
- EdgesWalkerMut {
- edges,
- next,
- dir
- }
+ EdgesWalkerMut { edges, next, dir }
}
-impl<'a, E, Ix> EdgesWalkerMut<'a, E, Ix> where
+impl<'a, E, Ix> EdgesWalkerMut<'a, E, Ix>
+where
Ix: IndexType,
{
fn next_edge(&mut self) -> Option<&mut Edge<E, Ix>> {
@@ -1510,10 +1560,10 @@
}
}
-
impl<'a, N, E, Ty, Ix> IntoEdges for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Edges = Edges<'a, E, Ty, Ix>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
@@ -1522,8 +1572,9 @@
}
impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgesDirected = Edges<'a, E, Ty, Ix>;
fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
@@ -1531,11 +1582,11 @@
}
}
-
/// Iterator over the edges of from or to a node
pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// starting node to skip over
skip_start: NodeIndex<Ix>,
@@ -1551,8 +1602,9 @@
}
impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ix>;
@@ -1606,7 +1658,7 @@
*node
},
weight,
- })
+ });
}
}
@@ -1616,8 +1668,9 @@
/// Iterator over the multiple directed edges connecting a source node to a target node
pub struct EdgesConnecting<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
target_node: NodeIndex<Ix>,
edges: Edges<'a, E, Ty, Ix>,
@@ -1625,8 +1678,9 @@
}
impl<'a, E, Ty, Ix> Iterator for EdgesConnecting<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ix>;
@@ -1641,15 +1695,15 @@
}
}
-
fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
x.swap(0, 1);
x
}
impl<'a, E, Ty, Ix> Clone for Edges<'a, E, Ty, Ix>
- where Ix: IndexType,
- Ty: EdgeType,
+where
+ Ix: IndexType,
+ Ty: EdgeType,
{
fn clone(&self) -> Self {
Edges {
@@ -1667,7 +1721,8 @@
nodes: ::std::slice::IterMut<'a, Node<N, Ix>>,
}
-impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix> where
+impl<'a, N, Ix> Iterator for NodeWeightsMut<'a, N, Ix>
+where
Ix: IndexType,
{
type Item = &'a mut N;
@@ -1686,7 +1741,8 @@
edges: ::std::slice::IterMut<'a, Edge<E, Ix>>,
}
-impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix> where
+impl<'a, E, Ix> Iterator for EdgeWeightsMut<'a, E, Ix>
+where
Ix: IndexType,
{
type Item = &'a mut E;
@@ -1703,7 +1759,8 @@
/// Index the `Graph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1716,20 +1773,21 @@
/// Index the `Graph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for Graph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
&mut self.nodes[index.index()].weight
}
-
}
/// Index the `Graph` by `EdgeIndex` to access edge weights.
///
/// **Panics** if the edge doesn't exist.
-impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1742,7 +1800,8 @@
/// Index the `Graph` by `EdgeIndex` to access edge weights.
///
/// **Panics** if the edge doesn't exist.
-impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for Graph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1753,14 +1812,17 @@
/// Create a new empty `Graph`.
impl<N, E, Ty, Ix> Default for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
- fn default() -> Self { Self::with_capacity(0, 0) }
+ fn default() -> Self {
+ Self::with_capacity(0, 0)
+ }
}
/// A `GraphIndex` is a node or edge index.
-pub trait GraphIndex : Copy {
+pub trait GraphIndex: Copy {
#[doc(hidden)]
fn index(&self) -> usize;
#[doc(hidden)]
@@ -1769,16 +1831,24 @@
impl<Ix: IndexType> GraphIndex for NodeIndex<Ix> {
#[inline]
- fn index(&self) -> usize { NodeIndex::index(*self) }
+ fn index(&self) -> usize {
+ NodeIndex::index(*self)
+ }
#[inline]
- fn is_node_index() -> bool { true }
+ fn is_node_index() -> bool {
+ true
+ }
}
impl<Ix: IndexType> GraphIndex for EdgeIndex<Ix> {
#[inline]
- fn index(&self) -> usize { EdgeIndex::index(*self) }
+ fn index(&self) -> usize {
+ EdgeIndex::index(*self)
+ }
#[inline]
- fn is_node_index() -> bool { false }
+ fn is_node_index() -> bool {
+ false
+ }
}
/// A “walker” object that can be used to step through the edge list of a node.
@@ -1822,7 +1892,8 @@
}
impl<Ix> Clone for WalkNeighbors<Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
fn clone(&self) -> Self {
WalkNeighbors {
@@ -1839,8 +1910,10 @@
/// where the `WalkNeighbors` value was created.
/// For an `Outgoing` walk, the target nodes,
/// for an `Incoming` walk, the source nodes of the edge.
- pub fn next<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
- -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
+ pub fn next<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &Graph<N, E, Ty, Ix>,
+ ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
// First any outgoing edges
match g.edges.get(self.next[0].index()) {
None => {}
@@ -1864,15 +1937,17 @@
None
}
- pub fn next_node<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
- -> Option<NodeIndex<Ix>>
- {
+ pub fn next_node<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &Graph<N, E, Ty, Ix>,
+ ) -> Option<NodeIndex<Ix>> {
self.next(g).map(|t| t.1)
}
- pub fn next_edge<N, E, Ty: EdgeType>(&mut self, g: &Graph<N, E, Ty, Ix>)
- -> Option<EdgeIndex<Ix>>
- {
+ pub fn next_edge<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &Graph<N, E, Ty, Ix>,
+ ) -> Option<EdgeIndex<Ix>> {
self.next(g).map(|t| t.0)
}
}
@@ -1945,10 +2020,11 @@
}
}
-impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> { }
+impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
- where E: PartialEq,
+where
+ E: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
self.index == rhs.index && self.weight == rhs.weight
@@ -1956,14 +2032,15 @@
}
impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeRef = (NodeIndex<Ix>, &'a N);
type NodeReferences = NodeReferences<'a, N, Ix>;
fn node_references(self) -> Self::NodeReferences {
NodeReferences {
- iter: self.nodes.iter().enumerate()
+ iter: self.nodes.iter().enumerate(),
}
}
}
@@ -1974,14 +2051,15 @@
}
impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
type Item = (NodeIndex<Ix>, &'a N);
fn next(&mut self) -> Option<Self::Item> {
- self.iter.next().map(|(i, node)|
- (node_index(i), &node.weight)
- )
+ self.iter
+ .next()
+ .map(|(i, node)| (node_index(i), &node.weight))
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -1990,61 +2068,70 @@
}
impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.iter.next_back().map(|(i, node)|
- (node_index(i), &node.weight)
- )
+ self.iter
+ .next_back()
+ .map(|(i, node)| (node_index(i), &node.weight))
}
}
-impl<'a, N, Ix> ExactSizeIterator for NodeReferences<'a, N, Ix>
- where Ix: IndexType
-{ }
+impl<'a, N, Ix> ExactSizeIterator for NodeReferences<'a, N, Ix> where Ix: IndexType {}
impl<'a, Ix, E> EdgeReference<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
/// Access the edge’s weight.
///
/// **NOTE** that this method offers a longer lifetime
/// than the trait (unfortunately they don't match yet).
- pub fn weight(&self) -> &'a E { self.weight }
+ pub fn weight(&self) -> &'a E {
+ self.weight
+ }
}
impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type NodeId = NodeIndex<Ix>;
type EdgeId = EdgeIndex<Ix>;
type Weight = E;
- fn source(&self) -> Self::NodeId { self.node[0] }
- fn target(&self) -> Self::NodeId { self.node[1] }
- fn weight(&self) -> &E { self.weight }
- fn id(&self) -> Self::EdgeId { self.index }
+ fn source(&self) -> Self::NodeId {
+ self.node[0]
+ }
+ fn target(&self) -> Self::NodeId {
+ self.node[1]
+ }
+ fn weight(&self) -> &E {
+ self.weight
+ }
+ fn id(&self) -> Self::EdgeId {
+ self.index
+ }
}
-
/// Iterator over all edges of a graph.
pub struct EdgeReferences<'a, E: 'a, Ix: IndexType = DefaultIx> {
iter: iter::Enumerate<slice::Iter<'a, Edge<E, Ix>>>,
}
impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ix>;
fn next(&mut self) -> Option<Self::Item> {
- self.iter.next().map(|(i, edge)|
- EdgeReference {
- index: edge_index(i),
- node: edge.node,
- weight: &edge.weight,
- }
- )
+ self.iter.next().map(|(i, edge)| EdgeReference {
+ index: edge_index(i),
+ node: edge.node,
+ weight: &edge.weight,
+ })
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -2053,26 +2140,23 @@
}
impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.iter.next_back().map(|(i, edge)|
- EdgeReference {
- index: edge_index(i),
- node: edge.node,
- weight: &edge.weight,
- }
- )
+ self.iter.next_back().map(|(i, edge)| EdgeReference {
+ index: edge_index(i),
+ node: edge.node,
+ weight: &edge.weight,
+ })
}
}
-impl<'a, E, Ix> ExactSizeIterator for EdgeReferences<'a, E, Ix>
- where Ix: IndexType
-{}
+impl<'a, E, Ix> ExactSizeIterator for EdgeReferences<'a, E, Ix> where Ix: IndexType {}
+mod frozen;
#[cfg(feature = "stable_graph")]
pub mod stable_graph;
-mod frozen;
/// `Frozen` is a graph wrapper.
///
diff --git a/src/graph_impl/serialization.rs b/src/graph_impl/serialization.rs
index 8c93c2e..30f258b 100644
--- a/src/graph_impl/serialization.rs
+++ b/src/graph_impl/serialization.rs
@@ -1,19 +1,18 @@
-
use serde::de::Error;
use std::marker::PhantomData;
use crate::prelude::*;
-use crate::EdgeType;
use crate::graph::Node;
-use crate::graph::{IndexType, Edge};
-use crate::serde_utils::MappedSequenceVisitor;
+use crate::graph::{Edge, IndexType};
use crate::serde_utils::CollectSeqWithLength;
-use crate::serde_utils::{IntoSerializable, FromDeserialized};
+use crate::serde_utils::MappedSequenceVisitor;
+use crate::serde_utils::{FromDeserialized, IntoSerializable};
+use crate::EdgeType;
-use super::{NodeIndex, EdgeIndex};
-use serde::{Serialize, Serializer, Deserialize, Deserializer};
+use super::{EdgeIndex, NodeIndex};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Serialization representation for Graph
/// Keep in sync with deserialization and StableGraph
@@ -28,7 +27,7 @@
/// }
///
/// The same format is used by both Graph and StableGraph.
-///
+///
/// For graph there are restrictions:
/// node_holes is always empty and edges are always Some
///
@@ -42,11 +41,11 @@
#[serde(rename = "Graph")]
#[serde(bound(serialize = "N: Serialize, E: Serialize, Ix: IndexType + Serialize"))]
pub struct SerGraph<'a, N: 'a, E: 'a, Ix: 'a + IndexType> {
- #[serde(serialize_with="ser_graph_nodes")]
+ #[serde(serialize_with = "ser_graph_nodes")]
nodes: &'a [Node<N, Ix>],
node_holes: &'a [NodeIndex<Ix>],
edge_property: EdgeProperty,
- #[serde(serialize_with="ser_graph_edges")]
+ #[serde(serialize_with = "ser_graph_edges")]
edges: &'a [Edge<E, Ix>],
}
@@ -54,62 +53,71 @@
// Keep in sync with serialization and StableGraph
#[derive(Deserialize)]
#[serde(rename = "Graph")]
-#[serde(bound(deserialize = "N: Deserialize<'de>, E: Deserialize<'de>, Ix: IndexType + Deserialize<'de>"))]
+#[serde(bound(
+ deserialize = "N: Deserialize<'de>, E: Deserialize<'de>, Ix: IndexType + Deserialize<'de>"
+))]
pub struct DeserGraph<N, E, Ix> {
- #[serde(deserialize_with="deser_graph_nodes")]
+ #[serde(deserialize_with = "deser_graph_nodes")]
nodes: Vec<Node<N, Ix>>,
- #[serde(deserialize_with="deser_graph_node_holes")]
+ #[serde(deserialize_with = "deser_graph_node_holes")]
#[allow(unused)]
- #[serde(default="Vec::new")]
+ #[serde(default = "Vec::new")]
node_holes: Vec<NodeIndex<Ix>>,
edge_property: EdgeProperty,
- #[serde(deserialize_with="deser_graph_edges")]
+ #[serde(deserialize_with = "deser_graph_edges")]
edges: Vec<Edge<E, Ix>>,
}
-
impl<Ix> Serialize for NodeIndex<Ix>
- where Ix: IndexType + Serialize,
+where
+ Ix: IndexType + Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer
+ where
+ S: Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de, Ix> Deserialize<'de> for NodeIndex<Ix>
- where Ix: IndexType + Deserialize<'de>,
+where
+ Ix: IndexType + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'de>
+ where
+ D: Deserializer<'de>,
{
Ok(NodeIndex(Ix::deserialize(deserializer)?))
}
}
impl<Ix> Serialize for EdgeIndex<Ix>
- where Ix: IndexType + Serialize,
+where
+ Ix: IndexType + Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer
+ where
+ S: Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de, Ix> Deserialize<'de> for EdgeIndex<Ix>
- where Ix: IndexType + Deserialize<'de>,
+where
+ Ix: IndexType + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'de>
+ where
+ D: Deserializer<'de>,
{
Ok(EdgeIndex(Ix::deserialize(deserializer)?))
}
}
#[derive(Serialize, Deserialize)]
-#[serde(rename_all="lowercase")]
+#[serde(rename_all = "lowercase")]
#[derive(Debug)]
pub enum EdgeProperty {
Undirected,
@@ -125,7 +133,10 @@
}
}
-impl<Ty> From<PhantomData<Ty>> for EdgeProperty where Ty: EdgeType {
+impl<Ty> From<PhantomData<Ty>> for EdgeProperty
+where
+ Ty: EdgeType,
+{
fn from(_: PhantomData<Ty>) -> Self {
if Ty::is_directed() {
EdgeProperty::Directed
@@ -135,18 +146,22 @@
}
}
-
-impl<Ty> FromDeserialized for PhantomData<Ty> where Ty: EdgeType
+impl<Ty> FromDeserialized for PhantomData<Ty>
+where
+ Ty: EdgeType,
{
type Input = EdgeProperty;
fn from_deserialized<E2>(input: Self::Input) -> Result<Self, E2>
- where E2: Error
+ where
+ E2: Error,
{
if input.is_directed() != Ty::is_directed() {
- Err(E2::custom(format_args!("graph edge property mismatch, \
+ Err(E2::custom(format_args!(
+ "graph edge property mismatch, \
expected {:?}, found {:?}",
- EdgeProperty::from(PhantomData::<Ty>),
- input)))
+ EdgeProperty::from(PhantomData::<Ty>),
+ input
+ )))
} else {
Ok(PhantomData)
}
@@ -154,58 +169,64 @@
}
fn ser_graph_nodes<S, N, Ix>(nodes: &&[Node<N, Ix>], serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
- N: Serialize,
- Ix: Serialize + IndexType,
+where
+ S: Serializer,
+ N: Serialize,
+ Ix: Serialize + IndexType,
{
- serializer.collect_seq_exact(
- nodes.iter()
- .map(|node| &node.weight))
+ serializer.collect_seq_exact(nodes.iter().map(|node| &node.weight))
}
fn ser_graph_edges<S, E, Ix>(edges: &&[Edge<E, Ix>], serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
- E: Serialize,
- Ix: Serialize + IndexType,
+where
+ S: Serializer,
+ E: Serialize,
+ Ix: Serialize + IndexType,
{
serializer.collect_seq_exact(
- edges.iter()
- .map(|edge| Some((
- edge.source(),
- edge.target(),
- &edge.weight,
- ))))
+ edges
+ .iter()
+ .map(|edge| Some((edge.source(), edge.target(), &edge.weight))),
+ )
}
-
fn deser_graph_nodes<'de, D, N, Ix>(deserializer: D) -> Result<Vec<Node<N, Ix>>, D::Error>
- where D: Deserializer<'de>,
- N: Deserialize<'de>,
- Ix: IndexType + Deserialize<'de>,
+where
+ D: Deserializer<'de>,
+ N: Deserialize<'de>,
+ Ix: IndexType + Deserialize<'de>,
{
- deserializer.deserialize_seq(MappedSequenceVisitor::new(|n|
+ deserializer.deserialize_seq(MappedSequenceVisitor::new(|n| {
Ok(Node {
weight: n,
next: [EdgeIndex::end(); 2],
})
- ))
-}
-
-fn deser_graph_node_holes<'de, D, Ix>(deserializer: D) -> Result<Vec<NodeIndex<Ix>>, D::Error>
- where D: Deserializer<'de>,
- Ix: IndexType + Deserialize<'de>,
-{
- deserializer.deserialize_seq(MappedSequenceVisitor::<NodeIndex<Ix>, NodeIndex<Ix>, _>::new(|_| {
- Err("Graph can not have holes in the node set, found non-empty node_holes")
}))
}
-fn deser_graph_edges<'de, D, N, Ix>(deserializer: D) -> Result<Vec<Edge<N, Ix>>, D::Error>
- where D: Deserializer<'de>,
- N: Deserialize<'de>,
- Ix: IndexType + Deserialize<'de>,
+fn deser_graph_node_holes<'de, D, Ix>(deserializer: D) -> Result<Vec<NodeIndex<Ix>>, D::Error>
+where
+ D: Deserializer<'de>,
+ Ix: IndexType + Deserialize<'de>,
{
- deserializer.deserialize_seq(MappedSequenceVisitor::<Option<(NodeIndex<Ix>, NodeIndex<Ix>, N)>, _, _>::new(|x|
+ deserializer.deserialize_seq(
+ MappedSequenceVisitor::<NodeIndex<Ix>, NodeIndex<Ix>, _>::new(|_| {
+ Err("Graph can not have holes in the node set, found non-empty node_holes")
+ }),
+ )
+}
+
+fn deser_graph_edges<'de, D, N, Ix>(deserializer: D) -> Result<Vec<Edge<N, Ix>>, D::Error>
+where
+ D: Deserializer<'de>,
+ N: Deserialize<'de>,
+ Ix: IndexType + Deserialize<'de>,
+{
+ deserializer.deserialize_seq(MappedSequenceVisitor::<
+ Option<(NodeIndex<Ix>, NodeIndex<Ix>, N)>,
+ _,
+ _,
+ >::new(|x| {
if let Some((i, j, w)) = x {
Ok(Edge {
weight: w,
@@ -215,12 +236,13 @@
} else {
Err("Graph can not have holes in the edge set, found None, expected edge")
}
- ))
+ }))
}
impl<'a, N, E, Ty, Ix> IntoSerializable for &'a Graph<N, E, Ty, Ix>
- where Ix: IndexType,
- Ty: EdgeType,
+where
+ Ix: IndexType,
+ Ty: EdgeType,
{
type Output = SerGraph<'a, N, E, Ix>;
fn into_serializable(self) -> Self::Output {
@@ -235,39 +257,53 @@
/// Requires crate feature `"serde-1"`
impl<N, E, Ty, Ix> Serialize for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType + Serialize,
- N: Serialize,
- E: Serialize,
+where
+ Ty: EdgeType,
+ Ix: IndexType + Serialize,
+ N: Serialize,
+ E: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer
+ where
+ S: Serializer,
{
self.into_serializable().serialize(serializer)
}
}
-
-pub fn invalid_node_err<E>(node_index: usize, len: usize) -> E where E: Error {
- E::custom(format_args!("invalid value: node index `{}` does not exist in graph \
+pub fn invalid_node_err<E>(node_index: usize, len: usize) -> E
+where
+ E: Error,
+{
+ E::custom(format_args!(
+ "invalid value: node index `{}` does not exist in graph \
with node bound {}",
- node_index, len))
+ node_index, len
+ ))
}
pub fn invalid_length_err<Ix, E>(node_or_edge: &str, len: usize) -> E
- where E: Error, Ix: IndexType
+where
+ E: Error,
+ Ix: IndexType,
{
- E::custom(format_args!("invalid size: graph {} count {} exceeds index type maximum {}",
- node_or_edge, len, <Ix as IndexType>::max().index()))
+ E::custom(format_args!(
+ "invalid size: graph {} count {} exceeds index type maximum {}",
+ node_or_edge,
+ len,
+ <Ix as IndexType>::max().index()
+ ))
}
impl<'a, N, E, Ty, Ix> FromDeserialized for Graph<N, E, Ty, Ix>
- where Ix: IndexType,
- Ty: EdgeType,
+where
+ Ix: IndexType,
+ Ty: EdgeType,
{
type Input = DeserGraph<N, E, Ix>;
fn from_deserialized<E2>(input: Self::Input) -> Result<Self, E2>
- where E2: Error
+ where
+ E2: Error,
{
let ty = PhantomData::<Ty>::from_deserialized(input.edge_property)?;
let nodes = input.nodes;
@@ -286,23 +322,24 @@
ty: ty,
};
let nc = gr.node_count();
- gr.link_edges().map_err(|i| invalid_node_err(i.index(), nc))?;
+ gr.link_edges()
+ .map_err(|i| invalid_node_err(i.index(), nc))?;
Ok(gr)
}
}
-
/// Requires crate feature `"serde-1"`
impl<'de, N, E, Ty, Ix> Deserialize<'de> for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType + Deserialize<'de>,
- N: Deserialize<'de>,
- E: Deserialize<'de>,
+where
+ Ty: EdgeType,
+ Ix: IndexType + Deserialize<'de>,
+ N: Deserialize<'de>,
+ E: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'de>
+ where
+ D: Deserializer<'de>,
{
Self::from_deserialized(DeserGraph::deserialize(deserializer)?)
}
}
-
diff --git a/src/graph_impl/stable_graph/mod.rs b/src/graph_impl/stable_graph/mod.rs
index a0bae5b..7c98681 100644
--- a/src/graph_impl/stable_graph/mod.rs
+++ b/src/graph_impl/stable_graph/mod.rs
@@ -12,51 +12,21 @@
use std::ops::{Index, IndexMut};
use std::slice;
-use crate::{
- Graph,
- EdgeType,
- Directed,
- Undirected,
- Direction,
- Incoming,
- Outgoing,
-};
+use crate::{Directed, Direction, EdgeType, Graph, Incoming, Outgoing, Undirected};
-use crate::iter_format::{
- IterFormatExt,
- NoPretty,
- DebugMap,
-};
+use crate::iter_format::{DebugMap, IterFormatExt, NoPretty};
use crate::iter_utils::IterUtilsExt;
-use super::{
- Edge,
- index_twice,
- Node,
- DIRECTIONS,
- Pair,
- Frozen,
+use super::{index_twice, Edge, Frozen, Node, Pair, DIRECTIONS};
+use crate::visit::{
+ EdgeRef, IntoEdgeReferences, IntoEdges, IntoEdgesDirected, IntoNodeReferences, NodeIndexable,
};
use crate::IntoWeightedEdge;
-use crate::visit::{
- EdgeRef,
- IntoNodeReferences,
- IntoEdges,
- IntoEdgesDirected,
- IntoEdgeReferences,
- NodeIndexable,
-};
// reexport those things that are shared with Graph
#[doc(no_inline)]
pub use crate::graph::{
- NodeIndex,
- EdgeIndex,
- GraphIndex,
- IndexType,
- DefaultIx,
- node_index,
- edge_index,
+ edge_index, node_index, DefaultIx, EdgeIndex, GraphIndex, IndexType, NodeIndex,
};
use crate::util::enumerate;
@@ -100,8 +70,7 @@
/// Depends on crate feature `stable_graph` (default). *Stable Graph is still
/// missing a few methods compared to Graph. You can contribute to help it
/// achieve parity.*
-pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx>
-{
+pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx> {
g: Graph<Option<N>, Option<E>, Ty, Ix>,
node_count: usize,
edge_count: usize,
@@ -130,41 +99,60 @@
pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
- where N: fmt::Debug,
- E: fmt::Debug,
- Ty: EdgeType,
- Ix: IndexType,
+where
+ N: fmt::Debug,
+ E: fmt::Debug,
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- let etype = if self.is_directed() { "Directed" } else { "Undirected" };
+ let etype = if self.is_directed() {
+ "Directed"
+ } else {
+ "Undirected"
+ };
let mut fmt_struct = f.debug_struct("StableGraph");
fmt_struct.field("Ty", &etype);
fmt_struct.field("node_count", &self.node_count);
fmt_struct.field("edge_count", &self.edge_count);
if self.g.edges.iter().any(|e| e.weight.is_some()) {
- fmt_struct.field("edges", &self.g.edges.iter()
- .filter(|e| e.weight.is_some())
- .map(|e| NoPretty((e.source().index(), e.target().index())))
- .format(", "));
+ fmt_struct.field(
+ "edges",
+ &self
+ .g
+ .edges
+ .iter()
+ .filter(|e| e.weight.is_some())
+ .map(|e| NoPretty((e.source().index(), e.target().index())))
+ .format(", "),
+ );
}
// skip weights if they are ZST!
if size_of::<N>() != 0 {
- fmt_struct.field("node weights",
- &DebugMap(||
- self.g.nodes.iter()
- .map(|n| n.weight.as_ref())
- .enumerate()
- .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
- ));
+ fmt_struct.field(
+ "node weights",
+ &DebugMap(|| {
+ self.g
+ .nodes
+ .iter()
+ .map(|n| n.weight.as_ref())
+ .enumerate()
+ .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
+ }),
+ );
}
if size_of::<E>() != 0 {
- fmt_struct.field("edge weights",
- &DebugMap(||
- self.g.edges.iter()
- .map(|n| n.weight.as_ref())
- .enumerate()
- .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
- ));
+ fmt_struct.field(
+ "edge weights",
+ &DebugMap(|| {
+ self.g
+ .edges
+ .iter()
+ .map(|n| n.weight.as_ref())
+ .enumerate()
+ .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
+ }),
+ );
}
fmt_struct.field("free_node", &self.free_node);
fmt_struct.field("free_edge", &self.free_edge);
@@ -172,7 +160,6 @@
}
}
-
impl<N, E> StableGraph<N, E, Directed> {
/// Create a new `StableGraph` with directed edges.
///
@@ -185,8 +172,9 @@
}
impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// Create a new `StableGraph` with estimated capacity.
pub fn with_capacity(nodes: usize, edges: usize) -> Self {
@@ -298,7 +286,7 @@
loop {
let next = self.g.nodes[a.index()].next[k];
if next == EdgeIndex::end() {
- break
+ break;
}
let ret = self.remove_edge(next);
debug_assert!(ret.is_some());
@@ -322,8 +310,10 @@
// Return the Node if it is not vacant (non-None weight)
fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
- self.g.nodes.get(a.index())
- .and_then(|node| node.weight.as_ref().map(move |_| node))
+ self.g
+ .nodes
+ .get(a.index())
+ .and_then(|node| node.weight.as_ref().map(move |_| node))
}
/// Add an edge from `a` to `b` to the graph, with its associated
@@ -338,9 +328,7 @@
/// its index type.
///
/// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
- pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
- -> EdgeIndex<Ix>
- {
+ pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
let edge_idx;
let mut new_edge = None::<Edge<_, _>>;
{
@@ -391,7 +379,10 @@
}
};
if let Some(i) = wrong_index {
- panic!("StableGraph::add_edge: node index {} is not a node in the graph", i);
+ panic!(
+ "StableGraph::add_edge: node index {} is not a node in the graph",
+ i
+ );
}
self.edge_count += 1;
}
@@ -424,9 +415,7 @@
/// connected to `a` (and `b`, if the graph edges are undirected).
///
/// **Panics** if any of the nodes don't exist.
- pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
- -> EdgeIndex<Ix>
- {
+ pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> EdgeIndex<Ix> {
if let Some(ix) = self.find_edge(a, b) {
self[ix] = weight;
return ix;
@@ -488,7 +477,7 @@
/// Return an iterator over the node indices of the graph
pub fn node_indices(&self) -> NodeIndices<N, Ix> {
NodeIndices {
- iter: enumerate(self.raw_nodes())
+ iter: enumerate(self.raw_nodes()),
}
}
@@ -513,9 +502,7 @@
}
/// Access the source and target nodes for `e`.
- pub fn edge_endpoints(&self, e: EdgeIndex<Ix>)
- -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>
- {
+ pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)> {
match self.g.edges.get(e.index()) {
Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
_otherwise => None,
@@ -525,7 +512,7 @@
/// Return an iterator over the node indices of the graph
pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
EdgeIndices {
- iter: enumerate(self.raw_edges())
+ iter: enumerate(self.raw_edges()),
}
}
@@ -541,14 +528,13 @@
///
/// Computes in **O(e')** time, where **e'** is the number of edges
/// connected to `a` (and `b`, if the graph edges are undirected).
- pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>
- {
+ pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>> {
if !self.is_directed() {
self.find_edge_undirected(a, b).map(|(ix, _)| ix)
} else {
match self.get_node(a) {
None => None,
- Some(node) => self.g.find_edge_directed_from_node(node, b)
+ Some(node) => self.g.find_edge_directed_from_node(node, b),
}
}
}
@@ -560,15 +546,17 @@
/// Return the edge index and its directionality, with `Outgoing` meaning
/// from `a` to `b` and `Incoming` the reverse,
/// or `None` if the edge does not exist.
- pub fn find_edge_undirected(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<(EdgeIndex<Ix>, Direction)>
- {
+ pub fn find_edge_undirected(
+ &self,
+ a: NodeIndex<Ix>,
+ b: NodeIndex<Ix>,
+ ) -> Option<(EdgeIndex<Ix>, Direction)> {
match self.get_node(a) {
None => None,
Some(node) => self.g.find_edge_undirected_from_node(node, b),
}
}
-
/// Return an iterator of all nodes with an edge starting from `a`.
///
/// - `Directed`: Outgoing edges from `a`.
@@ -600,9 +588,7 @@
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
- pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction)
- -> Neighbors<E, Ix>
- {
+ pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Neighbors<E, Ix> {
let mut iter = self.neighbors_undirected(a);
if self.is_directed() {
let k = dir.index();
@@ -625,15 +611,14 @@
/// not borrow from the graph.
///
/// [1]: struct.Neighbors.html#method.detach
- pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
- {
+ pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
Neighbors {
skip_start: a,
edges: &self.g.edges,
next: match self.get_node(a) {
None => [EdgeIndex::end(), EdgeIndex::end()],
Some(n) => n.next,
- }
+ },
}
}
@@ -659,8 +644,7 @@
///
/// Produces an empty iterator if the node `a` doesn't exist.<br>
/// Iterator element type is `EdgeReference<E, Ix>`.
- pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>
- {
+ pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix> {
Edges {
skip_start: a,
edges: &self.g.edges,
@@ -684,30 +668,40 @@
/// just the nodes without edges.
///
/// The whole iteration computes in **O(|V|)** time.
- pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix>
- {
- Externals { iter: self.raw_nodes().iter().enumerate(), dir, ty: PhantomData }
+ pub fn externals(&self, dir: Direction) -> Externals<N, Ty, Ix> {
+ Externals {
+ iter: self.raw_nodes().iter().enumerate(),
+ dir,
+ ty: PhantomData,
+ }
}
/// Index the `StableGraph` by two indices, any combination of
/// node or edge indices is fine.
///
/// **Panics** if the indices are equal or if they are out of bounds.
- pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
- -> (&mut <Self as Index<T>>::Output,
- &mut <Self as Index<U>>::Output)
- where Self: IndexMut<T> + IndexMut<U>,
- T: GraphIndex,
- U: GraphIndex,
+ pub fn index_twice_mut<T, U>(
+ &mut self,
+ i: T,
+ j: U,
+ ) -> (
+ &mut <Self as Index<T>>::Output,
+ &mut <Self as Index<U>>::Output,
+ )
+ where
+ Self: IndexMut<T> + IndexMut<U>,
+ T: GraphIndex,
+ U: GraphIndex,
{
- assert!(T::is_node_index() != U::is_node_index() ||
- i.index() != j.index());
+ assert!(T::is_node_index() != U::is_node_index() || i.index() != j.index());
// Allow two mutable indexes here -- they are nonoverlapping
unsafe {
let self_mut = self as *mut _;
- (<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
- <Self as IndexMut<U>>::index_mut(&mut *self_mut, j))
+ (
+ <Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
+ <Self as IndexMut<U>>::index_mut(&mut *self_mut, j),
+ )
}
}
@@ -726,7 +720,10 @@
/// Computes in **O(n + e')** time, where **n** is the number of node indices and
/// **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
/// where *n* is the number of edges with an endpoint in a removed node.
- pub fn retain_nodes<F>(&mut self, mut visit: F) where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool {
+ pub fn retain_nodes<F>(&mut self, mut visit: F)
+ where
+ F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool,
+ {
for i in 0..self.node_bound() {
let ix = node_index(i);
if self.contains_node(ix) && !visit(Frozen(self), ix) {
@@ -749,7 +746,8 @@
/// Computes in **O(e'')** time, **e'** is the number of affected edges,
/// including the calls to `.remove_edge()` for each removed edge.
pub fn retain_edges<F>(&mut self, mut visit: F)
- where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool
+ where
+ F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool,
{
for i in 0..self.edge_bound() {
let ix = edge_index(i);
@@ -778,10 +776,11 @@
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
let mut g = Self::with_capacity(0, 0);
g.extend_with_edges(iterable);
@@ -793,14 +792,19 @@
///
/// The resulting graph has the same structure and the same
/// graph indices as `self`.
- pub fn map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
- -> StableGraph<N2, E2, Ty, Ix>
- where F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
- G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
+ pub fn map<'a, F, G, N2, E2>(
+ &'a self,
+ mut node_map: F,
+ mut edge_map: G,
+ ) -> StableGraph<N2, E2, Ty, Ix>
+ where
+ F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
+ G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
{
let g = self.g.map(
move |i, w| w.as_ref().map(|w| node_map(i, w)),
- move |i, w| w.as_ref().map(|w| edge_map(i, w)));
+ move |i, w| w.as_ref().map(|w| edge_map(i, w)),
+ );
StableGraph {
g,
node_count: self.node_count,
@@ -821,10 +825,14 @@
/// The resulting graph has the structure of a subgraph of the original graph.
/// Nodes and edges that are not removed maintain their old node or edge
/// indices.
- pub fn filter_map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
- -> StableGraph<N2, E2, Ty, Ix>
- where F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
- G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
+ pub fn filter_map<'a, F, G, N2, E2>(
+ &'a self,
+ mut node_map: F,
+ mut edge_map: G,
+ ) -> StableGraph<N2, E2, Ty, Ix>
+ where
+ F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
+ G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
{
let node_bound = self.node_bound();
let edge_bound = self.edge_bound();
@@ -837,7 +845,9 @@
// the stable graph keeps the node map itself
for (i, node) in enumerate(self.raw_nodes()) {
- if i >= node_bound { break; }
+ if i >= node_bound {
+ break;
+ }
if let Some(node_weight) = node.weight.as_ref() {
if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
result_g.add_node(new_weight);
@@ -847,7 +857,9 @@
result_g.add_vacant_node(&mut free_node);
}
for (i, edge) in enumerate(self.raw_edges()) {
- if i >= edge_bound { break; }
+ if i >= edge_bound {
+ break;
+ }
let source = edge.source();
let target = edge.target();
if let Some(edge_weight) = edge.weight.as_ref() {
@@ -874,10 +886,11 @@
///
/// Nodes are inserted automatically to match the edges.
pub fn extend_with_edges<I>(&mut self, iterable: I)
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
let iter = iterable.into_iter();
@@ -959,7 +972,7 @@
}
#[cfg(not(debug_assertions))]
- fn check_free_lists(&self) { }
+ fn check_free_lists(&self) {}
#[cfg(debug_assertions)]
// internal method to debug check the free lists (linked lists)
fn check_free_lists(&self) {
@@ -972,8 +985,11 @@
free_node_len += 1;
continue;
}
- debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
- free_node.index());
+ debug_assert!(
+ false,
+ "Corrupt free list: pointing to existing {:?}",
+ free_node.index()
+ );
}
debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
}
@@ -988,8 +1004,11 @@
free_edge_len += 1;
continue;
}
- debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
- free_node.index());
+ debug_assert!(
+ false,
+ "Corrupt free list: pointing to existing {:?}",
+ free_node.index()
+ );
}
debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
}
@@ -999,7 +1018,9 @@
/// The resulting cloned graph has the same graph indices as `self`.
impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
- where N: Clone, E: Clone,
+where
+ N: Clone,
+ E: Clone,
{
fn clone(&self) -> Self {
StableGraph {
@@ -1023,7 +1044,8 @@
/// Index the `StableGraph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1036,20 +1058,21 @@
/// Index the `StableGraph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
self.node_weight_mut(index).unwrap()
}
-
}
/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
///
/// **Panics** if the edge doesn't exist.
-impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1062,7 +1085,8 @@
/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
///
/// **Panics** if the edge doesn't exist.
-impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
@@ -1073,10 +1097,13 @@
/// Create a new empty `StableGraph`.
impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
- fn default() -> Self { Self::with_capacity(0, 0) }
+ fn default() -> Self {
+ Self::with_capacity(0, 0)
+ }
}
/// Convert a `Graph` into a `StableGraph`
@@ -1086,8 +1113,9 @@
/// The resulting graph has the same node and edge indices as
/// the original graph.
impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn from(g: Graph<N, E, Ty, Ix>) -> Self {
let nodes = g.nodes.into_iter().map(|e| Node {
@@ -1102,7 +1130,11 @@
StableGraph {
node_count: nodes.len(),
edge_count: edges.len(),
- g: Graph { edges: edges.collect(), nodes: nodes.collect(), ty: g.ty },
+ g: Graph {
+ edges: edges.collect(),
+ nodes: nodes.collect(),
+ ty: g.ty,
+ },
free_node: NodeIndex::end(),
free_edge: EdgeIndex::end(),
}
@@ -1120,8 +1152,9 @@
/// equal to node count, and the same for edges), would the resulting graph have
/// the same node and edge indices as the input.
impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
@@ -1149,14 +1182,15 @@
}
impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeRef = (NodeIndex<Ix>, &'a N);
type NodeReferences = NodeReferences<'a, N, Ix>;
fn node_references(self) -> Self::NodeReferences {
NodeReferences {
- iter: enumerate(self.raw_nodes())
+ iter: enumerate(self.raw_nodes()),
}
}
}
@@ -1167,14 +1201,14 @@
}
impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
type Item = (NodeIndex<Ix>, &'a N);
fn next(&mut self) -> Option<Self::Item> {
- self.iter.ex_find_map(|(i, node)| {
- node.weight.as_ref().map(move |w| (node_index(i), w))
- })
+ self.iter
+ .ex_find_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -1184,12 +1218,12 @@
}
impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.iter.ex_rfind_map(|(i, node)| {
- node.weight.as_ref().map(move |w| (node_index(i), w))
- })
+ self.iter
+ .ex_rfind_map(|(i, node)| node.weight.as_ref().map(move |w| (node_index(i), w)))
}
}
@@ -1207,10 +1241,11 @@
}
}
-impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> { }
+impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> {}
impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
- where E: PartialEq,
+where
+ E: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
self.index == rhs.index && self.weight == rhs.weight
@@ -1218,31 +1253,44 @@
}
impl<'a, Ix, E> EdgeReference<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
/// Access the edge’s weight.
///
/// **NOTE** that this method offers a longer lifetime
/// than the trait (unfortunately they don't match yet).
- pub fn weight(&self) -> &'a E { self.weight }
+ pub fn weight(&self) -> &'a E {
+ self.weight
+ }
}
impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type NodeId = NodeIndex<Ix>;
type EdgeId = EdgeIndex<Ix>;
type Weight = E;
- fn source(&self) -> Self::NodeId { self.node[0] }
- fn target(&self) -> Self::NodeId { self.node[1] }
- fn weight(&self) -> &E { self.weight }
- fn id(&self) -> Self::EdgeId { self.index }
+ fn source(&self) -> Self::NodeId {
+ self.node[0]
+ }
+ fn target(&self) -> Self::NodeId {
+ self.node[1]
+ }
+ fn weight(&self) -> &E {
+ self.weight
+ }
+ fn id(&self) -> Self::EdgeId {
+ self.index
+ }
}
impl<'a, N, E, Ty, Ix> IntoEdges for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Edges = Edges<'a, E, Ty, Ix>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
@@ -1251,8 +1299,9 @@
}
impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgesDirected = Edges<'a, E, Ty, Ix>;
fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
@@ -1262,8 +1311,9 @@
/// Iterator over the edges of from or to a node
pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// starting node to skip over
skip_start: NodeIndex<Ix>,
@@ -1279,8 +1329,9 @@
}
impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ix>;
@@ -1302,7 +1353,12 @@
if iterate_over.unwrap_or(Outgoing) == Outgoing {
let i = self.next[0].index();
- if let Some(Edge { node, weight: Some(weight), next }) = self.edges.get(i) {
+ if let Some(Edge {
+ node,
+ weight: Some(weight),
+ next,
+ }) = self.edges.get(i)
+ {
self.next[0] = next[0];
return Some(EdgeReference {
index: edge_index(i),
@@ -1335,7 +1391,7 @@
*node
},
weight: weight.as_ref().unwrap(),
- })
+ });
}
}
@@ -1349,8 +1405,9 @@
}
impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeRef = EdgeReference<'a, E, Ix>;
type EdgeReferences = EdgeReferences<'a, E, Ix>;
@@ -1360,10 +1417,9 @@
/// Iterator element type is `EdgeReference<E, Ix>`.
fn edge_references(self) -> Self::EdgeReferences {
EdgeReferences {
- iter: self.g.edges.iter().enumerate()
+ iter: self.g.edges.iter().enumerate(),
}
}
-
}
/// Iterator over all edges of a graph.
@@ -1372,34 +1428,34 @@
}
impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
type Item = EdgeReference<'a, E, Ix>;
fn next(&mut self) -> Option<Self::Item> {
- self.iter.ex_find_map(|(i, edge)|
- edge.weight.as_ref().map(move |weight| {
- EdgeReference {
- index: edge_index(i),
- node: edge.node,
- weight,
- }
- }))
+ self.iter.ex_find_map(|(i, edge)| {
+ edge.weight.as_ref().map(move |weight| EdgeReference {
+ index: edge_index(i),
+ node: edge.node,
+ weight,
+ })
+ })
}
}
impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
- where Ix: IndexType
+where
+ Ix: IndexType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.iter.ex_rfind_map(|(i, edge)|
- edge.weight.as_ref().map(move |weight| {
- EdgeReference {
- index: edge_index(i),
- node: edge.node,
- weight,
- }
- }))
+ self.iter.ex_rfind_map(|(i, edge)| {
+ edge.weight.as_ref().map(move |weight| EdgeReference {
+ index: edge_index(i),
+ node: edge.node,
+ weight,
+ })
+ })
}
}
@@ -1410,27 +1466,27 @@
ty: PhantomData<Ty>,
}
-impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix> where
+impl<'a, N: 'a, Ty, Ix> Iterator for Externals<'a, N, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
type Item = NodeIndex<Ix>;
- fn next(&mut self) -> Option<NodeIndex<Ix>>
- {
+ fn next(&mut self) -> Option<NodeIndex<Ix>> {
let k = self.dir.index();
loop {
match self.iter.next() {
None => return None,
Some((index, node)) => {
- if node.weight.is_some() &&
- node.next[k] == EdgeIndex::end() &&
- (Ty::is_directed() ||
- node.next[1-k] == EdgeIndex::end()) {
- return Some(NodeIndex::new(index))
+ if node.weight.is_some()
+ && node.next[k] == EdgeIndex::end()
+ && (Ty::is_directed() || node.next[1 - k] == EdgeIndex::end())
+ {
+ return Some(NodeIndex::new(index));
} else {
- continue
+ continue;
}
- },
+ }
}
}
}
@@ -1439,8 +1495,7 @@
/// Iterator over the neighbors of a node.
///
/// Iterator element type is `NodeIndex`.
-pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx>
-{
+pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx> {
/// starting node to skip over
skip_start: NodeIndex<Ix>,
edges: &'a [Edge<Option<E>, Ix>],
@@ -1448,7 +1503,8 @@
}
impl<'a, E, Ix> Neighbors<'a, E, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
/// Return a “walker” object that can be used to step through the
/// neighbors and edges from the origin node.
@@ -1459,13 +1515,14 @@
WalkNeighbors {
inner: super::WalkNeighbors {
skip_start: self.skip_start,
- next: self.next
+ next: self.next,
},
}
}
}
-impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix> where
+impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix>
+where
Ix: IndexType,
{
type Item = NodeIndex<Ix>;
@@ -1546,20 +1603,24 @@
/// where the `WalkNeighbors` value was created.
/// For an `Outgoing` walk, the target nodes,
/// for an `Incoming` walk, the source nodes of the edge.
- pub fn next<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
- -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
+ pub fn next<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &StableGraph<N, E, Ty, Ix>,
+ ) -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
self.inner.next(&g.g)
}
- pub fn next_node<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
- -> Option<NodeIndex<Ix>>
- {
+ pub fn next_node<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &StableGraph<N, E, Ty, Ix>,
+ ) -> Option<NodeIndex<Ix>> {
self.next(g).map(|t| t.1)
}
- pub fn next_edge<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
- -> Option<EdgeIndex<Ix>>
- {
+ pub fn next_edge<N, E, Ty: EdgeType>(
+ &mut self,
+ g: &StableGraph<N, E, Ty, Ix>,
+ ) -> Option<EdgeIndex<Ix>> {
self.next(g).map(|t| t.0)
}
}
@@ -1576,7 +1637,9 @@
self.iter.ex_find_map(|(i, node)| {
if node.weight.is_some() {
Some(node_index(i))
- } else { None }
+ } else {
+ None
+ }
})
}
@@ -1591,23 +1654,28 @@
self.iter.ex_rfind_map(|(i, node)| {
if node.weight.is_some() {
Some(node_index(i))
- } else { None }
+ } else {
+ None
+ }
})
}
}
impl<N, E, Ty, Ix> NodeIndexable for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
/// Return an upper bound of the node indices in the graph
fn node_bound(&self) -> usize {
- self.node_indices()
- .next_back()
- .map_or(0, |i| i.index() + 1)
+ self.node_indices().next_back().map_or(0, |i| i.index() + 1)
}
- fn to_index(&self, ix: NodeIndex<Ix>) -> usize { ix.index() }
- fn from_index(&self, ix: usize) -> Self::NodeId { NodeIndex::new(ix) }
+ fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
+ ix.index()
+ }
+ fn from_index(&self, ix: usize) -> Self::NodeId {
+ NodeIndex::new(ix)
+ }
}
/// Iterator over the edge indices of a graph.
@@ -1622,7 +1690,9 @@
self.iter.ex_find_map(|(i, node)| {
if node.weight.is_some() {
Some(edge_index(i))
- } else { None }
+ } else {
+ None
+ }
})
}
@@ -1637,12 +1707,13 @@
self.iter.ex_rfind_map(|(i, node)| {
if node.weight.is_some() {
Some(edge_index(i))
- } else { None }
+ } else {
+ None
+ }
})
}
}
-
#[test]
fn stable_graph() {
let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
@@ -1718,7 +1789,7 @@
assert_eq!(gr.node_count(), 5);
assert_eq!(gr.edge_count(), 8);
- gr.retain_nodes(|frozen_gr, ix| {frozen_gr[ix] >= "c"});
+ gr.retain_nodes(|frozen_gr, ix| frozen_gr[ix] >= "c");
assert_eq!(gr.node_count(), 3);
assert_eq!(gr.edge_count(), 2);
diff --git a/src/graph_impl/stable_graph/serialization.rs b/src/graph_impl/stable_graph/serialization.rs
index da031c6..c24ca63 100644
--- a/src/graph_impl/stable_graph/serialization.rs
+++ b/src/graph_impl/stable_graph/serialization.rs
@@ -1,23 +1,21 @@
-
-
use serde::de::Error;
-use serde::{Serialize, Serializer, Deserialize, Deserializer};
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::marker::PhantomData;
use crate::prelude::*;
-use crate::EdgeType;
use crate::graph::Node;
-use crate::graph::{IndexType, Edge};
+use crate::graph::{Edge, IndexType};
+use crate::serde_utils::CollectSeqWithLength;
+use crate::serde_utils::MappedSequenceVisitor;
+use crate::serde_utils::{FromDeserialized, IntoSerializable};
use crate::stable_graph::StableGraph;
use crate::util::rev;
-use crate::serde_utils::MappedSequenceVisitor;
-use crate::serde_utils::CollectSeqWithLength;
-use crate::serde_utils::{IntoSerializable, FromDeserialized};
use crate::visit::NodeIndexable;
+use crate::EdgeType;
-use super::super::serialization::{EdgeProperty, invalid_length_err, invalid_node_err};
+use super::super::serialization::{invalid_length_err, invalid_node_err, EdgeProperty};
// Serialization representation for StableGraph
// Keep in sync with deserialization and Graph
@@ -28,7 +26,7 @@
nodes: Somes<&'a [Node<Option<N>, Ix>]>,
node_holes: Holes<&'a [Node<Option<N>, Ix>]>,
edge_property: EdgeProperty,
- #[serde(serialize_with="ser_stable_graph_edges")]
+ #[serde(serialize_with = "ser_stable_graph_edges")]
edges: &'a [Edge<Option<E>, Ix>],
}
@@ -36,14 +34,16 @@
// Keep in sync with serialization and Graph
#[derive(Deserialize)]
#[serde(rename = "Graph")]
-#[serde(bound(deserialize = "N: Deserialize<'de>, E: Deserialize<'de>, Ix: IndexType + Deserialize<'de>"))]
+#[serde(bound(
+ deserialize = "N: Deserialize<'de>, E: Deserialize<'de>, Ix: IndexType + Deserialize<'de>"
+))]
pub struct DeserStableGraph<N, E, Ix> {
- #[serde(deserialize_with="deser_stable_graph_nodes")]
+ #[serde(deserialize_with = "deser_stable_graph_nodes")]
nodes: Vec<Node<Option<N>, Ix>>,
- #[serde(default="Vec::new")]
+ #[serde(default = "Vec::new")]
node_holes: Vec<NodeIndex<Ix>>,
edge_property: EdgeProperty,
- #[serde(deserialize_with="deser_stable_graph_edges")]
+ #[serde(deserialize_with = "deser_stable_graph_edges")]
edges: Vec<Edge<Option<E>, Ix>>,
}
@@ -51,13 +51,17 @@
struct Somes<T>(usize, T);
impl<'a, N, Ix> Serialize for Somes<&'a [Node<Option<N>, Ix>]>
- where N: Serialize,
+where
+ N: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where
+ S: Serializer,
{
- serializer.collect_seq_with_length(self.0,
- self.1.iter().filter_map(|node| node.weight.as_ref()))
+ serializer.collect_seq_with_length(
+ self.0,
+ self.1.iter().filter_map(|node| node.weight.as_ref()),
+ )
}
}
@@ -65,55 +69,71 @@
struct Holes<T>(usize, T);
impl<'a, N, Ix> Serialize for Holes<&'a [Node<Option<N>, Ix>]>
- where Ix: Serialize + IndexType,
+where
+ Ix: Serialize + IndexType,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
+ where
+ S: Serializer,
{
- serializer.collect_seq_with_length(self.0,
- self.1.iter()
- .enumerate()
- .filter_map(|(i, node)| if node.weight.is_none() {
- Some(NodeIndex::<Ix>::new(i))
- } else {
- None
- }))
+ serializer.collect_seq_with_length(
+ self.0,
+ self.1.iter().enumerate().filter_map(|(i, node)| {
+ if node.weight.is_none() {
+ Some(NodeIndex::<Ix>::new(i))
+ } else {
+ None
+ }
+ }),
+ )
}
}
-fn ser_stable_graph_edges<S, E, Ix>(edges: &&[Edge<Option<E>, Ix>], serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer,
- E: Serialize,
- Ix: Serialize + IndexType,
+fn ser_stable_graph_edges<S, E, Ix>(
+ edges: &&[Edge<Option<E>, Ix>],
+ serializer: S,
+) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+ E: Serialize,
+ Ix: Serialize + IndexType,
{
- serializer.collect_seq_exact(
- edges.iter()
- .map(|edge| edge.weight.as_ref().map(|w| (
- edge.source(),
- edge.target(),
- w
- ))))
+ serializer.collect_seq_exact(edges.iter().map(|edge| {
+ edge.weight
+ .as_ref()
+ .map(|w| (edge.source(), edge.target(), w))
+ }))
}
-fn deser_stable_graph_nodes<'de, D, N, Ix>(deserializer: D) -> Result<Vec<Node<Option<N>, Ix>>, D::Error>
- where D: Deserializer<'de>,
- N: Deserialize<'de>,
- Ix: IndexType + Deserialize<'de>,
+fn deser_stable_graph_nodes<'de, D, N, Ix>(
+ deserializer: D,
+) -> Result<Vec<Node<Option<N>, Ix>>, D::Error>
+where
+ D: Deserializer<'de>,
+ N: Deserialize<'de>,
+ Ix: IndexType + Deserialize<'de>,
{
- deserializer.deserialize_seq(MappedSequenceVisitor::new(|n|
+ deserializer.deserialize_seq(MappedSequenceVisitor::new(|n| {
Ok(Node {
weight: Some(n),
next: [EdgeIndex::end(); 2],
})
- ))
+ }))
}
-fn deser_stable_graph_edges<'de, D, N, Ix>(deserializer: D) -> Result<Vec<Edge<Option<N>, Ix>>, D::Error>
- where D: Deserializer<'de>,
- N: Deserialize<'de>,
- Ix: IndexType + Deserialize<'de>,
+fn deser_stable_graph_edges<'de, D, N, Ix>(
+ deserializer: D,
+) -> Result<Vec<Edge<Option<N>, Ix>>, D::Error>
+where
+ D: Deserializer<'de>,
+ N: Deserialize<'de>,
+ Ix: IndexType + Deserialize<'de>,
{
- deserializer.deserialize_seq(MappedSequenceVisitor::<Option<(NodeIndex<Ix>, NodeIndex<Ix>, N)>, _, _>::new(|x|
+ deserializer.deserialize_seq(MappedSequenceVisitor::<
+ Option<(NodeIndex<Ix>, NodeIndex<Ix>, N)>,
+ _,
+ _,
+ >::new(|x| {
if let Some((i, j, w)) = x {
Ok(Edge {
weight: Some(w),
@@ -127,12 +147,13 @@
next: [EdgeIndex::end(); 2],
})
}
- ))
+ }))
}
impl<'a, N, E, Ty, Ix> IntoSerializable for &'a StableGraph<N, E, Ty, Ix>
- where Ix: IndexType,
- Ty: EdgeType,
+where
+ Ix: IndexType,
+ Ty: EdgeType,
{
type Output = SerStableGraph<'a, N, E, Ix>;
fn into_serializable(self) -> Self::Output {
@@ -151,25 +172,29 @@
/// Requires crate feature `"serde-1"`
impl<N, E, Ty, Ix> Serialize for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType + Serialize,
- N: Serialize,
- E: Serialize,
+where
+ Ty: EdgeType,
+ Ix: IndexType + Serialize,
+ N: Serialize,
+ E: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where S: Serializer
+ where
+ S: Serializer,
{
self.into_serializable().serialize(serializer)
}
}
impl<'a, N, E, Ty, Ix> FromDeserialized for StableGraph<N, E, Ty, Ix>
- where Ix: IndexType,
- Ty: EdgeType,
+where
+ Ix: IndexType,
+ Ty: EdgeType,
{
type Input = DeserStableGraph<N, E, Ix>;
fn from_deserialized<E2>(input: Self::Input) -> Result<Self, E2>
- where E2: Error
+ where
+ E2: Error,
{
let ty = PhantomData::<Ty>::from_deserialized(input.edge_property)?;
let mut nodes = input.nodes;
@@ -188,10 +213,13 @@
Err(invalid_node_err(hole_pos.index(), node_bound))?;
}
let insert_pos = hole_pos.index() - offset;
- nodes.insert(insert_pos, Node {
- weight: None,
- next: [EdgeIndex::end(); 2],
- });
+ nodes.insert(
+ insert_pos,
+ Node {
+ weight: None,
+ next: [EdgeIndex::end(); 2],
+ },
+ );
}
if nodes.len() >= <Ix as IndexType>::max().index() {
@@ -210,20 +238,23 @@
free_edge: EdgeIndex::end(),
free_node: NodeIndex::end(),
};
- sgr.link_edges().map_err(|i| invalid_node_err(i.index(), node_bound))?;
+ sgr.link_edges()
+ .map_err(|i| invalid_node_err(i.index(), node_bound))?;
Ok(sgr)
}
}
/// Requires crate feature `"serde-1"`
impl<'de, N, E, Ty, Ix> Deserialize<'de> for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType + Deserialize<'de>,
- N: Deserialize<'de>,
- E: Deserialize<'de>,
+where
+ Ty: EdgeType,
+ Ix: IndexType + Deserialize<'de>,
+ N: Deserialize<'de>,
+ E: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'de>
+ where
+ D: Deserializer<'de>,
{
Self::from_deserialized(DeserStableGraph::deserialize(deserializer)?)
}
@@ -233,8 +264,8 @@
fn test_from_deserialized_with_holes() {
use crate::graph::node_index;
use crate::stable_graph::StableUnGraph;
- use serde::de::value::Error as SerdeError;
use itertools::assert_equal;
+ use serde::de::value::Error as SerdeError;
let input = DeserStableGraph::<_, (), u32> {
nodes: vec![
@@ -251,12 +282,7 @@
next: [EdgeIndex::end(); 2],
},
],
- node_holes: vec![
- node_index(0),
- node_index(2),
- node_index(3),
- node_index(6),
- ],
+ node_holes: vec![node_index(0), node_index(2), node_index(3), node_index(6)],
edges: vec![],
edge_property: EdgeProperty::Undirected,
};
@@ -265,6 +291,6 @@
assert_eq!(graph.node_count(), 3);
assert_equal(
graph.raw_nodes().iter().map(|n| n.weight.as_ref().cloned()),
- vec![None, Some(1), None, None, Some(4), Some(5), None]);
+ vec![None, Some(1), None, None, Some(4), Some(5), None],
+ );
}
-
diff --git a/src/graphmap.rs b/src/graphmap.rs
index 2183235..ecd0d26 100644
--- a/src/graphmap.rs
+++ b/src/graphmap.rs
@@ -1,39 +1,25 @@
//! `GraphMap<N, E, Ty>` is a graph datastructure where node values are mapping
//! keys.
-use std::cmp::Ordering;
-use std::hash::{self, Hash};
-use std::iter::{
- Cloned,
- DoubleEndedIterator,
-};
-use std::slice::{
- Iter,
-};
-use std::fmt;
-use std::ops::{Index, IndexMut, Deref};
-use std::iter::FromIterator;
-use std::marker::PhantomData;
-use indexmap::IndexMap;
-use indexmap::map::{
- Iter as IndexMapIter, IterMut as IndexMapIterMut
-};
use indexmap::map::Keys;
+use indexmap::map::{Iter as IndexMapIter, IterMut as IndexMapIterMut};
+use indexmap::IndexMap;
+use std::cmp::Ordering;
+use std::fmt;
+use std::hash::{self, Hash};
+use std::iter::FromIterator;
+use std::iter::{Cloned, DoubleEndedIterator};
+use std::marker::PhantomData;
+use std::ops::{Deref, Index, IndexMut};
+use std::slice::Iter;
-use crate::{
- EdgeType,
- Directed,
- Undirected,
- Direction,
- Incoming,
- Outgoing,
-};
+use crate::{Directed, Direction, EdgeType, Incoming, Outgoing, Undirected};
-use crate::IntoWeightedEdge;
-use crate::visit::{IntoNodeIdentifiers, NodeCount, IntoNodeReferences, NodeIndexable};
-use crate::visit::{NodeCompactIndexable, IntoEdgeReferences, IntoEdges};
-use crate::graph::Graph;
use crate::graph::node_index;
+use crate::graph::Graph;
+use crate::visit::{IntoEdgeReferences, IntoEdges, NodeCompactIndexable};
+use crate::visit::{IntoNodeIdentifiers, IntoNodeReferences, NodeCount, NodeIndexable};
+use crate::IntoWeightedEdge;
/// A `GraphMap` with undirected edges.
///
@@ -84,7 +70,7 @@
}
/// A trait group for `GraphMap`'s node identifier.
-pub trait NodeTrait : Copy + Ord + Hash {}
+pub trait NodeTrait: Copy + Ord + Hash {}
impl<N> NodeTrait for N where N: Copy + Ord + Hash {}
// non-repr(usize) version of Direction
@@ -110,8 +96,9 @@
}
impl<N, E, Ty> GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
/// Create a new `GraphMap`
pub fn new() -> Self {
@@ -167,8 +154,9 @@
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E, NodeId=N>
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E, NodeId = N>,
{
Self::from_iter(iterable)
}
@@ -241,14 +229,16 @@
old
} else {
// insert in the adjacency list if it's a new edge
- self.nodes.entry(a)
- .or_insert_with(|| Vec::with_capacity(1))
- .push((b, CompactDirection::Outgoing));
+ self.nodes
+ .entry(a)
+ .or_insert_with(|| Vec::with_capacity(1))
+ .push((b, CompactDirection::Outgoing));
if a != b {
// self loops don't have the Incoming entry
- self.nodes.entry(b)
- .or_insert_with(|| Vec::with_capacity(1))
- .push((a, CompactDirection::Incoming));
+ self.nodes
+ .entry(b)
+ .or_insert_with(|| Vec::with_capacity(1))
+ .push((a, CompactDirection::Incoming));
}
None
}
@@ -262,13 +252,22 @@
None => false,
Some(sus) => {
if Ty::is_directed() {
- match sus.iter().position(|elt| elt == &(*b, CompactDirection::from(dir))) {
- Some(index) => { sus.swap_remove(index); true }
+ match sus
+ .iter()
+ .position(|elt| elt == &(*b, CompactDirection::from(dir)))
+ {
+ Some(index) => {
+ sus.swap_remove(index);
+ true
+ }
None => false,
}
} else {
match sus.iter().position(|elt| &elt.0 == b) {
- Some(index) => { sus.swap_remove(index); true }
+ Some(index) => {
+ sus.swap_remove(index);
+ true
+ }
None => false,
}
}
@@ -295,7 +294,9 @@
let exist1 = self.remove_single_edge(&a, &b, Outgoing);
let exist2 = if a != b {
self.remove_single_edge(&b, &a, Incoming)
- } else { exist1 };
+ } else {
+ exist1
+ };
let weight = self.edges.remove(&Self::edge_key(a, b));
debug_assert!(exist1 == exist2 && exist1 == weight.is_some());
weight
@@ -310,7 +311,9 @@
///
/// Iterator element type is `N`.
pub fn nodes(&self) -> Nodes<N> {
- Nodes{iter: self.nodes.keys().cloned()}
+ Nodes {
+ iter: self.nodes.keys().cloned(),
+ }
}
/// Return an iterator of all nodes with an edge starting from `a`.
@@ -340,9 +343,7 @@
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is `N`.
- pub fn neighbors_directed(&self, a: N, dir: Direction)
- -> NeighborsDirected<N, Ty>
- {
+ pub fn neighbors_directed(&self, a: N, dir: Direction) -> NeighborsDirected<N, Ty> {
NeighborsDirected {
iter: match self.nodes.get(&a) {
Some(neigh) => neigh.iter(),
@@ -415,7 +416,8 @@
/// **Panics** if the number of nodes or edges does not fit with
/// the resulting graph's index type.
pub fn into_graph<Ix>(self) -> Graph<N, E, Ty, Ix>
- where Ix: crate::graph::IndexType,
+ where
+ Ix: crate::graph::IndexType,
{
// assuming two successive iterations of the same hashmap produce the same order
let mut gr = Graph::with_capacity(self.node_count(), self.edge_count());
@@ -433,12 +435,14 @@
/// Create a new `GraphMap` from an iterable of edges.
impl<N, E, Ty, Item> FromIterator<Item> for GraphMap<N, E, Ty>
- where Item: IntoWeightedEdge<E, NodeId=N>,
- N: NodeTrait,
- Ty: EdgeType,
+where
+ Item: IntoWeightedEdge<E, NodeId = N>,
+ N: NodeTrait,
+ Ty: EdgeType,
{
fn from_iter<I>(iterable: I) -> Self
- where I: IntoIterator<Item=Item>,
+ where
+ I: IntoIterator<Item = Item>,
{
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
@@ -452,12 +456,14 @@
///
/// Nodes are inserted automatically to match the edges.
impl<N, E, Ty, Item> Extend<Item> for GraphMap<N, E, Ty>
- where Item: IntoWeightedEdge<E, NodeId=N>,
- N: NodeTrait,
- Ty: EdgeType,
+where
+ Item: IntoWeightedEdge<E, NodeId = N>,
+ N: NodeTrait,
+ Ty: EdgeType,
{
fn extend<I>(&mut self, iterable: I)
- where I: IntoIterator<Item=Item>,
+ where
+ I: IntoIterator<Item = Item>,
{
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
@@ -502,24 +508,24 @@
}
pub struct Neighbors<'a, N, Ty = Undirected>
- where N: 'a,
- Ty: EdgeType,
+where
+ N: 'a,
+ Ty: EdgeType,
{
iter: Iter<'a, (N, CompactDirection)>,
ty: PhantomData<Ty>,
}
impl<'a, N, Ty> Iterator for Neighbors<'a, N, Ty>
- where N: NodeTrait,
- Ty: EdgeType
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type Item = N;
fn next(&mut self) -> Option<N> {
if Ty::is_directed() {
(&mut self.iter)
- .filter_map(|&(n, dir)| if dir == Outgoing {
- Some(n)
- } else { None })
+ .filter_map(|&(n, dir)| if dir == Outgoing { Some(n) } else { None })
.next()
} else {
self.iter.next().map(|&(n, _)| n)
@@ -528,8 +534,9 @@
}
pub struct NeighborsDirected<'a, N, Ty>
- where N: 'a,
- Ty: EdgeType,
+where
+ N: 'a,
+ Ty: EdgeType,
{
iter: Iter<'a, (N, CompactDirection)>,
start_node: N,
@@ -538,8 +545,9 @@
}
impl<'a, N, Ty> Iterator for NeighborsDirected<'a, N, Ty>
- where N: NodeTrait,
- Ty: EdgeType
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type Item = N;
fn next(&mut self) -> Option<N> {
@@ -547,9 +555,13 @@
let self_dir = self.dir;
let start_node = self.start_node;
(&mut self.iter)
- .filter_map(move |&(n, dir)| if dir == self_dir || n == start_node {
- Some(n)
- } else { None })
+ .filter_map(move |&(n, dir)| {
+ if dir == self_dir || n == start_node {
+ Some(n)
+ } else {
+ None
+ }
+ })
.next()
} else {
self.iter.next().map(|&(n, _)| n)
@@ -558,8 +570,9 @@
}
pub struct Edges<'a, N, E: 'a, Ty>
- where N: 'a + NodeTrait,
- Ty: EdgeType
+where
+ N: 'a + NodeTrait,
+ Ty: EdgeType,
{
from: N,
edges: &'a IndexMap<(N, N), E>,
@@ -567,8 +580,10 @@
}
impl<'a, N, E, Ty> Iterator for Edges<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
type Item = (N, N, &'a E);
fn next(&mut self) -> Option<Self::Item> {
@@ -578,9 +593,7 @@
let a = self.from;
match self.edges.get(&GraphMap::<N, E, Ty>::edge_key(a, b)) {
None => unreachable!(),
- Some(edge) => {
- Some((a, b, edge))
- }
+ Some(edge) => Some((a, b, edge)),
}
}
}
@@ -588,8 +601,9 @@
}
impl<'a, N: 'a, E: 'a, Ty> IntoEdgeReferences for &'a GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type EdgeRef = (N, N, &'a E);
type EdgeReferences = AllEdges<'a, N, E, Ty>;
@@ -598,21 +612,25 @@
}
}
-pub struct AllEdges<'a, N, E: 'a, Ty> where N: 'a + NodeTrait {
+pub struct AllEdges<'a, N, E: 'a, Ty>
+where
+ N: 'a + NodeTrait,
+{
inner: IndexMapIter<'a, (N, N), E>,
ty: PhantomData<Ty>,
}
impl<'a, N, E, Ty> Iterator for AllEdges<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
type Item = (N, N, &'a E);
- fn next(&mut self) -> Option<Self::Item>
- {
+ fn next(&mut self) -> Option<Self::Item> {
match self.inner.next() {
None => None,
- Some((&(a, b), v)) => Some((a, b, v))
+ Some((&(a, b), v)) => Some((a, b, v)),
}
}
@@ -625,35 +643,50 @@
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
- self.inner.nth(n).map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .nth(n)
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn last(self) -> Option<Self::Item> {
- self.inner.last().map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .last()
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<'a, N, E, Ty> DoubleEndedIterator for AllEdges<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.inner.next_back().map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .next_back()
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
-pub struct AllEdgesMut<'a, N, E: 'a, Ty> where N: 'a + NodeTrait {
+pub struct AllEdgesMut<'a, N, E: 'a, Ty>
+where
+ N: 'a + NodeTrait,
+{
inner: IndexMapIterMut<'a, (N, N), E>,
ty: PhantomData<Ty>,
}
impl<'a, N, E, Ty> Iterator for AllEdgesMut<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
type Item = (N, N, &'a mut E);
fn next(&mut self) -> Option<Self::Item> {
- self.inner.next().map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .next()
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn size_hint(&self) -> (usize, Option<usize>) {
@@ -665,26 +698,35 @@
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
- self.inner.nth(n).map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .nth(n)
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
fn last(self) -> Option<Self::Item> {
- self.inner.last().map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .last()
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<'a, N, E, Ty> DoubleEndedIterator for AllEdgesMut<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
fn next_back(&mut self) -> Option<Self::Item> {
- self.inner.next_back().map(|(&(n1, n2), weight)| (n1, n2, weight))
+ self.inner
+ .next_back()
+ .map(|(&(n1, n2), weight)| (n1, n2, weight))
}
}
impl<'a, N: 'a, E: 'a, Ty> IntoEdges for &'a GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type Edges = Edges<'a, N, E, Ty>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
@@ -692,37 +734,42 @@
}
}
-
/// Index `GraphMap` by node pairs to access edge weights.
impl<N, E, Ty> Index<(N, N)> for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type Output = E;
- fn index(&self, index: (N, N)) -> &E
- {
+ fn index(&self, index: (N, N)) -> &E {
let index = Self::edge_key(index.0, index.1);
- self.edge_weight(index.0, index.1).expect("GraphMap::index: no such edge")
+ self.edge_weight(index.0, index.1)
+ .expect("GraphMap::index: no such edge")
}
}
/// Index `GraphMap` by node pairs to access edge weights.
impl<N, E, Ty> IndexMut<(N, N)> for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
fn index_mut(&mut self, index: (N, N)) -> &mut E {
let index = Self::edge_key(index.0, index.1);
- self.edge_weight_mut(index.0, index.1).expect("GraphMap::index: no such edge")
+ self.edge_weight_mut(index.0, index.1)
+ .expect("GraphMap::index: no such edge")
}
}
/// Create a new empty `GraphMap`.
impl<N, E, Ty> Default for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
- fn default() -> Self { GraphMap::with_capacity(0, 0) }
+ fn default() -> Self {
+ GraphMap::with_capacity(0, 0)
+ }
}
/// A reference that is hashed and compared by its pointer value.
@@ -734,33 +781,30 @@
pub struct Ptr<'b, T: 'b>(pub &'b T);
impl<'b, T> Copy for Ptr<'b, T> {}
-impl<'b, T> Clone for Ptr<'b, T>
-{
- fn clone(&self) -> Self { *self }
+impl<'b, T> Clone for Ptr<'b, T> {
+ fn clone(&self) -> Self {
+ *self
+ }
}
-
fn ptr_eq<T>(a: *const T, b: *const T) -> bool {
a == b
}
-impl<'b, T> PartialEq for Ptr<'b, T>
-{
+impl<'b, T> PartialEq for Ptr<'b, T> {
/// Ptr compares by pointer equality, i.e if they point to the same value
fn eq(&self, other: &Ptr<'b, T>) -> bool {
ptr_eq(self.0, other.0)
}
}
-impl<'b, T> PartialOrd for Ptr<'b, T>
-{
+impl<'b, T> PartialOrd for Ptr<'b, T> {
fn partial_cmp(&self, other: &Ptr<'b, T>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
-impl<'b, T> Ord for Ptr<'b, T>
-{
+impl<'b, T> Ord for Ptr<'b, T> {
/// Ptr is ordered by pointer value, i.e. an arbitrary but stable and total order.
fn cmp(&self, other: &Ptr<'b, T>) -> Ordering {
let a: *const T = self.0;
@@ -778,10 +822,8 @@
impl<'b, T> Eq for Ptr<'b, T> {}
-impl<'b, T> Hash for Ptr<'b, T>
-{
- fn hash<H: hash::Hasher>(&self, st: &mut H)
- {
+impl<'b, T> Hash for Ptr<'b, T> {
+ fn hash<H: hash::Hasher>(&self, st: &mut H) {
let ptr = (self.0) as *const T;
ptr.hash(st)
}
@@ -794,8 +836,9 @@
}
impl<'a, N, E: 'a, Ty> IntoNodeIdentifiers for &'a GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type NodeIdentifiers = NodeIdentifiers<'a, N, E, Ty>;
@@ -809,34 +852,40 @@
}
impl<N, E, Ty> NodeCount for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
fn node_count(&self) -> usize {
(*self).node_count()
}
}
-pub struct NodeIdentifiers<'a, N, E: 'a, Ty> where N: 'a + NodeTrait {
+pub struct NodeIdentifiers<'a, N, E: 'a, Ty>
+where
+ N: 'a + NodeTrait,
+{
iter: IndexMapIter<'a, N, Vec<(N, CompactDirection)>>,
ty: PhantomData<Ty>,
edge_ty: PhantomData<E>,
}
impl<'a, N, E, Ty> Iterator for NodeIdentifiers<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
type Item = N;
- fn next(&mut self) -> Option<Self::Item>
- {
+ fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(&n, _)| n)
}
}
impl<'a, N, E, Ty> IntoNodeReferences for &'a GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type NodeRef = (N, &'a N);
type NodeReferences = NodeReferences<'a, N, E, Ty>;
@@ -849,28 +898,35 @@
}
}
-pub struct NodeReferences<'a, N, E: 'a, Ty> where N: 'a + NodeTrait {
+pub struct NodeReferences<'a, N, E: 'a, Ty>
+where
+ N: 'a + NodeTrait,
+{
iter: IndexMapIter<'a, N, Vec<(N, CompactDirection)>>,
ty: PhantomData<Ty>,
edge_ty: PhantomData<E>,
}
impl<'a, N, E, Ty> Iterator for NodeReferences<'a, N, E, Ty>
- where N: 'a + NodeTrait, E: 'a,
- Ty: EdgeType,
+where
+ N: 'a + NodeTrait,
+ E: 'a,
+ Ty: EdgeType,
{
type Item = (N, &'a N);
- fn next(&mut self) -> Option<Self::Item>
- {
+ fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(n, _)| (*n, n))
}
}
impl<N, E, Ty> NodeIndexable for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
- fn node_bound(&self) -> usize { self.node_count() }
+ fn node_bound(&self) -> usize {
+ self.node_count()
+ }
fn to_index(&self, ix: Self::NodeId) -> usize {
let (i, _, _) = self.nodes.get_full(&ix).unwrap();
i
@@ -882,8 +938,8 @@
}
impl<N, E, Ty> NodeCompactIndexable for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
}
-
diff --git a/src/isomorphism.rs b/src/isomorphism.rs
index e85c328..1d2cd27 100644
--- a/src/isomorphism.rs
+++ b/src/isomorphism.rs
@@ -1,15 +1,8 @@
-use std::marker;
use fixedbitset::FixedBitSet;
+use std::marker;
-use super::{
- EdgeType,
- Incoming,
-};
-use super::graph::{
- Graph,
- IndexType,
- NodeIndex,
-};
+use super::graph::{Graph, IndexType, NodeIndex};
+use super::{EdgeType, Incoming};
use super::visit::GetAdjacencyMatrix;
@@ -35,8 +28,9 @@
}
impl<Ty, Ix> Vf2State<Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
pub fn new<N, E>(g: &Graph<N, E, Ty, Ix>) -> Self {
let c0 = g.node_count();
@@ -66,9 +60,12 @@
}
/// Add mapping **from** <-> **to** to the state.
- pub fn push_mapping<N, E>(&mut self, from: NodeIndex<Ix>, to: NodeIndex<Ix>,
- g: &Graph<N, E, Ty, Ix>)
- {
+ pub fn push_mapping<N, E>(
+ &mut self,
+ from: NodeIndex<Ix>,
+ to: NodeIndex<Ix>,
+ g: &Graph<N, E, Ty, Ix>,
+ ) {
self.generation += 1;
let s = self.generation;
self.mapping[from.index()] = to;
@@ -92,9 +89,7 @@
}
/// Restore the state to before the last added mapping
- pub fn pop_mapping<N, E>(&mut self, from: NodeIndex<Ix>,
- g: &Graph<N, E, Ty, Ix>)
- {
+ pub fn pop_mapping<N, E>(&mut self, from: NodeIndex<Ix>, g: &Graph<N, E, Ty, Ix>) {
let s = self.generation;
self.generation -= 1;
@@ -119,39 +114,40 @@
}
/// Find the next (least) node in the Tout set.
- pub fn next_out_index(&self, from_index: usize) -> Option<usize>
- {
- self.out[from_index..].iter()
- .enumerate()
- .find(move |&(index, elt)| *elt > 0 &&
- self.mapping[from_index + index] == NodeIndex::end())
- .map(|(index, _)| index)
+ pub fn next_out_index(&self, from_index: usize) -> Option<usize> {
+ self.out[from_index..]
+ .iter()
+ .enumerate()
+ .find(move |&(index, elt)| {
+ *elt > 0 && self.mapping[from_index + index] == NodeIndex::end()
+ })
+ .map(|(index, _)| index)
}
/// Find the next (least) node in the Tin set.
- pub fn next_in_index(&self, from_index: usize) -> Option<usize>
- {
+ pub fn next_in_index(&self, from_index: usize) -> Option<usize> {
if !Ty::is_directed() {
- return None
+ return None;
}
- self.ins[from_index..].iter()
- .enumerate()
- .find(move |&(index, elt)| *elt > 0
- && self.mapping[from_index + index] == NodeIndex::end())
- .map(|(index, _)| index)
+ self.ins[from_index..]
+ .iter()
+ .enumerate()
+ .find(move |&(index, elt)| {
+ *elt > 0 && self.mapping[from_index + index] == NodeIndex::end()
+ })
+ .map(|(index, _)| index)
}
/// Find the next (least) node in the N - M set.
- pub fn next_rest_index(&self, from_index: usize) -> Option<usize>
- {
- self.mapping[from_index..].iter()
- .enumerate()
- .find(|&(_, elt)| *elt == NodeIndex::end())
- .map(|(index, _)| index)
+ pub fn next_rest_index(&self, from_index: usize) -> Option<usize> {
+ self.mapping[from_index..]
+ .iter()
+ .enumerate()
+ .find(|&(_, elt)| *elt == NodeIndex::end())
+ .map(|(index, _)| index)
}
}
-
/// [Graph] Return `true` if the graphs `g0` and `g1` are isomorphic.
///
/// Using the VF2 algorithm, only matching graph syntactically (graph
@@ -163,13 +159,13 @@
///
/// * Luigi P. Cordella, Pasquale Foggia, Carlo Sansone, Mario Vento;
/// *A (Sub)Graph Isomorphism Algorithm for Matching Large Graphs*
-pub fn is_isomorphic<N, E, Ty, Ix>(g0: &Graph<N, E, Ty, Ix>,
- g1: &Graph<N, E, Ty, Ix>) -> bool
- where Ty: EdgeType,
- Ix: IndexType,
+pub fn is_isomorphic<N, E, Ty, Ix>(g0: &Graph<N, E, Ty, Ix>, g1: &Graph<N, E, Ty, Ix>) -> bool
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
if g0.node_count() != g1.node_count() || g0.edge_count() != g1.edge_count() {
- return false
+ return false;
}
let mut st = [Vf2State::new(g0), Vf2State::new(g1)];
@@ -182,17 +178,20 @@
/// graph isomorphism (graph structure and matching node and edge weights).
///
/// The graphs should not be multigraphs.
-pub fn is_isomorphic_matching<N, E, Ty, Ix, F, G>(g0: &Graph<N, E, Ty, Ix>,
- g1: &Graph<N, E, Ty, Ix>,
- mut node_match: F,
- mut edge_match: G) -> bool
- where Ty: EdgeType,
- Ix: IndexType,
- F: FnMut(&N, &N) -> bool,
- G: FnMut(&E, &E) -> bool,
+pub fn is_isomorphic_matching<N, E, Ty, Ix, F, G>(
+ g0: &Graph<N, E, Ty, Ix>,
+ g1: &Graph<N, E, Ty, Ix>,
+ mut node_match: F,
+ mut edge_match: G,
+) -> bool
+where
+ Ty: EdgeType,
+ Ix: IndexType,
+ F: FnMut(&N, &N) -> bool,
+ G: FnMut(&E, &E) -> bool,
{
if g0.node_count() != g1.node_count() || g0.edge_count() != g1.edge_count() {
- return false
+ return false;
}
let mut st = [Vf2State::new(g0), Vf2State::new(g1)];
@@ -208,29 +207,42 @@
impl<T> SemanticMatcher<T> for NoSemanticMatch {
#[inline]
- fn enabled() -> bool { false }
+ fn enabled() -> bool {
+ false
+ }
#[inline]
- fn eq(&mut self, _: &T, _: &T) -> bool { true }
+ fn eq(&mut self, _: &T, _: &T) -> bool {
+ true
+ }
}
-impl<T, F> SemanticMatcher<T> for F where F: FnMut(&T, &T) -> bool {
+impl<T, F> SemanticMatcher<T> for F
+where
+ F: FnMut(&T, &T) -> bool,
+{
#[inline]
- fn enabled() -> bool { true }
+ fn enabled() -> bool {
+ true
+ }
#[inline]
- fn eq(&mut self, a: &T, b: &T) -> bool { self(a, b) }
+ fn eq(&mut self, a: &T, b: &T) -> bool {
+ self(a, b)
+ }
}
/// Return Some(bool) if isomorphism is decided, else None.
-fn try_match<N, E, Ty, Ix, F, G>(mut st: &mut [Vf2State<Ty, Ix>; 2],
- g0: &Graph<N, E, Ty, Ix>,
- g1: &Graph<N, E, Ty, Ix>,
- node_match: &mut F,
- edge_match: &mut G)
- -> Option<bool>
- where Ty: EdgeType,
- Ix: IndexType,
- F: SemanticMatcher<N>,
- G: SemanticMatcher<E>,
+fn try_match<N, E, Ty, Ix, F, G>(
+ mut st: &mut [Vf2State<Ty, Ix>; 2],
+ g0: &Graph<N, E, Ty, Ix>,
+ g1: &Graph<N, E, Ty, Ix>,
+ node_match: &mut F,
+ edge_match: &mut G,
+) -> Option<bool>
+where
+ Ty: EdgeType,
+ Ix: IndexType,
+ F: SemanticMatcher<N>,
+ G: SemanticMatcher<E>,
{
if st[0].is_complete() {
return Some(true);
@@ -254,77 +266,81 @@
#[derive(Clone, PartialEq, Debug)]
enum Frame<N: marker::Copy> {
Outer,
- Inner{ nodes: [N; 2], open_list: OpenList },
- Unwind{ nodes: [N; 2], open_list: OpenList },
+ Inner { nodes: [N; 2], open_list: OpenList },
+ Unwind { nodes: [N; 2], open_list: OpenList },
}
- let next_candidate = |st: &mut[Vf2State<Ty, Ix>; 2]|
- -> Option<(NodeIndex<Ix>, NodeIndex<Ix>, OpenList)> {
- let mut to_index;
- let mut from_index = None;
- let mut open_list = OpenList::Out;
- // Try the out list
- to_index = st[1].next_out_index(0);
-
- if to_index.is_some() {
- from_index = st[0].next_out_index(0);
- open_list = OpenList::Out;
- }
- // Try the in list
- if to_index.is_none() || from_index.is_none() {
- to_index = st[1].next_in_index(0);
+ let next_candidate =
+ |st: &mut [Vf2State<Ty, Ix>; 2]| -> Option<(NodeIndex<Ix>, NodeIndex<Ix>, OpenList)> {
+ let mut to_index;
+ let mut from_index = None;
+ let mut open_list = OpenList::Out;
+ // Try the out list
+ to_index = st[1].next_out_index(0);
if to_index.is_some() {
- from_index = st[0].next_in_index(0);
- open_list = OpenList::In;
+ from_index = st[0].next_out_index(0);
+ open_list = OpenList::Out;
}
- }
- // Try the other list -- disconnected graph
- if to_index.is_none() || from_index.is_none() {
- to_index = st[1].next_rest_index(0);
- if to_index.is_some() {
- from_index = st[0].next_rest_index(0);
- open_list = OpenList::Other;
+ // Try the in list
+ if to_index.is_none() || from_index.is_none() {
+ to_index = st[1].next_in_index(0);
+
+ if to_index.is_some() {
+ from_index = st[0].next_in_index(0);
+ open_list = OpenList::In;
+ }
}
- }
- match (from_index, to_index) {
- (Some(n), Some(m)) => Some((NodeIndex::new(n), NodeIndex::new(m), open_list)),
- // No more candidates
- _ => None,
- }
- };
- let next_from_ix = |st: &mut[Vf2State<Ty, Ix>; 2], nx: NodeIndex<Ix>, open_list: OpenList| -> Option<NodeIndex<Ix>> {
+ // Try the other list -- disconnected graph
+ if to_index.is_none() || from_index.is_none() {
+ to_index = st[1].next_rest_index(0);
+ if to_index.is_some() {
+ from_index = st[0].next_rest_index(0);
+ open_list = OpenList::Other;
+ }
+ }
+ match (from_index, to_index) {
+ (Some(n), Some(m)) => Some((NodeIndex::new(n), NodeIndex::new(m), open_list)),
+ // No more candidates
+ _ => None,
+ }
+ };
+ let next_from_ix = |st: &mut [Vf2State<Ty, Ix>; 2],
+ nx: NodeIndex<Ix>,
+ open_list: OpenList|
+ -> Option<NodeIndex<Ix>> {
// Find the next node index to try on the `from` side of the mapping
let start = nx.index() + 1;
let cand0 = match open_list {
OpenList::Out => st[0].next_out_index(start),
OpenList::In => st[0].next_in_index(start),
OpenList::Other => st[0].next_rest_index(start),
- }.map(|c| c + start); // compensate for start offset.
+ }
+ .map(|c| c + start); // compensate for start offset.
match cand0 {
None => None, // no more candidates
Some(ix) => {
debug_assert!(ix >= start);
Some(NodeIndex::new(ix))
- },
+ }
}
};
//fn pop_state(nodes: [NodeIndex<Ix>; 2]) {
- let pop_state = |st: &mut[Vf2State<Ty, Ix>; 2], nodes: [NodeIndex<Ix>; 2]| {
+ let pop_state = |st: &mut [Vf2State<Ty, Ix>; 2], nodes: [NodeIndex<Ix>; 2]| {
// Restore state.
for j in graph_indices.clone() {
st[j].pop_mapping(nodes[j], g[j]);
}
};
//fn push_state(nodes: [NodeIndex<Ix>; 2]) {
- let push_state = |st: &mut[Vf2State<Ty, Ix>; 2],nodes: [NodeIndex<Ix>; 2]| {
+ let push_state = |st: &mut [Vf2State<Ty, Ix>; 2], nodes: [NodeIndex<Ix>; 2]| {
// Add mapping nx <-> mx to the state
for j in graph_indices.clone() {
- st[j].push_mapping(nodes[j], nodes[1-j], g[j]);
+ st[j].push_mapping(nodes[j], nodes[1 - j], g[j]);
}
};
//fn is_feasible(nodes: [NodeIndex<Ix>; 2]) -> bool {
- let mut is_feasible = |st: &mut[Vf2State<Ty, Ix>; 2], nodes: [NodeIndex<Ix>; 2]| -> bool {
+ let mut is_feasible = |st: &mut [Vf2State<Ty, Ix>; 2], nodes: [NodeIndex<Ix>; 2]| -> bool {
// Check syntactic feasibility of mapping by ensuring adjacencies
// of nx map to adjacencies of mx.
//
@@ -355,7 +371,8 @@
if m_neigh == end {
continue;
}
- let has_edge = g[1-j].is_adjacent(&st[1-j].adjacency_matrix, nodes[1-j], m_neigh);
+ let has_edge =
+ g[1 - j].is_adjacent(&st[1 - j].adjacency_matrix, nodes[1 - j], m_neigh);
if !has_edge {
return false;
}
@@ -375,7 +392,8 @@
if m_neigh == end {
continue;
}
- let has_edge = g[1-j].is_adjacent(&st[1-j].adjacency_matrix, m_neigh, nodes[1-j]);
+ let has_edge =
+ g[1 - j].is_adjacent(&st[1 - j].adjacency_matrix, m_neigh, nodes[1 - j]);
if !has_edge {
return false;
}
@@ -404,13 +422,13 @@
if m_neigh == end {
continue;
}
- match g[1-j].find_edge(nodes[1 - j], m_neigh) {
+ match g[1 - j].find_edge(nodes[1 - j], m_neigh) {
Some(m_edge) => {
- if !edge_match.eq(&g[j][n_edge], &g[1-j][m_edge]) {
+ if !edge_match.eq(&g[j][n_edge], &g[1 - j][m_edge]) {
return false;
}
}
- None => unreachable!() // covered by syntactic check
+ None => unreachable!(), // covered by syntactic check
}
}
}
@@ -424,13 +442,13 @@
if m_neigh == end {
continue;
}
- match g[1-j].find_edge(m_neigh, nodes[1-j]) {
+ match g[1 - j].find_edge(m_neigh, nodes[1 - j]) {
Some(m_edge) => {
- if !edge_match.eq(&g[j][n_edge], &g[1-j][m_edge]) {
+ if !edge_match.eq(&g[j][n_edge], &g[1 - j][m_edge]) {
return false;
}
}
- None => unreachable!() // covered by syntactic check
+ None => unreachable!(), // covered by syntactic check
}
}
}
@@ -442,46 +460,61 @@
while let Some(frame) = stack.pop() {
match frame {
- Frame::Unwind{nodes, open_list: ol} => {
+ Frame::Unwind {
+ nodes,
+ open_list: ol,
+ } => {
pop_state(&mut st, nodes);
match next_from_ix(&mut st, nodes[0], ol) {
None => continue,
Some(nx) => {
- let f = Frame::Inner{nodes: [nx, nodes[1]], open_list: ol};
+ let f = Frame::Inner {
+ nodes: [nx, nodes[1]],
+ open_list: ol,
+ };
stack.push(f);
}
}
}
- Frame::Outer => {
- match next_candidate(&mut st) {
- None => continue,
- Some((nx, mx, ol)) => {
- let f = Frame::Inner{nodes: [nx, mx], open_list: ol};
- stack.push(f);
- }
+ Frame::Outer => match next_candidate(&mut st) {
+ None => continue,
+ Some((nx, mx, ol)) => {
+ let f = Frame::Inner {
+ nodes: [nx, mx],
+ open_list: ol,
+ };
+ stack.push(f);
}
- }
- Frame::Inner{nodes, open_list: ol} => {
+ },
+ Frame::Inner {
+ nodes,
+ open_list: ol,
+ } => {
if is_feasible(&mut st, nodes) {
push_state(&mut st, nodes);
if st[0].is_complete() {
return Some(true);
}
// Check cardinalities of Tin, Tout sets
- if st[0].out_size == st[1].out_size &&
- st[0].ins_size == st[1].ins_size {
- let f0 = Frame::Unwind{nodes, open_list: ol};
- stack.push(f0);
- stack.push(Frame::Outer);
- continue;
+ if st[0].out_size == st[1].out_size && st[0].ins_size == st[1].ins_size {
+ let f0 = Frame::Unwind {
+ nodes,
+ open_list: ol,
+ };
+ stack.push(f0);
+ stack.push(Frame::Outer);
+ continue;
}
pop_state(&mut st, nodes);
}
match next_from_ix(&mut st, nodes[0], ol) {
None => continue,
Some(nx) => {
- let f = Frame::Inner{nodes: [nx, nodes[1]], open_list: ol};
+ let f = Frame::Inner {
+ nodes: [nx, nodes[1]],
+ open_list: ol,
+ };
stack.push(f);
}
}
diff --git a/src/iter_format.rs b/src/iter_format.rs
index de03a2a..f6ffd6a 100644
--- a/src/iter_format.rs
+++ b/src/iter_format.rs
@@ -7,15 +7,14 @@
pub struct DebugMap<F>(pub F);
impl<'a, F, I, K, V> fmt::Debug for DebugMap<F>
- where F: Fn() -> I,
- I: IntoIterator<Item=(K, V)>,
- K: fmt::Debug,
- V: fmt::Debug,
+where
+ F: Fn() -> I,
+ I: IntoIterator<Item = (K, V)>,
+ K: fmt::Debug,
+ V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_map()
- .entries((self.0)())
- .finish()
+ f.debug_map().entries((self.0)()).finish()
}
}
@@ -23,7 +22,8 @@
pub struct NoPretty<T>(pub T);
impl<T> fmt::Debug for NoPretty<T>
- where T: fmt::Debug,
+where
+ T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.0)
@@ -44,9 +44,10 @@
inner: RefCell<Option<I>>,
}
-pub trait IterFormatExt : Iterator {
+pub trait IterFormatExt: Iterator {
fn format(self, separator: &str) -> Format<Self>
- where Self: Sized
+ where
+ Self: Sized,
{
Format {
sep: separator,
@@ -55,14 +56,15 @@
}
}
-impl<I> IterFormatExt for I where I: Iterator { }
-
+impl<I> IterFormatExt for I where I: Iterator {}
impl<'a, I> Format<'a, I>
- where I: Iterator,
+where
+ I: Iterator,
{
fn format<F>(&self, f: &mut fmt::Formatter, mut cb: F) -> fmt::Result
- where F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result,
+ where
+ F: FnMut(&I::Item, &mut fmt::Formatter) -> fmt::Result,
{
let mut iter = match self.inner.borrow_mut().take() {
Some(t) => t,
diff --git a/src/iter_utils.rs b/src/iter_utils.rs
index 30db2d5..587af84 100644
--- a/src/iter_utils.rs
+++ b/src/iter_utils.rs
@@ -1,9 +1,9 @@
-
-pub trait IterUtilsExt : Iterator {
+pub trait IterUtilsExt: Iterator {
/// Return the first element that maps to `Some(_)`, or None if the iterator
/// was exhausted.
fn ex_find_map<F, R>(&mut self, mut f: F) -> Option<R>
- where F: FnMut(Self::Item) -> Option<R>
+ where
+ F: FnMut(Self::Item) -> Option<R>,
{
for elt in self {
if let result @ Some(_) = f(elt) {
@@ -16,8 +16,9 @@
/// Return the last element from the back that maps to `Some(_)`, or
/// None if the iterator was exhausted.
fn ex_rfind_map<F, R>(&mut self, mut f: F) -> Option<R>
- where F: FnMut(Self::Item) -> Option<R>,
- Self: DoubleEndedIterator,
+ where
+ F: FnMut(Self::Item) -> Option<R>,
+ Self: DoubleEndedIterator,
{
while let Some(elt) = self.next_back() {
if let result @ Some(_) = f(elt) {
@@ -28,4 +29,4 @@
}
}
-impl<I> IterUtilsExt for I where I: Iterator { }
+impl<I> IterUtilsExt for I where I: Iterator {}
diff --git a/src/lib.rs b/src/lib.rs
index aaaec0c..d475884 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,6 +1,5 @@
-
//! `petgraph` is a graph data structure library.
-//!
+//!
//! Graphs are collections of nodes, and edges between nodes. `petgraph`
//! provides several [graph types](index.html#graph-types) (each differing in the
//! tradeoffs taken in their internal representation),
@@ -8,9 +7,9 @@
//! [output graphs](./doc/petgraph/dot/struct.Dot.html) in
//! [`graphviz`](https://www.graphviz.org/) format. Both nodes and edges
//! can have arbitrary associated data, and edges may be either directed or undirected.
-//!
+//!
//! # Example
-//!
+//!
//! ```rust
//! use petgraph::graph::{NodeIndex, UnGraph};
//! use petgraph::algo::{dijkstra, min_spanning_tree};
@@ -45,7 +44,7 @@
//! ```
//!
//! # Graph types
-//!
+//!
//! * [`Graph`](./graph/struct.Graph.html) -
//! An adjacency list graph with arbitrary associated data.
//! * [`StableGraph`](./stable_graph/struct.StableGraph.html) -
@@ -59,11 +58,11 @@
//! A sparse adjacency matrix graph with arbitrary associated data.
//!
//! ### Generic parameters
-//!
+//!
//! Each graph type is generic over a handful of parameters. All graphs share 3 common
//! parameters, `N`, `E`, and `Ty`. This is a broad overview of what those are. Each
//! type's documentation will have finer detail on these parameters.
-//!
+//!
//! `N` & `E` are called *weights* in this implementation, and are associated with
//! nodes and edges respectively. They can generally be of arbitrary type, and don't have to
//! be what you might conventionally consider weight-like. For example, using `&str` for `N`
@@ -74,25 +73,25 @@
//! implement [`PartialOrd`](https://doc.rust-lang.org/stable/core/cmp/trait.PartialOrd.html).
//! [`GraphMap`](./graphmap/struct.GraphMap.html) requires node weights that can serve as hash
//! map keys, since that graph type does not create standalone node indices.
-//!
+//!
//! `Ty` controls whether edges are [`Directed`](./petgraph/enum.Directed.html) or
//! [`Undirected`](./petgraph/enum.Unirected.html).
-//!
+//!
//! `Ix` appears on graph types that use indices. It is exposed so you can control
//! the size of node and edge indices, and therefore the memory footprint of your graphs.
//! Allowed values are `u8`, `u16`, `u32`, and `usize`, with `u32` being the default.
-//!
+//!
//! ### Shorthand types
-//!
+//!
//! Each graph type vends a few shorthand type definitions that name some specific
//! generic choices. For example, [`DiGraph<_, _>`](./graph/type.DiGraph.html) is shorthand
//! for [`Graph<_, _, Undirected>`](graph/struct.Graph.html).
//! [`UnMatrix<_, _>`](./matrix_graph/type.UnMatrix.html) is shorthand for
//! [`MatrixGraph<_, _, Undirected>`](./matrix_graph/struct.MatrixGraph.html). Each graph type's
//! module documentation lists the available shorthand types.
-//!
+//!
//! # Crate features
-//!
+//!
//! * **serde-1** -
//! Defaults off. Enables serialization for ``Graph, StableGraph`` using
//! [`serde 1.0`](https://crates.io/crates/serde). May require a more recent version
@@ -122,7 +121,7 @@
#[doc(no_inline)]
pub use crate::graph::Graph;
-pub use crate::Direction::{Outgoing, Incoming};
+pub use crate::Direction::{Incoming, Outgoing};
#[macro_use]
mod macros;
@@ -135,58 +134,38 @@
pub mod data;
pub mod algo;
+mod astar;
+pub mod csr;
+mod dijkstra;
+pub mod dot;
#[cfg(feature = "generate")]
pub mod generate;
+mod graph_impl;
#[cfg(feature = "graphmap")]
pub mod graphmap;
-#[cfg(feature = "matrix_graph")]
-pub mod matrix_graph;
-mod graph_impl;
-pub mod dot;
-pub mod unionfind;
-mod dijkstra;
-mod astar;
-mod simple_paths;
-pub mod csr;
+mod isomorphism;
mod iter_format;
mod iter_utils;
-mod isomorphism;
-mod traits_graph;
-mod util;
+#[cfg(feature = "matrix_graph")]
+pub mod matrix_graph;
#[cfg(feature = "quickcheck")]
mod quickcheck;
#[cfg(feature = "serde-1")]
mod serde_utils;
+mod simple_paths;
+mod traits_graph;
+pub mod unionfind;
+mod util;
pub mod prelude;
/// `Graph<N, E, Ty, Ix>` is a graph datastructure using an adjacency list representation.
pub mod graph {
pub use crate::graph_impl::{
- Edge,
- EdgeIndex,
- EdgeIndices,
- EdgeReference,
- EdgeReferences,
- EdgeWeightsMut,
- Edges,
- Externals,
- Frozen,
- Graph,
- Neighbors,
- Node,
- NodeIndex,
- NodeIndices,
- NodeWeightsMut,
- NodeReferences,
+ edge_index, node_index, DefaultIx, DiGraph, Edge, EdgeIndex, EdgeIndices, EdgeReference,
+ EdgeReferences, EdgeWeightsMut, Edges, Externals, Frozen, Graph, GraphIndex, IndexType,
+ Neighbors, Node, NodeIndex, NodeIndices, NodeReferences, NodeWeightsMut, UnGraph,
WalkNeighbors,
- GraphIndex,
- IndexType,
- edge_index,
- node_index,
- DefaultIx,
- DiGraph,
- UnGraph,
};
}
@@ -197,9 +176,11 @@
($name:ident) => {
impl Clone for $name {
#[inline]
- fn clone(&self) -> Self { *self }
+ fn clone(&self) -> Self {
+ *self
+ }
}
- }
+ };
}
// Index into the NodeIndex and EdgeIndex arrays
@@ -210,7 +191,7 @@
/// An `Outgoing` edge is an outward edge *from* the current node.
Outgoing = 0,
/// An `Incoming` edge is an inbound edge *to* the current node.
- Incoming = 1
+ Incoming = 1,
}
copyclone!(Direction);
@@ -237,12 +218,12 @@
/// Marker type for a directed graph.
#[derive(Copy, Debug)]
-pub enum Directed { }
+pub enum Directed {}
copyclone!(Directed);
/// Marker type for an undirected graph.
#[derive(Copy, Debug)]
-pub enum Undirected { }
+pub enum Undirected {}
copyclone!(Undirected);
/// A graph's edge type determines whether it has directed edges or not.
@@ -252,15 +233,18 @@
impl EdgeType for Directed {
#[inline]
- fn is_directed() -> bool { true }
+ fn is_directed() -> bool {
+ true
+ }
}
impl EdgeType for Undirected {
#[inline]
- fn is_directed() -> bool { false }
+ fn is_directed() -> bool {
+ false
+ }
}
-
/// Convert an element like `(i, j)` or `(i, j, w)` into
/// a triple of source, target, edge weight.
///
@@ -271,7 +255,8 @@
}
impl<Ix, E> IntoWeightedEdge<E> for (Ix, Ix)
- where E: Default
+where
+ E: Default,
{
type NodeId = Ix;
@@ -281,8 +266,7 @@
}
}
-impl<Ix, E> IntoWeightedEdge<E> for (Ix, Ix, E)
-{
+impl<Ix, E> IntoWeightedEdge<E> for (Ix, Ix, E) {
type NodeId = Ix;
fn into_weighted_edge(self) -> (Ix, Ix, E) {
self
@@ -290,7 +274,8 @@
}
impl<'a, Ix, E> IntoWeightedEdge<E> for (Ix, Ix, &'a E)
- where E: Clone
+where
+ E: Clone,
{
type NodeId = Ix;
fn into_weighted_edge(self) -> (Ix, Ix, E) {
@@ -300,7 +285,9 @@
}
impl<'a, Ix, E> IntoWeightedEdge<E> for &'a (Ix, Ix)
- where Ix: Copy, E: Default
+where
+ Ix: Copy,
+ E: Default,
{
type NodeId = Ix;
fn into_weighted_edge(self) -> (Ix, Ix, E) {
@@ -310,7 +297,9 @@
}
impl<'a, Ix, E> IntoWeightedEdge<E> for &'a (Ix, Ix, E)
- where Ix: Copy, E: Clone
+where
+ Ix: Copy,
+ E: Clone,
{
type NodeId = Ix;
fn into_weighted_edge(self) -> (Ix, Ix, E) {
diff --git a/src/macros.rs b/src/macros.rs
index 964372f..0d86ad1 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -1,4 +1,3 @@
-
macro_rules! clone_fields {
($name:ident, $($field:ident),+ $(,)*) => (
fn clone(&self) -> Self {
@@ -10,4 +9,3 @@
}
);
}
-
diff --git a/src/matrix_graph.rs b/src/matrix_graph.rs
index d64747c..0e0c26c 100644
--- a/src/matrix_graph.rs
+++ b/src/matrix_graph.rs
@@ -10,32 +10,14 @@
use fixedbitset::FixedBitSet;
-use crate::{
- Directed,
- EdgeType,
- Outgoing,
- Undirected,
- Direction,
- IntoWeightedEdge,
-};
+use crate::{Directed, Direction, EdgeType, IntoWeightedEdge, Outgoing, Undirected};
use crate::graph::NodeIndex as GraphNodeIndex;
use crate::visit::{
- Data,
- GetAdjacencyMatrix,
- GraphBase,
- GraphProp,
- IntoEdgeReferences,
- IntoEdges,
- IntoNeighbors,
- IntoNeighborsDirected,
- IntoNodeIdentifiers,
- IntoNodeReferences,
- NodeCount,
- NodeIndexable,
- NodeCompactIndexable,
- Visitable,
+ Data, GetAdjacencyMatrix, GraphBase, GraphProp, IntoEdgeReferences, IntoEdges, IntoNeighbors,
+ IntoNeighborsDirected, IntoNodeIdentifiers, IntoNodeReferences, NodeCompactIndexable,
+ NodeCount, NodeIndexable, Visitable,
};
use crate::data::Build;
@@ -48,7 +30,7 @@
type DefaultIx = u16;
/// Node identifier.
-pub type NodeIndex<Ix=DefaultIx> = GraphNodeIndex<Ix>;
+pub type NodeIndex<Ix = DefaultIx> = GraphNodeIndex<Ix>;
mod private {
pub trait Sealed {}
@@ -125,20 +107,29 @@
}
fn as_ref(&self) -> Option<&Self::Wrapped> {
- if !self.is_null() { Some(&self.0) }
- else { None }
+ if !self.is_null() {
+ Some(&self.0)
+ } else {
+ None
+ }
}
fn as_mut(&mut self) -> Option<&mut Self::Wrapped> {
- if !self.is_null() { Some(&mut self.0) }
- else { None }
+ if !self.is_null() {
+ Some(&mut self.0)
+ } else {
+ None
+ }
}
}
impl<T: Zero> Into<Option<T>> for NotZero<T> {
fn into(self) -> Option<T> {
- if !self.is_null() { Some(self.0) }
- else { None }
+ if !self.is_null() {
+ Some(self.0)
+ } else {
+ None
+ }
}
}
@@ -167,7 +158,7 @@
self == &Self::zero()
}
}
- }
+ };
}
macro_rules! not_zero_impls {
@@ -208,7 +199,8 @@
/// matrix is stored. Since the backing array stores edge weights, it is recommended to box large
/// edge weights.
#[derive(Clone)]
-pub struct MatrixGraph<N, E, Ty = Directed, Null: Nullable<Wrapped=E> = Option<E>, Ix = DefaultIx> {
+pub struct MatrixGraph<N, E, Ty = Directed, Null: Nullable<Wrapped = E> = Option<E>, Ix = DefaultIx>
+{
node_adjacencies: Vec<Null>,
node_capacity: usize,
nodes: IdStorage<N>,
@@ -223,7 +215,9 @@
/// A `MatrixGraph` with undirected edges.
pub type UnMatrix<N, E, Null = Option<E>, Ix = DefaultIx> = MatrixGraph<N, E, Undirected, Null, Ix>;
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType>
+ MatrixGraph<N, E, Ty, Null, Ix>
+{
/// Create a new `MatrixGraph` with estimated capacity for nodes.
pub fn with_capacity(node_capacity: usize) -> Self {
let mut m = Self {
@@ -309,7 +303,11 @@
#[inline]
fn extend_capacity_for_node(&mut self, min_node: NodeIndex<Ix>) {
- self.node_capacity = extend_linearized_matrix::<Ty, _>(&mut self.node_adjacencies, self.node_capacity, min_node.index());
+ self.node_capacity = extend_linearized_matrix::<Ty, _>(
+ &mut self.node_adjacencies,
+ self.node_capacity,
+ min_node.index(),
+ );
}
#[inline]
@@ -363,7 +361,9 @@
/// **Panics** if no edge exists between `a` and `b`.
pub fn remove_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> E {
let p = self.to_edge_position(a, b);
- let old_weight = mem::replace(&mut self.node_adjacencies[p], Default::default()).into().unwrap();
+ let old_weight = mem::replace(&mut self.node_adjacencies[p], Default::default())
+ .into()
+ .unwrap();
let old_weight: Option<_> = old_weight.into();
self.nb_edges -= 1;
old_weight.unwrap()
@@ -423,7 +423,11 @@
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is [`NodeIndex<Ix>`](../graph/struct.NodeIndex.html).
pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<Ty, Null, Ix> {
- Neighbors(Edges::on_columns(a.index(), &self.node_adjacencies, self.node_capacity))
+ Neighbors(Edges::on_columns(
+ a.index(),
+ &self.node_adjacencies,
+ self.node_capacity,
+ ))
}
/// Return an iterator of all edges of `a`.
@@ -455,10 +459,11 @@
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
let mut g = Self::default();
g.extend_with_edges(iterable);
@@ -473,10 +478,11 @@
///
/// Nodes are inserted automatically to match the edges.
pub fn extend_with_edges<I>(&mut self, iterable: I)
- where I: IntoIterator,
- I::Item: IntoWeightedEdge<E>,
- <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
- N: Default,
+ where
+ I: IntoIterator,
+ I::Item: IntoWeightedEdge<E>,
+ <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
+ N: Default,
{
for elt in iterable {
let (source, target, weight) = elt.into_weighted_edge();
@@ -490,7 +496,7 @@
}
}
-impl<N, E, Null: Nullable<Wrapped=E>, Ix: IndexType> MatrixGraph<N, E, Directed, Null, Ix> {
+impl<N, E, Null: Nullable<Wrapped = E>, Ix: IndexType> MatrixGraph<N, E, Directed, Null, Ix> {
/// Return an iterator of all neighbors that have an edge between them and
/// `a`, in the specified direction.
/// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
@@ -500,11 +506,19 @@
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is [`NodeIndex<Ix>`](../graph/struct.NodeIndex.html).
- pub fn neighbors_directed(&self, a: NodeIndex<Ix>, d: Direction) -> Neighbors<Directed, Null, Ix> {
+ pub fn neighbors_directed(
+ &self,
+ a: NodeIndex<Ix>,
+ d: Direction,
+ ) -> Neighbors<Directed, Null, Ix> {
if d == Outgoing {
self.neighbors(a)
} else {
- Neighbors(Edges::on_rows(a.index(), &self.node_adjacencies, self.node_capacity))
+ Neighbors(Edges::on_rows(
+ a.index(),
+ &self.node_adjacencies,
+ self.node_capacity,
+ ))
}
}
@@ -537,7 +551,10 @@
impl<'a, Ix: IndexType> NodeIdentifiers<'a, Ix> {
fn new(iter: IdIterator<'a>) -> Self {
- Self { iter, ix: PhantomData }
+ Self {
+ iter,
+ ix: PhantomData,
+ }
}
}
@@ -575,7 +592,9 @@
type Item = (NodeIndex<Ix>, &'a N);
fn next(&mut self) -> Option<Self::Item> {
- self.iter.next().map(|i| (NodeIndex::new(i), &self.nodes[i]))
+ self.iter
+ .next()
+ .map(|i| (NodeIndex::new(i), &self.nodes[i]))
}
}
@@ -597,7 +616,8 @@
impl<'a, Ty: EdgeType, Null: 'a + Nullable, Ix> EdgeReferences<'a, Ty, Null, Ix> {
fn new(node_adjacencies: &'a [Null], node_capacity: usize) -> Self {
EdgeReferences {
- row: 0, column: 0,
+ row: 0,
+ column: 0,
node_adjacencies,
node_capacity,
ty: PhantomData,
@@ -606,7 +626,9 @@
}
}
-impl<'a, Ty: EdgeType, Null: Nullable, Ix: IndexType> Iterator for EdgeReferences<'a, Ty, Null, Ix> {
+impl<'a, Ty: EdgeType, Null: Nullable, Ix: IndexType> Iterator
+ for EdgeReferences<'a, Ty, Null, Ix>
+{
type Item = (NodeIndex<Ix>, NodeIndex<Ix>, &'a Null::Wrapped);
fn next(&mut self) -> Option<Self::Item> {
@@ -621,7 +643,11 @@
// Note that for undirected graphs, we don't want to yield the same edge twice,
// therefore the maximum column length should be the index new after the row index.
self.column += 1;
- let max_column_len = if !Ty::is_directed() { row + 1 } else { self.node_capacity };
+ let max_column_len = if !Ty::is_directed() {
+ row + 1
+ } else {
+ self.node_capacity
+ };
if self.column >= max_column_len {
self.column = 0;
self.row += 1;
@@ -713,14 +739,14 @@
}
match self.iter_direction {
- Rows => self.row += 1,
+ Rows => self.row += 1,
Columns => self.column += 1,
}
let p = to_linearized_matrix_position::<Ty>(row, column, self.node_capacity);
if let Some(e) = self.node_adjacencies[p].as_ref() {
let (a, b) = match self.iter_direction {
- Rows => (column, row),
+ Rows => (column, row),
Columns => (row, column),
};
@@ -740,7 +766,11 @@
}
#[inline]
-fn extend_linearized_matrix<Ty: EdgeType, T: Default>(node_adjacencies: &mut Vec<T>, old_node_capacity: usize, min_node_capacity: usize) -> usize {
+fn extend_linearized_matrix<Ty: EdgeType, T: Default>(
+ node_adjacencies: &mut Vec<T>,
+ old_node_capacity: usize,
+ min_node_capacity: usize,
+) -> usize {
if Ty::is_directed() {
extend_flat_square_matrix(node_adjacencies, old_node_capacity, min_node_capacity)
} else {
@@ -754,7 +784,11 @@
}
#[inline]
-fn extend_flat_square_matrix<T: Default>(node_adjacencies: &mut Vec<T>, old_node_capacity: usize, min_node_capacity: usize) -> usize {
+fn extend_flat_square_matrix<T: Default>(
+ node_adjacencies: &mut Vec<T>,
+ old_node_capacity: usize,
+ min_node_capacity: usize,
+) -> usize {
let min_node_capacity = (min_node_capacity + 1).next_power_of_two();
// Optimization: when resizing the matrix this way we skip the first few grows to make
@@ -782,12 +816,19 @@
#[inline]
fn to_lower_triangular_matrix_position(row: usize, column: usize) -> usize {
- let (row, column) = if row > column { (row, column) } else { (column, row) };
+ let (row, column) = if row > column {
+ (row, column)
+ } else {
+ (column, row)
+ };
(row * (row + 1)) / 2 + column
}
#[inline]
-fn extend_lower_triangular_matrix<T: Default>(node_adjacencies: &mut Vec<T>, new_node_capacity: usize) -> usize {
+fn extend_lower_triangular_matrix<T: Default>(
+ node_adjacencies: &mut Vec<T>,
+ new_node_capacity: usize,
+) -> usize {
let max_pos = to_lower_triangular_matrix_position(new_node_capacity, new_node_capacity);
ensure_len(node_adjacencies, max_pos + 1);
new_node_capacity + 1
@@ -915,7 +956,9 @@
}
/// Create a new empty `MatrixGraph`.
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Default for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> Default
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn default() -> Self {
Self::with_capacity(0)
}
@@ -944,7 +987,9 @@
/// Index the `MatrixGraph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Index<NodeIndex<Ix>> for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> Index<NodeIndex<Ix>>
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type Output = N;
fn index(&self, ax: NodeIndex<Ix>) -> &N {
@@ -955,13 +1000,17 @@
/// Index the `MatrixGraph` by `NodeIndex` to access node weights.
///
/// **Panics** if the node doesn't exist.
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IndexMut<NodeIndex<Ix>> for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IndexMut<NodeIndex<Ix>>
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn index_mut(&mut self, ax: NodeIndex<Ix>) -> &mut N {
self.node_weight_mut(ax)
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> NodeCount for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> NodeCount
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn node_count(&self) -> usize {
MatrixGraph::node_count(self)
}
@@ -972,7 +1021,9 @@
/// Also available with indexing syntax: `&graph[e]`.
///
/// **Panics** if no edge exists between `a` and `b`.
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Index<(NodeIndex<Ix>, NodeIndex<Ix>)> for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType>
+ Index<(NodeIndex<Ix>, NodeIndex<Ix>)> for MatrixGraph<N, E, Ty, Null, Ix>
+{
type Output = E;
fn index(&self, (ax, bx): (NodeIndex<Ix>, NodeIndex<Ix>)) -> &E {
@@ -985,24 +1036,29 @@
/// Also available with indexing syntax: `&mut graph[e]`.
///
/// **Panics** if no edge exists between `a` and `b`.
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IndexMut<(NodeIndex<Ix>, NodeIndex<Ix>)> for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType>
+ IndexMut<(NodeIndex<Ix>, NodeIndex<Ix>)> for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn index_mut(&mut self, (ax, bx): (NodeIndex<Ix>, NodeIndex<Ix>)) -> &mut E {
self.edge_weight_mut(ax, bx)
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> GetAdjacencyMatrix for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> GetAdjacencyMatrix
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type AdjMatrix = ();
- fn adjacency_matrix(&self) -> Self::AdjMatrix {
- }
+ fn adjacency_matrix(&self) -> Self::AdjMatrix {}
fn is_adjacent(&self, _: &Self::AdjMatrix, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
MatrixGraph::has_edge(self, a, b)
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Visitable for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> Visitable
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type Map = FixedBitSet;
fn visit_map(&self) -> FixedBitSet {
@@ -1015,21 +1071,29 @@
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> GraphBase for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> GraphBase
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type NodeId = NodeIndex<Ix>;
type EdgeId = (NodeIndex<Ix>, NodeIndex<Ix>);
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> GraphProp for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> GraphProp
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type EdgeType = Ty;
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Data for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> Data
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
type NodeWeight = N;
type EdgeWeight = E;
}
-impl<'a, N, E: 'a, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoNodeIdentifiers for &'a MatrixGraph<N, E, Ty, Null, Ix> {
+impl<'a, N, E: 'a, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoNodeIdentifiers
+ for &'a MatrixGraph<N, E, Ty, Null, Ix>
+{
type NodeIdentifiers = NodeIdentifiers<'a, Ix>;
fn node_identifiers(self) -> Self::NodeIdentifiers {
@@ -1037,7 +1101,9 @@
}
}
-impl<'a, N, E: 'a, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoNeighbors for &'a MatrixGraph<N, E, Ty, Null, Ix> {
+impl<'a, N, E: 'a, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoNeighbors
+ for &'a MatrixGraph<N, E, Ty, Null, Ix>
+{
type Neighbors = Neighbors<'a, Ty, Null, Ix>;
fn neighbors(self, a: NodeIndex<Ix>) -> Self::Neighbors {
@@ -1045,7 +1111,9 @@
}
}
-impl<'a, N, E: 'a, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoNeighborsDirected for &'a MatrixGraph<N, E, Directed, Null, Ix> {
+impl<'a, N, E: 'a, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoNeighborsDirected
+ for &'a MatrixGraph<N, E, Directed, Null, Ix>
+{
type NeighborsDirected = Neighbors<'a, Directed, Null, Ix>;
fn neighbors_directed(self, a: NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected {
@@ -1053,7 +1121,9 @@
}
}
-impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoNodeReferences for &'a MatrixGraph<N, E, Ty, Null, Ix> {
+impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoNodeReferences
+ for &'a MatrixGraph<N, E, Ty, Null, Ix>
+{
type NodeRef = (NodeIndex<Ix>, &'a N);
type NodeReferences = NodeReferences<'a, N, Ix>;
fn node_references(self) -> Self::NodeReferences {
@@ -1061,7 +1131,9 @@
}
}
-impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoEdgeReferences for &'a MatrixGraph<N, E, Ty, Null, Ix> {
+impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoEdgeReferences
+ for &'a MatrixGraph<N, E, Ty, Null, Ix>
+{
type EdgeRef = (NodeIndex<Ix>, NodeIndex<Ix>, &'a E);
type EdgeReferences = EdgeReferences<'a, Ty, Null, Ix>;
fn edge_references(self) -> Self::EdgeReferences {
@@ -1069,14 +1141,18 @@
}
}
-impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> IntoEdges for &'a MatrixGraph<N, E, Ty, Null, Ix> {
+impl<'a, N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> IntoEdges
+ for &'a MatrixGraph<N, E, Ty, Null, Ix>
+{
type Edges = Edges<'a, Ty, Null, Ix>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
MatrixGraph::edges(self, a)
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> NodeIndexable for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> NodeIndexable
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn node_bound(&self) -> usize {
self.node_count()
}
@@ -1090,15 +1166,24 @@
}
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> NodeCompactIndexable for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> NodeCompactIndexable
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
}
-impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped=E>, Ix: IndexType> Build for MatrixGraph<N, E, Ty, Null, Ix> {
+impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType> Build
+ for MatrixGraph<N, E, Ty, Null, Ix>
+{
fn add_node(&mut self, weight: Self::NodeWeight) -> Self::NodeId {
self.add_node(weight)
}
- fn add_edge(&mut self, a: Self::NodeId, b: Self::NodeId, weight: Self::EdgeWeight) -> Option<Self::EdgeId> {
+ fn add_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Option<Self::EdgeId> {
if !self.has_edge(a, b) {
MatrixGraph::update_edge(self, a, b, weight);
Some((a, b))
@@ -1107,7 +1192,12 @@
}
}
- fn update_edge(&mut self, a: Self::NodeId, b: Self::NodeId, weight: Self::EdgeWeight) -> Self::EdgeId {
+ fn update_edge(
+ &mut self,
+ a: Self::NodeId,
+ b: Self::NodeId,
+ weight: Self::EdgeWeight,
+ ) -> Self::EdgeId {
MatrixGraph::update_edge(self, a, b, weight);
(a, b)
}
@@ -1116,7 +1206,7 @@
#[cfg(test)]
mod tests {
use super::*;
- use crate::{Outgoing, Incoming};
+ use crate::{Incoming, Outgoing};
#[test]
fn test_new() {
@@ -1206,7 +1296,8 @@
}
impl<It, T> IntoVec<T> for It
- where It: Iterator<Item=T>,
+ where
+ It: Iterator<Item = T>,
{
fn into_vec(self) -> Vec<T> {
self.collect()
@@ -1281,8 +1372,9 @@
}
impl<It, T> IntoSortedVec<T> for It
- where It: Iterator<Item=T>,
- T: Ord,
+ where
+ It: Iterator<Item = T>,
+ T: Ord,
{
fn into_sorted_vec(self) -> Vec<T> {
let mut v: Vec<T> = self.collect();
@@ -1401,9 +1493,13 @@
#[test]
fn test_edges_directed() {
let g: MatrixGraph<char, bool> = MatrixGraph::from_edges(&[
- (0, 5), (0, 2), (0, 3), (0, 1),
+ (0, 5),
+ (0, 2),
+ (0, 3),
+ (0, 1),
(1, 3),
- (2, 3), (2, 4),
+ (2, 3),
+ (2, 4),
(4, 0),
(6, 6),
]);
@@ -1428,9 +1524,13 @@
#[test]
fn test_edges_undirected() {
let g: UnMatrix<char, bool> = UnMatrix::from_edges(&[
- (0, 5), (0, 2), (0, 3), (0, 1),
+ (0, 5),
+ (0, 2),
+ (0, 3),
+ (0, 1),
(1, 3),
- (2, 3), (2, 4),
+ (2, 3),
+ (2, 4),
(4, 0),
(6, 6),
]);
@@ -1459,9 +1559,13 @@
#[test]
fn test_edge_references() {
let g: MatrixGraph<char, bool> = MatrixGraph::from_edges(&[
- (0, 5), (0, 2), (0, 3), (0, 1),
+ (0, 5),
+ (0, 2),
+ (0, 3),
+ (0, 1),
(1, 3),
- (2, 3), (2, 4),
+ (2, 3),
+ (2, 4),
(4, 0),
(6, 6),
]);
@@ -1472,9 +1576,13 @@
#[test]
fn test_edge_references_undirected() {
let g: UnMatrix<char, bool> = UnMatrix::from_edges(&[
- (0, 5), (0, 2), (0, 3), (0, 1),
+ (0, 5),
+ (0, 2),
+ (0, 3),
+ (0, 1),
(1, 3),
- (2, 3), (2, 4),
+ (2, 3),
+ (2, 4),
(4, 0),
(6, 6),
]);
diff --git a/src/prelude.rs b/src/prelude.rs
index d35161e..f50b338 100644
--- a/src/prelude.rs
+++ b/src/prelude.rs
@@ -1,4 +1,3 @@
-
//! Commonly used items.
//!
//! ```
@@ -6,43 +5,17 @@
//! ```
#[doc(no_inline)]
-pub use crate::graph::{
- Graph,
- NodeIndex,
- EdgeIndex,
- DiGraph,
- UnGraph,
-};
+pub use crate::graph::{DiGraph, EdgeIndex, Graph, NodeIndex, UnGraph};
#[cfg(feature = "graphmap")]
#[doc(no_inline)]
-pub use crate::graphmap::{
- GraphMap,
- DiGraphMap,
- UnGraphMap,
-};
+pub use crate::graphmap::{DiGraphMap, GraphMap, UnGraphMap};
#[doc(no_inline)]
#[cfg(feature = "stable_graph")]
-pub use crate::stable_graph::{
- StableGraph,
- StableDiGraph,
- StableUnGraph,
-};
+pub use crate::stable_graph::{StableDiGraph, StableGraph, StableUnGraph};
#[doc(no_inline)]
-pub use crate::visit::{
- Bfs,
- Dfs,
- DfsPostOrder,
-};
+pub use crate::visit::{Bfs, Dfs, DfsPostOrder};
#[doc(no_inline)]
-pub use crate::{
- Direction,
- Incoming,
- Outgoing,
- Directed,
- Undirected,
-};
+pub use crate::{Directed, Direction, Incoming, Outgoing, Undirected};
#[doc(no_inline)]
-pub use crate::visit::{
- EdgeRef,
-};
+pub use crate::visit::EdgeRef;
diff --git a/src/quickcheck.rs b/src/quickcheck.rs
index 7ce6cad..0c7ce6b 100644
--- a/src/quickcheck.rs
+++ b/src/quickcheck.rs
@@ -1,22 +1,13 @@
extern crate quickcheck;
-use self::quickcheck::{Gen, Arbitrary};
+use self::quickcheck::{Arbitrary, Gen};
-use crate::{
- Graph,
- EdgeType,
-};
-use crate::graph::{
- IndexType,
- node_index,
-};
+use crate::graph::{node_index, IndexType};
#[cfg(feature = "stable_graph")]
use crate::stable_graph::StableGraph;
+use crate::{EdgeType, Graph};
#[cfg(feature = "graphmap")]
-use crate::graphmap::{
- GraphMap,
- NodeTrait,
-};
+use crate::graphmap::{GraphMap, NodeTrait};
use crate::visit::NodeIndexable;
/// Return a random float in the range [0, 1.)
@@ -38,10 +29,11 @@
///
/// Requires crate feature `"quickcheck"`
impl<N, E, Ty, Ix> Arbitrary for Graph<N, E, Ty, Ix>
- where N: Arbitrary,
- E: Arbitrary,
- Ty: EdgeType + Send + 'static,
- Ix: IndexType + Send,
+where
+ N: Arbitrary,
+ E: Arbitrary,
+ Ty: EdgeType + Send + 'static,
+ Ix: IndexType + Send,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let nodes = usize::arbitrary(g);
@@ -71,17 +63,18 @@
// shrink the graph by splitting it in two by a very
// simple algorithm, just even and odd node indices
- fn shrink(&self) -> Box<dyn Iterator<Item=Self>> {
+ fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let self_ = self.clone();
Box::new((0..2).filter_map(move |x| {
- let gr = self_.filter_map(|i, w| {
- if i.index() % 2 == x {
- Some(w.clone())
- } else {
- None
- }
- },
- |_, w| Some(w.clone())
+ let gr = self_.filter_map(
+ |i, w| {
+ if i.index() % 2 == x {
+ Some(w.clone())
+ } else {
+ None
+ }
+ },
+ |_, w| Some(w.clone()),
);
// make sure we shrink
if gr.node_count() < self_.node_count() {
@@ -104,10 +97,11 @@
///
/// Requires crate features `"quickcheck"` and `"stable_graph"`
impl<N, E, Ty, Ix> Arbitrary for StableGraph<N, E, Ty, Ix>
- where N: Arbitrary,
- E: Arbitrary,
- Ty: EdgeType + Send + 'static,
- Ix: IndexType + Send,
+where
+ N: Arbitrary,
+ E: Arbitrary,
+ Ty: EdgeType + Send + 'static,
+ Ix: IndexType + Send,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let nodes = usize::arbitrary(g);
@@ -149,17 +143,18 @@
// shrink the graph by splitting it in two by a very
// simple algorithm, just even and odd node indices
- fn shrink(&self) -> Box<dyn Iterator<Item=Self>> {
+ fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let self_ = self.clone();
Box::new((0..2).filter_map(move |x| {
- let gr = self_.filter_map(|i, w| {
- if i.index() % 2 == x {
- Some(w.clone())
- } else {
- None
- }
- },
- |_, w| Some(w.clone())
+ let gr = self_.filter_map(
+ |i, w| {
+ if i.index() % 2 == x {
+ Some(w.clone())
+ } else {
+ None
+ }
+ },
+ |_, w| Some(w.clone()),
);
// make sure we shrink
if gr.node_count() < self_.node_count() {
@@ -182,9 +177,10 @@
/// Requires crate features `"quickcheck"` and `"graphmap"`
#[cfg(feature = "graphmap")]
impl<N, E, Ty> Arbitrary for GraphMap<N, E, Ty>
- where N: NodeTrait + Arbitrary,
- E: Arbitrary,
- Ty: EdgeType + Clone + Send + 'static,
+where
+ N: NodeTrait + Arbitrary,
+ E: Arbitrary,
+ Ty: EdgeType + Clone + Send + 'static,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let nodes = usize::arbitrary(g);
@@ -203,7 +199,11 @@
gr.add_node(node);
}
for (index, &i) in nodes.iter().enumerate() {
- let js = if Ty::is_directed() { &nodes[..] } else { &nodes[index..] };
+ let js = if Ty::is_directed() {
+ &nodes[..]
+ } else {
+ &nodes[index..]
+ };
for &j in js {
let p: f64 = random_01(g);
if p <= edge_prob {
diff --git a/src/scored.rs b/src/scored.rs
index cb19147..a4f88a9 100644
--- a/src/scored.rs
+++ b/src/scored.rs
@@ -50,4 +50,3 @@
}
}
}
-
diff --git a/src/serde_utils.rs b/src/serde_utils.rs
index fcda128..f127f33 100644
--- a/src/serde_utils.rs
+++ b/src/serde_utils.rs
@@ -1,7 +1,7 @@
+use serde::de::{Deserialize, Error, SeqAccess, Visitor};
+use serde::ser::{Serialize, SerializeSeq, Serializer};
use std::fmt;
use std::marker::PhantomData;
-use serde::de::{Error, Visitor, Deserialize, SeqAccess};
-use serde::ser::{Serializer, SerializeSeq, Serialize};
/// Map to serializeable representation
pub trait IntoSerializable {
@@ -10,25 +10,27 @@
}
/// Map from deserialized representation
-pub trait FromDeserialized : Sized {
+pub trait FromDeserialized: Sized {
type Input;
- fn from_deserialized<E>(input: Self::Input) -> Result<Self, E> where E: Error;
+ fn from_deserialized<E>(input: Self::Input) -> Result<Self, E>
+ where
+ E: Error;
}
-
-
/// Serde combinator. A sequence visitor that maps deserialized elements
/// lazily; the visitor can also emit new errors if the elements have errors.
pub struct MappedSequenceVisitor<T, R, F>
- where F: Fn(T) -> Result<R, &'static str>
+where
+ F: Fn(T) -> Result<R, &'static str>,
{
f: F,
- marker: PhantomData<fn() -> T>
+ marker: PhantomData<fn() -> T>,
}
-impl<'de, F, T, R> MappedSequenceVisitor<T, R, F>
- where T: Deserialize<'de>,
- F: Fn(T) -> Result<R, &'static str>,
+impl<'de, F, T, R> MappedSequenceVisitor<T, R, F>
+where
+ T: Deserialize<'de>,
+ F: Fn(T) -> Result<R, &'static str>,
{
pub fn new(f: F) -> Self {
MappedSequenceVisitor {
@@ -38,9 +40,10 @@
}
}
-impl<'de, F, T, R> Visitor<'de> for MappedSequenceVisitor<T, R, F>
- where T: Deserialize<'de>,
- F: Fn(T) -> Result<R, &'static str>,
+impl<'de, F, T, R> Visitor<'de> for MappedSequenceVisitor<T, R, F>
+where
+ T: Deserialize<'de>,
+ F: Fn(T) -> Result<R, &'static str>,
{
type Value = Vec<R>;
@@ -48,7 +51,8 @@
write!(formatter, "a sequence")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
- where A: SeqAccess<'de>,
+ where
+ A: SeqAccess<'de>,
{
let mut v = Vec::new();
while let Some(elem) = seq.next_element()? {
@@ -61,12 +65,11 @@
}
}
-
-pub trait CollectSeqWithLength : Serializer {
- fn collect_seq_with_length<I>(self, length: usize, iterable: I)
- -> Result<Self::Ok, Self::Error>
- where I: IntoIterator,
- I::Item: Serialize
+pub trait CollectSeqWithLength: Serializer {
+ fn collect_seq_with_length<I>(self, length: usize, iterable: I) -> Result<Self::Ok, Self::Error>
+ where
+ I: IntoIterator,
+ I::Item: Serialize,
{
let mut count = 0;
let mut seq = self.serialize_seq(Some(length))?;
@@ -78,15 +81,15 @@
seq.end()
}
- fn collect_seq_exact<I>(self, iterable: I)
- -> Result<Self::Ok, Self::Error>
- where I: IntoIterator,
- I::Item: Serialize,
- I::IntoIter: ExactSizeIterator,
+ fn collect_seq_exact<I>(self, iterable: I) -> Result<Self::Ok, Self::Error>
+ where
+ I: IntoIterator,
+ I::Item: Serialize,
+ I::IntoIter: ExactSizeIterator,
{
let iter = iterable.into_iter();
self.collect_seq_with_length(iter.len(), iter)
}
}
-impl<S> CollectSeqWithLength for S where S: Serializer { }
+impl<S> CollectSeqWithLength for S where S: Serializer {}
diff --git a/src/simple_paths.rs b/src/simple_paths.rs
index 7d698df..76be84e 100644
--- a/src/simple_paths.rs
+++ b/src/simple_paths.rs
@@ -6,26 +6,26 @@
use indexmap::IndexSet;
use crate::{
+ visit::{IntoNeighborsDirected, NodeCount},
Direction::Outgoing,
- visit::{
- IntoNeighborsDirected,
- NodeCount,
- },
};
/// Returns iterator that produces all simple paths from `from` node to `to`, which contains at least `min_intermidiate_nodes` nodes
/// and at most `max_intermidiate_nodes`, if given, limited by graph's order otherwise
/// Simple path is path without repetitions
/// Algorithm is adopted from https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.simple_paths.all_simple_paths.html
-pub fn all_simple_paths<TargetColl, G>(graph: G,
- from: G::NodeId,
- to: G::NodeId,
- min_intermidiate_nodes: usize,
- max_intermidiate_nodes: Option<usize>) -> impl Iterator<Item=TargetColl>
- where G: NodeCount,
- G: IntoNeighborsDirected,
- G::NodeId: Eq + Hash,
- TargetColl: FromIterator<G::NodeId>
+pub fn all_simple_paths<TargetColl, G>(
+ graph: G,
+ from: G::NodeId,
+ to: G::NodeId,
+ min_intermidiate_nodes: usize,
+ max_intermidiate_nodes: Option<usize>,
+) -> impl Iterator<Item = TargetColl>
+where
+ G: NodeCount,
+ G: IntoNeighborsDirected,
+ G::NodeId: Eq + Hash,
+ TargetColl: FromIterator<G::NodeId>,
{
// how many nodes are allowed in simple path up to target node
// it is min/max allowed path length minus one, because it is more appropriate when implementing lookahead
@@ -50,7 +50,11 @@
if visited.len() < max_length {
if child == to {
if visited.len() >= min_length {
- let path = visited.iter().cloned().chain(Some(to)).collect::<TargetColl>();
+ let path = visited
+ .iter()
+ .cloned()
+ .chain(Some(to))
+ .collect::<TargetColl>();
return Some(path);
}
} else if !visited.contains(&child) {
@@ -59,7 +63,11 @@
}
} else {
if (child == to || children.any(|v| v == to)) && visited.len() >= min_length {
- let path = visited.iter().cloned().chain(Some(to)).collect::<TargetColl>();
+ let path = visited
+ .iter()
+ .cloned()
+ .chain(Some(to))
+ .collect::<TargetColl>();
return Some(path);
}
stack.pop();
@@ -76,17 +84,11 @@
#[cfg(test)]
mod test {
- use std::{
- collections::HashSet,
- iter::FromIterator,
- };
+ use std::{collections::HashSet, iter::FromIterator};
use itertools::assert_equal;
- use crate::{
- dot::Dot,
- prelude::DiGraph,
- };
+ use crate::{dot::Dot, prelude::DiGraph};
use super::all_simple_paths;
@@ -105,7 +107,7 @@
(4, 2),
(4, 5),
(5, 2),
- (5, 3)
+ (5, 3),
]);
let expexted_simple_paths_0_to_5 = vec![
@@ -120,27 +122,27 @@
];
println!("{}", Dot::new(&graph));
- let actual_simple_paths_0_to_5: HashSet<Vec<_>> = all_simple_paths(&graph, 0u32.into(), 5u32.into(), 0, None)
- .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
- .collect();
+ let actual_simple_paths_0_to_5: HashSet<Vec<_>> =
+ all_simple_paths(&graph, 0u32.into(), 5u32.into(), 0, None)
+ .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
+ .collect();
assert_eq!(actual_simple_paths_0_to_5.len(), 8);
- assert_eq!(HashSet::from_iter(expexted_simple_paths_0_to_5), actual_simple_paths_0_to_5);
+ assert_eq!(
+ HashSet::from_iter(expexted_simple_paths_0_to_5),
+ actual_simple_paths_0_to_5
+ );
}
#[test]
fn test_one_simple_path() {
- let graph = DiGraph::<i32, i32, _>::from_edges(&[
- (0, 1),
- (2, 1)
- ]);
+ let graph = DiGraph::<i32, i32, _>::from_edges(&[(0, 1), (2, 1)]);
- let expexted_simple_paths_0_to_1 = &[
- vec![0usize, 1],
- ];
+ let expexted_simple_paths_0_to_1 = &[vec![0usize, 1]];
println!("{}", Dot::new(&graph));
- let actual_simple_paths_0_to_1: Vec<Vec<_>> = all_simple_paths(&graph, 0u32.into(), 1u32.into(), 0, None)
- .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
- .collect();
+ let actual_simple_paths_0_to_1: Vec<Vec<_>> =
+ all_simple_paths(&graph, 0u32.into(), 1u32.into(), 0, None)
+ .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
+ .collect();
assert_eq!(actual_simple_paths_0_to_1.len(), 1);
assert_equal(expexted_simple_paths_0_to_1, &actual_simple_paths_0_to_1);
@@ -148,15 +150,13 @@
#[test]
fn test_no_simple_paths() {
- let graph = DiGraph::<i32, i32, _>::from_edges(&[
- (0, 1),
- (2, 1)
- ]);
+ let graph = DiGraph::<i32, i32, _>::from_edges(&[(0, 1), (2, 1)]);
println!("{}", Dot::new(&graph));
- let actual_simple_paths_0_to_2: Vec<Vec<_>> = all_simple_paths(&graph, 0u32.into(), 2u32.into(), 0, None)
- .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
- .collect();
+ let actual_simple_paths_0_to_2: Vec<Vec<_>> =
+ all_simple_paths(&graph, 0u32.into(), 2u32.into(), 0, None)
+ .map(|v: Vec<_>| v.into_iter().map(|i| i.index()).collect())
+ .collect();
assert_eq!(actual_simple_paths_0_to_2.len(), 0);
}
diff --git a/src/traits_graph.rs b/src/traits_graph.rs
index 1eef177..272e9e7 100644
--- a/src/traits_graph.rs
+++ b/src/traits_graph.rs
@@ -1,33 +1,26 @@
-
use fixedbitset::FixedBitSet;
-use super::{
- EdgeType,
-};
+use super::EdgeType;
-use super::graph::{
- Graph,
- IndexType,
- NodeIndex,
-};
+use super::graph::{Graph, IndexType, NodeIndex};
#[cfg(feature = "stable_graph")]
use crate::stable_graph::StableGraph;
-#[cfg(feature = "stable_graph")]
-use crate::visit::{NodeIndexable, IntoEdgeReferences};
use crate::visit::EdgeRef;
+#[cfg(feature = "stable_graph")]
+use crate::visit::{IntoEdgeReferences, NodeIndexable};
use super::visit::GetAdjacencyMatrix;
/// The adjacency matrix for **Graph** is a bitmap that's computed by
/// `.adjacency_matrix()`.
-impl<N, E, Ty, Ix> GetAdjacencyMatrix for Graph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> GetAdjacencyMatrix for Graph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
type AdjMatrix = FixedBitSet;
- fn adjacency_matrix(&self) -> FixedBitSet
- {
+ fn adjacency_matrix(&self) -> FixedBitSet {
let n = self.node_count();
let mut matrix = FixedBitSet::with_capacity(n * n);
for edge in self.edge_references() {
@@ -41,26 +34,24 @@
matrix
}
- fn is_adjacent(&self, matrix: &FixedBitSet, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool
- {
+ fn is_adjacent(&self, matrix: &FixedBitSet, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
let n = self.node_count();
let index = n * a.index() + b.index();
matrix.contains(index)
}
}
-
#[cfg(feature = "stable_graph")]
/// The adjacency matrix for **Graph** is a bitmap that's computed by
/// `.adjacency_matrix()`.
-impl<N, E, Ty, Ix> GetAdjacencyMatrix for StableGraph<N, E, Ty, Ix> where
+impl<N, E, Ty, Ix> GetAdjacencyMatrix for StableGraph<N, E, Ty, Ix>
+where
Ty: EdgeType,
Ix: IndexType,
{
type AdjMatrix = FixedBitSet;
- fn adjacency_matrix(&self) -> FixedBitSet
- {
+ fn adjacency_matrix(&self) -> FixedBitSet {
let n = self.node_bound();
let mut matrix = FixedBitSet::with_capacity(n * n);
for edge in self.edge_references() {
@@ -74,12 +65,9 @@
matrix
}
- fn is_adjacent(&self, matrix: &FixedBitSet, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool
- {
+ fn is_adjacent(&self, matrix: &FixedBitSet, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
let n = self.node_count();
let index = n * a.index() + b.index();
matrix.contains(index)
}
}
-
-
diff --git a/src/unionfind.rs b/src/unionfind.rs
index e64d8b6..2f6b12c 100644
--- a/src/unionfind.rs
+++ b/src/unionfind.rs
@@ -1,7 +1,7 @@
//! `UnionFind<K>` is a disjoint-set data structure.
-use std::cmp::Ordering;
use super::graph::IndexType;
+use std::cmp::Ordering;
/// `UnionFind<K>` is a disjoint-set data structure. It tracks set membership of *n* elements
/// indexed from *0* to *n - 1*. The scalar type is `K` which must be an unsigned integer type.
@@ -13,8 +13,7 @@
/// “The amortized time per operation is **O(α(n))** where **α(n)** is the
/// inverse of **f(x) = A(x, x)** with **A** being the extremely fast-growing Ackermann function.”
#[derive(Debug, Clone)]
-pub struct UnionFind<K>
-{
+pub struct UnionFind<K> {
// For element at index *i*, store the index of its parent; the representative itself
// stores its own index. This forms equivalence classes which are the disjoint sets, each
// with a unique representative.
@@ -28,36 +27,33 @@
}
#[inline]
-unsafe fn get_unchecked<K>(xs: &[K], index: usize) -> &K
-{
+unsafe fn get_unchecked<K>(xs: &[K], index: usize) -> &K {
debug_assert!(index < xs.len());
xs.get_unchecked(index)
}
#[inline]
-unsafe fn get_unchecked_mut<K>(xs: &mut [K], index: usize) -> &mut K
-{
+unsafe fn get_unchecked_mut<K>(xs: &mut [K], index: usize) -> &mut K {
debug_assert!(index < xs.len());
xs.get_unchecked_mut(index)
}
impl<K> UnionFind<K>
- where K: IndexType
+where
+ K: IndexType,
{
/// Create a new `UnionFind` of `n` disjoint sets.
- pub fn new(n: usize) -> Self
- {
+ pub fn new(n: usize) -> Self {
let rank = vec![0; n];
let parent = (0..n).map(K::new).collect::<Vec<K>>();
- UnionFind{parent, rank}
+ UnionFind { parent, rank }
}
/// Return the representative for `x`.
///
/// **Panics** if `x` is out of bounds.
- pub fn find(&self, x: K) -> K
- {
+ pub fn find(&self, x: K) -> K {
assert!(x.index() < self.parent.len());
unsafe {
let mut x = x;
@@ -65,7 +61,7 @@
// Use unchecked indexing because we can trust the internal set ids.
let xparent = *get_unchecked(&self.parent, x.index());
if xparent == x {
- break
+ break;
}
x = xparent;
}
@@ -79,16 +75,12 @@
/// datastructure in the process and quicken future lookups.
///
/// **Panics** if `x` is out of bounds.
- pub fn find_mut(&mut self, x: K) -> K
- {
+ pub fn find_mut(&mut self, x: K) -> K {
assert!(x.index() < self.parent.len());
- unsafe {
- self.find_mut_recursive(x)
- }
+ unsafe { self.find_mut_recursive(x) }
}
- unsafe fn find_mut_recursive(&mut self, mut x: K) -> K
- {
+ unsafe fn find_mut_recursive(&mut self, mut x: K) -> K {
let mut parent = *get_unchecked(&self.parent, x.index());
while parent != x {
let grandparent = *get_unchecked(&self.parent, parent.index());
@@ -105,14 +97,12 @@
self.find(x) == self.find(y)
}
-
/// Unify the two sets containing `x` and `y`.
///
/// Return `false` if the sets were already the same, `true` if they were unified.
///
/// **Panics** if `x` or `y` is out of bounds.
- pub fn union(&mut self, x: K, y: K) -> bool
- {
+ pub fn union(&mut self, x: K, y: K) -> bool {
if x == y {
return false;
}
@@ -142,8 +132,7 @@
}
/// Return a vector mapping each element to its representative.
- pub fn into_labeling(mut self) -> Vec<K>
- {
+ pub fn into_labeling(mut self) -> Vec<K> {
// write in the labeling of each element
unsafe {
for ix in 0..self.parent.len() {
diff --git a/src/util.rs b/src/util.rs
index 7cc3445..f4d28d9 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -1,23 +1,25 @@
-
use std::iter;
pub fn enumerate<I>(iterable: I) -> iter::Enumerate<I::IntoIter>
- where I: IntoIterator
+where
+ I: IntoIterator,
{
iterable.into_iter().enumerate()
}
#[cfg(feature = "serde-1")]
pub fn rev<I>(iterable: I) -> iter::Rev<I::IntoIter>
- where I: IntoIterator,
- I::IntoIter: DoubleEndedIterator
+where
+ I: IntoIterator,
+ I::IntoIter: DoubleEndedIterator,
{
iterable.into_iter().rev()
}
pub fn zip<I, J>(i: I, j: J) -> iter::Zip<I::IntoIter, J::IntoIter>
- where I: IntoIterator,
- J: IntoIterator
+where
+ I: IntoIterator,
+ J: IntoIterator,
{
i.into_iter().zip(j)
}
diff --git a/src/visit/dfsvisit.rs b/src/visit/dfsvisit.rs
index 5ac93c7..3acaf77 100644
--- a/src/visit/dfsvisit.rs
+++ b/src/visit/dfsvisit.rs
@@ -1,5 +1,3 @@
-
-
use crate::visit::IntoNeighbors;
use crate::visit::{VisitMap, Visitable};
@@ -29,13 +27,15 @@
macro_rules! try_control {
($e:expr, $p:stmt) => {
match $e {
- x => if x.should_break() {
- return x;
- } else if x.should_prune() {
- $p
+ x => {
+ if x.should_break() {
+ return x;
+ } else if x.should_prune() {
+ $p
+ }
}
}
- }
+ };
}
/// Control flow for `depth_first_search` callbacks.
@@ -53,7 +53,9 @@
}
impl<B> Control<B> {
- pub fn breaking() -> Control<()> { Control::Break(()) }
+ pub fn breaking() -> Control<()> {
+ Control::Break(())
+ }
/// Get the value in `Control::Break(_)`, if present.
pub fn break_value(self) -> Option<B> {
match self {
@@ -73,17 +75,27 @@
}
impl ControlFlow for () {
- fn continuing() { }
+ fn continuing() {}
#[inline]
- fn should_break(&self) -> bool { false }
+ fn should_break(&self) -> bool {
+ false
+ }
#[inline]
- fn should_prune(&self) -> bool { false }
+ fn should_prune(&self) -> bool {
+ false
+ }
}
impl<B> ControlFlow for Control<B> {
- fn continuing() -> Self { Control::Continue }
+ fn continuing() -> Self {
+ Control::Continue
+ }
fn should_break(&self) -> bool {
- if let Control::Break(_) = *self { true } else { false }
+ if let Control::Break(_) = *self {
+ true
+ } else {
+ false
+ }
}
fn should_prune(&self) -> bool {
match *self {
@@ -94,18 +106,30 @@
}
impl<C: ControlFlow, E> ControlFlow for Result<C, E> {
- fn continuing() -> Self { Ok(C::continuing()) }
+ fn continuing() -> Self {
+ Ok(C::continuing())
+ }
fn should_break(&self) -> bool {
- if let Ok(ref c) = *self { c.should_break() } else { true }
+ if let Ok(ref c) = *self {
+ c.should_break()
+ } else {
+ true
+ }
}
fn should_prune(&self) -> bool {
- if let Ok(ref c) = *self { c.should_prune() } else { false }
+ if let Ok(ref c) = *self {
+ c.should_prune()
+ } else {
+ false
+ }
}
}
/// The default is `Continue`.
impl<B> Default for Control<B> {
- fn default() -> Self { Control::Continue }
+ fn default() -> Self {
+ Control::Continue
+ }
}
/// A recursive depth first search.
@@ -171,40 +195,54 @@
/// assert_eq!(&path, &[n(0), n(2), n(4), n(5)]);
/// ```
pub fn depth_first_search<G, I, F, C>(graph: G, starts: I, mut visitor: F) -> C
- where G: IntoNeighbors + Visitable,
- I: IntoIterator<Item=G::NodeId>,
- F: FnMut(DfsEvent<G::NodeId>) -> C,
- C: ControlFlow,
+where
+ G: IntoNeighbors + Visitable,
+ I: IntoIterator<Item = G::NodeId>,
+ F: FnMut(DfsEvent<G::NodeId>) -> C,
+ C: ControlFlow,
{
let time = &mut Time(0);
let discovered = &mut graph.visit_map();
let finished = &mut graph.visit_map();
for start in starts {
- try_control!(dfs_visitor(graph, start, &mut visitor, discovered, finished, time),
- unreachable!());
+ try_control!(
+ dfs_visitor(graph, start, &mut visitor, discovered, finished, time),
+ unreachable!()
+ );
}
C::continuing()
}
-fn dfs_visitor<G, F, C>(graph: G, u: G::NodeId, visitor: &mut F,
- discovered: &mut G::Map, finished: &mut G::Map,
- time: &mut Time) -> C
- where G: IntoNeighbors + Visitable,
- F: FnMut(DfsEvent<G::NodeId>) -> C,
- C: ControlFlow,
+fn dfs_visitor<G, F, C>(
+ graph: G,
+ u: G::NodeId,
+ visitor: &mut F,
+ discovered: &mut G::Map,
+ finished: &mut G::Map,
+ time: &mut Time,
+) -> C
+where
+ G: IntoNeighbors + Visitable,
+ F: FnMut(DfsEvent<G::NodeId>) -> C,
+ C: ControlFlow,
{
if !discovered.visit(u) {
return C::continuing();
}
'prune: loop {
- try_control!(visitor(DfsEvent::Discover(u, time_post_inc(time))), break 'prune);
+ try_control!(
+ visitor(DfsEvent::Discover(u, time_post_inc(time))),
+ break 'prune
+ );
for v in graph.neighbors(u) {
if !discovered.is_visited(&v) {
try_control!(visitor(DfsEvent::TreeEdge(u, v)), continue);
- try_control!(dfs_visitor(graph, v, visitor, discovered, finished, time),
- unreachable!());
+ try_control!(
+ dfs_visitor(graph, v, visitor, discovered, finished, time),
+ unreachable!()
+ );
} else if !finished.is_visited(&v) {
try_control!(visitor(DfsEvent::BackEdge(u, v)), continue);
} else {
@@ -216,8 +254,10 @@
}
let first_finish = finished.visit(u);
debug_assert!(first_finish);
- try_control!(visitor(DfsEvent::Finish(u, time_post_inc(time))),
- panic!("Pruning on the `DfsEvent::Finish` is not supported!"));
+ try_control!(
+ visitor(DfsEvent::Finish(u, time_post_inc(time))),
+ panic!("Pruning on the `DfsEvent::Finish` is not supported!")
+ );
C::continuing()
}
diff --git a/src/visit/filter.rs b/src/visit/filter.rs
index 7f7c568..866194d 100644
--- a/src/visit/filter.rs
+++ b/src/visit/filter.rs
@@ -1,37 +1,26 @@
-
use crate::prelude::*;
use fixedbitset::FixedBitSet;
use std::collections::HashSet;
use std::marker::PhantomData;
-use crate::visit::{
- GraphBase,
- GraphProp,
- IntoEdgeReferences,
- IntoEdges,
- IntoEdgesDirected,
- IntoNeighbors,
- IntoNeighborsDirected,
- IntoNodeIdentifiers,
- IntoNodeReferences,
- NodeIndexable,
- NodeRef,
- VisitMap,
- Visitable,
-};
+use crate::data::DataMap;
use crate::visit::{Data, NodeCompactIndexable, NodeCount};
-use crate::data::{DataMap};
+use crate::visit::{
+ GraphBase, GraphProp, IntoEdgeReferences, IntoEdges, IntoEdgesDirected, IntoNeighbors,
+ IntoNeighborsDirected, IntoNodeIdentifiers, IntoNodeReferences, NodeIndexable, NodeRef,
+ VisitMap, Visitable,
+};
/// A graph filter for nodes.
-pub trait FilterNode<N>
-{
+pub trait FilterNode<N> {
/// Return true to have the node be part of the graph
fn include_node(&self, node: N) -> bool;
}
impl<F, N> FilterNode<N> for F
- where F: Fn(N) -> bool,
+where
+ F: Fn(N) -> bool,
{
fn include_node(&self, n: N) -> bool {
(*self)(n)
@@ -40,7 +29,8 @@
/// This filter includes the nodes that are contained in the set.
impl<N> FilterNode<N> for FixedBitSet
- where FixedBitSet: VisitMap<N>,
+where
+ FixedBitSet: VisitMap<N>,
{
fn include_node(&self, n: N) -> bool {
self.is_visited(&n)
@@ -49,7 +39,8 @@
/// This filter includes the nodes that are contained in the set.
impl<N, S> FilterNode<N> for HashSet<N, S>
- where HashSet<N, S>: VisitMap<N>,
+where
+ HashSet<N, S>: VisitMap<N>,
{
fn include_node(&self, n: N) -> bool {
self.is_visited(&n)
@@ -61,8 +52,9 @@
pub struct NodeFiltered<G, F>(pub G, pub F);
impl<F, G> NodeFiltered<G, F>
- where G: GraphBase,
- F: Fn(G::NodeId) -> bool,
+where
+ G: GraphBase,
+ F: Fn(G::NodeId) -> bool,
{
/// Create an `NodeFiltered` adaptor from the closure `filter`.
pub fn from_fn(graph: G, filter: F) -> Self {
@@ -70,14 +62,18 @@
}
}
-impl<G, F> GraphBase for NodeFiltered<G, F> where G: GraphBase {
+impl<G, F> GraphBase for NodeFiltered<G, F>
+where
+ G: GraphBase,
+{
type NodeId = G::NodeId;
type EdgeId = G::EdgeId;
}
impl<'a, G, F> IntoNeighbors for &'a NodeFiltered<G, F>
- where G: IntoNeighbors,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoNeighbors,
+ F: FilterNode<G::NodeId>,
{
type Neighbors = NodeFilteredNeighbors<'a, G::Neighbors, F>;
fn neighbors(self, n: G::NodeId) -> Self::Neighbors {
@@ -90,17 +86,17 @@
}
/// A filtered neighbors iterator.
-pub struct NodeFilteredNeighbors<'a, I, F: 'a>
-{
+pub struct NodeFilteredNeighbors<'a, I, F: 'a> {
include_source: bool,
iter: I,
f: &'a F,
}
impl<'a, I, F> Iterator for NodeFilteredNeighbors<'a, I, F>
- where I: Iterator,
- I::Item: Copy,
- F: FilterNode<I::Item>,
+where
+ I: Iterator,
+ I::Item: Copy,
+ F: FilterNode<I::Item>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
@@ -114,12 +110,12 @@
}
impl<'a, G, F> IntoNeighborsDirected for &'a NodeFiltered<G, F>
- where G: IntoNeighborsDirected,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoNeighborsDirected,
+ F: FilterNode<G::NodeId>,
{
type NeighborsDirected = NodeFilteredNeighbors<'a, G::NeighborsDirected, F>;
- fn neighbors_directed(self, n: G::NodeId, dir: Direction)
- -> Self::NeighborsDirected {
+ fn neighbors_directed(self, n: G::NodeId, dir: Direction) -> Self::NeighborsDirected {
NodeFilteredNeighbors {
include_source: self.1.include_node(n),
iter: self.0.neighbors_directed(n, dir),
@@ -129,8 +125,9 @@
}
impl<'a, G, F> IntoNodeIdentifiers for &'a NodeFiltered<G, F>
- where G: IntoNodeIdentifiers,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoNodeIdentifiers,
+ F: FilterNode<G::NodeId>,
{
type NodeIdentifiers = NodeFilteredNeighbors<'a, G::NodeIdentifiers, F>;
fn node_identifiers(self) -> Self::NodeIdentifiers {
@@ -143,8 +140,9 @@
}
impl<'a, G, F> IntoNodeReferences for &'a NodeFiltered<G, F>
- where G: IntoNodeReferences,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoNodeReferences,
+ F: FilterNode<G::NodeId>,
{
type NodeRef = G::NodeRef;
type NodeReferences = NodeFilteredNodes<'a, G::NodeReferences, F>;
@@ -158,17 +156,17 @@
}
/// A filtered node references iterator.
-pub struct NodeFilteredNodes<'a, I, F: 'a>
-{
+pub struct NodeFilteredNodes<'a, I, F: 'a> {
include_source: bool,
iter: I,
f: &'a F,
}
impl<'a, I, F> Iterator for NodeFilteredNodes<'a, I, F>
- where I: Iterator,
- I::Item: Copy + NodeRef,
- F: FilterNode<<I::Item as NodeRef>::NodeId>,
+where
+ I: Iterator,
+ I::Item: Copy + NodeRef,
+ F: FilterNode<<I::Item as NodeRef>::NodeId>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
@@ -182,8 +180,9 @@
}
impl<'a, G, F> IntoEdgeReferences for &'a NodeFiltered<G, F>
- where G: IntoEdgeReferences,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoEdgeReferences,
+ F: FilterNode<G::NodeId>,
{
type EdgeRef = G::EdgeRef;
type EdgeReferences = NodeFilteredEdgeReferences<'a, G, G::EdgeReferences, F>;
@@ -197,29 +196,30 @@
}
/// A filtered edges iterator.
-pub struct NodeFilteredEdgeReferences<'a, G, I, F: 'a>
-{
+pub struct NodeFilteredEdgeReferences<'a, G, I, F: 'a> {
graph: PhantomData<G>,
iter: I,
f: &'a F,
}
impl<'a, G, I, F> Iterator for NodeFilteredEdgeReferences<'a, G, I, F>
- where F: FilterNode<G::NodeId>,
- G: IntoEdgeReferences,
- I: Iterator<Item=G::EdgeRef>,
+where
+ F: FilterNode<G::NodeId>,
+ G: IntoEdgeReferences,
+ I: Iterator<Item = G::EdgeRef>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
let f = self.f;
- self.iter.find(move |&edge| f.include_node(edge.source()) &&
- f.include_node(edge.target()))
+ self.iter
+ .find(move |&edge| f.include_node(edge.source()) && f.include_node(edge.target()))
}
}
impl<'a, G, F> IntoEdges for &'a NodeFiltered<G, F>
- where G: IntoEdges,
- F: FilterNode<G::NodeId>,
+where
+ G: IntoEdges,
+ F: FilterNode<G::NodeId>,
{
type Edges = NodeFilteredEdges<'a, G, G::Edges, F>;
fn edges(self, a: G::NodeId) -> Self::Edges {
@@ -232,21 +232,19 @@
}
}
-
/// A filtered edges iterator.
-pub struct NodeFilteredEdges<'a, G, I, F: 'a>
-{
+pub struct NodeFilteredEdges<'a, G, I, F: 'a> {
graph: PhantomData<G>,
include_source: bool,
iter: I,
f: &'a F,
}
-
impl<'a, G, I, F> Iterator for NodeFilteredEdges<'a, G, I, F>
- where F: FilterNode<G::NodeId>,
- G: IntoEdges,
- I: Iterator<Item=G::EdgeRef>,
+where
+ F: FilterNode<G::NodeId>,
+ G: IntoEdges,
+ I: Iterator<Item = G::EdgeRef>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
@@ -260,8 +258,9 @@
}
impl<G, F> DataMap for NodeFiltered<G, F>
- where G: DataMap,
- F: FilterNode<G::NodeId>,
+where
+ G: DataMap,
+ F: FilterNode<G::NodeId>,
{
fn node_weight(&self, id: Self::NodeId) -> Option<&Self::NodeWeight> {
if self.1.include_node(id) {
@@ -277,13 +276,15 @@
}
macro_rules! access0 {
- ($e:expr) => ($e.0)
+ ($e:expr) => {
+ $e.0
+ };
}
-Data!{delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
-NodeIndexable!{delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
-GraphProp!{delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
-Visitable!{delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
+Data! {delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
+NodeIndexable! {delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
+GraphProp! {delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
+Visitable! {delegate_impl [[G, F], G, NodeFiltered<G, F>, access0]}
/// A graph filter for edges
pub trait FilterEdge<Edge> {
@@ -292,7 +293,8 @@
}
impl<F, N> FilterEdge<N> for F
- where F: Fn(N) -> bool,
+where
+ F: Fn(N) -> bool,
{
fn include_edge(&self, n: N) -> bool {
(*self)(n)
@@ -311,8 +313,9 @@
pub struct EdgeFiltered<G, F>(pub G, pub F);
impl<F, G> EdgeFiltered<G, F>
- where G: IntoEdgeReferences,
- F: Fn(G::EdgeRef) -> bool,
+where
+ G: IntoEdgeReferences,
+ F: Fn(G::EdgeRef) -> bool,
{
/// Create an `EdgeFiltered` adaptor from the closure `filter`.
pub fn from_fn(graph: G, filter: F) -> Self {
@@ -320,14 +323,18 @@
}
}
-impl<G, F> GraphBase for EdgeFiltered<G, F> where G: GraphBase {
+impl<G, F> GraphBase for EdgeFiltered<G, F>
+where
+ G: GraphBase,
+{
type NodeId = G::NodeId;
type EdgeId = G::EdgeId;
}
impl<'a, G, F> IntoNeighbors for &'a EdgeFiltered<G, F>
- where G: IntoEdges,
- F: FilterEdge<G::EdgeRef>,
+where
+ G: IntoEdges,
+ F: FilterEdge<G::EdgeRef>,
{
type Neighbors = EdgeFilteredNeighbors<'a, G, F>;
fn neighbors(self, n: G::NodeId) -> Self::Neighbors {
@@ -355,30 +362,37 @@
/// A filtered neighbors iterator.
pub struct EdgeFilteredNeighbors<'a, G, F: 'a>
- where G: IntoEdges,
+where
+ G: IntoEdges,
{
iter: G::Edges,
f: &'a F,
}
impl<'a, G, F> Iterator for EdgeFilteredNeighbors<'a, G, F>
- where F: FilterEdge<G::EdgeRef>,
- G: IntoEdges,
+where
+ F: FilterEdge<G::EdgeRef>,
+ G: IntoEdges,
{
type Item = G::NodeId;
fn next(&mut self) -> Option<Self::Item> {
let f = self.f;
- (&mut self.iter).filter_map(move |edge| {
- if f.include_edge(edge) {
- Some(edge.target())
- } else { None }
- }).next()
+ (&mut self.iter)
+ .filter_map(move |edge| {
+ if f.include_edge(edge) {
+ Some(edge.target())
+ } else {
+ None
+ }
+ })
+ .next()
}
}
impl<'a, G, F> IntoEdgeReferences for &'a EdgeFiltered<G, F>
- where G: IntoEdgeReferences,
- F: FilterEdge<G::EdgeRef>,
+where
+ G: IntoEdgeReferences,
+ F: FilterEdge<G::EdgeRef>,
{
type EdgeRef = G::EdgeRef;
type EdgeReferences = EdgeFilteredEdges<'a, G, G::EdgeReferences, F>;
@@ -392,8 +406,9 @@
}
impl<'a, G, F> IntoEdges for &'a EdgeFiltered<G, F>
- where G: IntoEdges,
- F: FilterEdge<G::EdgeRef>,
+where
+ G: IntoEdges,
+ F: FilterEdge<G::EdgeRef>,
{
type Edges = EdgeFilteredEdges<'a, G, G::Edges, F>;
fn edges(self, n: G::NodeId) -> Self::Edges {
@@ -406,17 +421,17 @@
}
/// A filtered edges iterator.
-pub struct EdgeFilteredEdges<'a, G, I, F: 'a>
-{
+pub struct EdgeFilteredEdges<'a, G, I, F: 'a> {
graph: PhantomData<G>,
iter: I,
f: &'a F,
}
impl<'a, G, I, F> Iterator for EdgeFilteredEdges<'a, G, I, F>
- where F: FilterEdge<G::EdgeRef>,
- G: IntoEdgeReferences,
- I: Iterator<Item=G::EdgeRef>,
+where
+ F: FilterEdge<G::EdgeRef>,
+ G: IntoEdgeReferences,
+ I: Iterator<Item = G::EdgeRef>,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
@@ -460,11 +475,11 @@
}
}
-Data!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
-GraphProp!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
-IntoNodeIdentifiers!{delegate_impl [['a, G, F], G, &'a EdgeFiltered<G, F>, access0]}
-IntoNodeReferences!{delegate_impl [['a, G, F], G, &'a EdgeFiltered<G, F>, access0]}
-NodeCompactIndexable!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
-NodeCount!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
-NodeIndexable!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
-Visitable!{delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+Data! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+GraphProp! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+IntoNodeIdentifiers! {delegate_impl [['a, G, F], G, &'a EdgeFiltered<G, F>, access0]}
+IntoNodeReferences! {delegate_impl [['a, G, F], G, &'a EdgeFiltered<G, F>, access0]}
+NodeCompactIndexable! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+NodeCount! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+NodeIndexable! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
+Visitable! {delegate_impl [[G, F], G, EdgeFiltered<G, F>, access0]}
diff --git a/src/visit/macros.rs b/src/visit/macros.rs
index da24542..c558b6e 100644
--- a/src/visit/macros.rs
+++ b/src/visit/macros.rs
@@ -1,4 +1,3 @@
-
/// Define a trait as usual, and a macro that can be used to instantiate
/// implementations of it.
///
@@ -17,7 +16,7 @@
}
}
- remove_sections! { []
+ remove_sections! { []
$(#[$doc])*
pub trait $name $($methods)*
@@ -67,10 +66,14 @@
}
macro_rules! deref {
- ($e:expr) => (*$e);
+ ($e:expr) => {
+ *$e
+ };
}
macro_rules! deref_twice {
- ($e:expr) => (**$e);
+ ($e:expr) => {
+ **$e
+ };
}
/// Implement a trait by delegation. By default as if we are delegating
@@ -130,4 +133,3 @@
}
}
}
-
diff --git a/src/visit/mod.rs b/src/visit/mod.rs
index 739ab58..aa93c35 100644
--- a/src/visit/mod.rs
+++ b/src/visit/mod.rs
@@ -42,7 +42,8 @@
pub use self::filter::*;
pub use self::reversed::*;
-#[macro_use] mod macros;
+#[macro_use]
+mod macros;
mod dfsvisit;
mod traversal;
@@ -50,36 +51,26 @@
pub use self::traversal::*;
use fixedbitset::FixedBitSet;
-use std::collections::{
- HashSet,
-};
-use std::hash::{Hash, BuildHasher};
+use std::collections::HashSet;
+use std::hash::{BuildHasher, Hash};
-use crate::prelude::{Graph, Direction};
+use super::{graph, EdgeType};
+use crate::graph::NodeIndex;
#[cfg(feature = "graphmap")]
use crate::prelude::GraphMap;
#[cfg(feature = "stable_graph")]
use crate::prelude::StableGraph;
-use crate::graph::{NodeIndex};
-use super::{
- graph,
- EdgeType,
-};
+use crate::prelude::{Direction, Graph};
-use crate::graph::{
- IndexType,
-};
+use crate::graph::Frozen;
+use crate::graph::IndexType;
#[cfg(feature = "stable_graph")]
use crate::stable_graph;
-use crate::graph::Frozen;
#[cfg(feature = "graphmap")]
-use crate::graphmap::{
- self,
- NodeTrait,
-};
+use crate::graphmap::{self, NodeTrait};
-trait_template!{
+trait_template! {
/// Base graph trait: defines the associated node identifier and
/// edge identifier types.
pub trait GraphBase {
@@ -94,23 +85,27 @@
}
}
-GraphBase!{delegate_impl []}
-GraphBase!{delegate_impl [['a, G], G, &'a mut G, deref]}
+GraphBase! {delegate_impl []}
+GraphBase! {delegate_impl [['a, G], G, &'a mut G, deref]}
/// A copyable reference to a graph.
-pub trait GraphRef : Copy + GraphBase { }
+pub trait GraphRef: Copy + GraphBase {}
-impl<'a, G> GraphRef for &'a G where G: GraphBase { }
+impl<'a, G> GraphRef for &'a G where G: GraphBase {}
-impl<'a, G> GraphBase for Frozen<'a, G> where G: GraphBase {
+impl<'a, G> GraphBase for Frozen<'a, G>
+where
+ G: GraphBase,
+{
type NodeId = G::NodeId;
type EdgeId = G::EdgeId;
}
#[cfg(feature = "stable_graph")]
impl<'a, N, E: 'a, Ty, Ix> IntoNeighbors for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Neighbors = stable_graph::Neighbors<'a, E, Ix>;
fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
@@ -118,11 +113,11 @@
}
}
-
#[cfg(feature = "graphmap")]
impl<'a, N: 'a, E, Ty> IntoNeighbors for &'a GraphMap<N, E, Ty>
- where N: Copy + Ord + Hash,
- Ty: EdgeType,
+where
+ N: Copy + Ord + Hash,
+ Ty: EdgeType,
{
type Neighbors = graphmap::Neighbors<'a, N, Ty>;
fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
@@ -130,7 +125,6 @@
}
}
-
trait_template! {
/// Access to the neighbors of each node
///
@@ -147,7 +141,7 @@
}
}
-IntoNeighbors!{delegate_impl []}
+IntoNeighbors! {delegate_impl []}
trait_template! {
/// Access to the neighbors of each node, through incoming or outgoing edges.
@@ -168,51 +162,51 @@
}
impl<'a, N, E: 'a, Ty, Ix> IntoNeighbors for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Neighbors = graph::Neighbors<'a, E, Ix>;
- fn neighbors(self, n: graph::NodeIndex<Ix>)
- -> graph::Neighbors<'a, E, Ix>
- {
+ fn neighbors(self, n: graph::NodeIndex<Ix>) -> graph::Neighbors<'a, E, Ix> {
Graph::neighbors(self, n)
}
}
impl<'a, N, E: 'a, Ty, Ix> IntoNeighborsDirected for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NeighborsDirected = graph::Neighbors<'a, E, Ix>;
- fn neighbors_directed(self, n: graph::NodeIndex<Ix>, d: Direction)
- -> graph::Neighbors<'a, E, Ix>
- {
+ fn neighbors_directed(
+ self,
+ n: graph::NodeIndex<Ix>,
+ d: Direction,
+ ) -> graph::Neighbors<'a, E, Ix> {
Graph::neighbors_directed(self, n, d)
}
}
#[cfg(feature = "stable_graph")]
impl<'a, N, E: 'a, Ty, Ix> IntoNeighborsDirected for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NeighborsDirected = stable_graph::Neighbors<'a, E, Ix>;
- fn neighbors_directed(self, n: graph::NodeIndex<Ix>, d: Direction)
- -> Self::NeighborsDirected
- {
+ fn neighbors_directed(self, n: graph::NodeIndex<Ix>, d: Direction) -> Self::NeighborsDirected {
StableGraph::neighbors_directed(self, n, d)
}
}
#[cfg(feature = "graphmap")]
impl<'a, N: 'a, E, Ty> IntoNeighborsDirected for &'a GraphMap<N, E, Ty>
- where N: Copy + Ord + Hash,
- Ty: EdgeType,
+where
+ N: Copy + Ord + Hash,
+ Ty: EdgeType,
{
type NeighborsDirected = graphmap::NeighborsDirected<'a, N, Ty>;
- fn neighbors_directed(self, n: N, dir: Direction)
- -> Self::NeighborsDirected
- {
+ fn neighbors_directed(self, n: N, dir: Direction) -> Self::NeighborsDirected {
self.neighbors_directed(n, dir)
}
}
@@ -238,7 +232,7 @@
}
}
-IntoEdges!{delegate_impl []}
+IntoEdges! {delegate_impl []}
trait_template! {
/// Access to all edges of each node, in the specified direction.
@@ -264,7 +258,7 @@
}
}
-IntoEdgesDirected!{delegate_impl []}
+IntoEdgesDirected! {delegate_impl []}
trait_template! {
/// Access to the sequence of the graph’s `NodeId`s.
@@ -276,11 +270,12 @@
}
}
-IntoNodeIdentifiers!{delegate_impl []}
+IntoNodeIdentifiers! {delegate_impl []}
impl<'a, N, E: 'a, Ty, Ix> IntoNodeIdentifiers for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeIdentifiers = graph::NodeIndices<Ix>;
fn node_identifiers(self) -> graph::NodeIndices<Ix> {
@@ -289,8 +284,9 @@
}
impl<N, E, Ty, Ix> NodeCount for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_count(&self) -> usize {
self.node_count()
@@ -299,8 +295,9 @@
#[cfg(feature = "stable_graph")]
impl<'a, N, E: 'a, Ty, Ix> IntoNodeIdentifiers for &'a StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeIdentifiers = stable_graph::NodeIndices<'a, N, Ix>;
fn node_identifiers(self) -> Self::NodeIdentifiers {
@@ -310,15 +307,16 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> NodeCount for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
fn node_count(&self) -> usize {
self.node_count()
}
}
-IntoNeighborsDirected!{delegate_impl []}
+IntoNeighborsDirected! {delegate_impl []}
trait_template! {
/// Define associated data for nodes and edges
@@ -329,13 +327,13 @@
}
}
-Data!{delegate_impl []}
-Data!{delegate_impl [['a, G], G, &'a mut G, deref]}
+Data! {delegate_impl []}
+Data! {delegate_impl [['a, G], G, &'a mut G, deref]}
/// An edge reference.
///
/// Edge references are used by traits `IntoEdges` and `IntoEdgeReferences`.
-pub trait EdgeRef : Copy {
+pub trait EdgeRef: Copy {
type NodeId;
type EdgeId;
type Weight;
@@ -350,20 +348,29 @@
}
impl<'a, N, E> EdgeRef for (N, N, &'a E)
- where N: Copy
+where
+ N: Copy,
{
type NodeId = N;
type EdgeId = (N, N);
type Weight = E;
- fn source(&self) -> N { self.0 }
- fn target(&self) -> N { self.1 }
- fn weight(&self) -> &E { self.2 }
- fn id(&self) -> (N, N) { (self.0, self.1) }
+ fn source(&self) -> N {
+ self.0
+ }
+ fn target(&self) -> N {
+ self.1
+ }
+ fn weight(&self) -> &E {
+ self.2
+ }
+ fn id(&self) -> (N, N) {
+ (self.0, self.1)
+ }
}
/// A node reference.
-pub trait NodeRef : Copy {
+pub trait NodeRef: Copy {
type NodeId;
type Weight;
fn id(&self) -> Self::NodeId;
@@ -381,14 +388,17 @@
}
}
-IntoNodeReferences!{delegate_impl []}
+IntoNodeReferences! {delegate_impl []}
impl<Id> NodeRef for (Id, ())
- where Id: Copy,
+where
+ Id: Copy,
{
type NodeId = Id;
type Weight = ();
- fn id(&self) -> Self::NodeId { self.0 }
+ fn id(&self) -> Self::NodeId {
+ self.0
+ }
fn weight(&self) -> &Self::Weight {
static DUMMY: () = ();
&DUMMY
@@ -396,15 +406,19 @@
}
impl<'a, Id, W> NodeRef for (Id, &'a W)
- where Id: Copy,
+where
+ Id: Copy,
{
type NodeId = Id;
type Weight = W;
- fn id(&self) -> Self::NodeId { self.0 }
- fn weight(&self) -> &Self::Weight { self.1 }
+ fn id(&self) -> Self::NodeId {
+ self.0
+ }
+ fn weight(&self) -> &Self::Weight {
+ self.1
+ }
}
-
trait_template! {
/// Access to the sequence of the graph’s edges
pub trait IntoEdgeReferences : Data + GraphRef {
@@ -417,12 +431,13 @@
}
}
-IntoEdgeReferences!{delegate_impl [] }
+IntoEdgeReferences! {delegate_impl [] }
#[cfg(feature = "graphmap")]
impl<N, E, Ty> Data for GraphMap<N, E, Ty>
- where N: Copy + PartialEq,
- Ty: EdgeType,
+where
+ N: Copy + PartialEq,
+ Ty: EdgeType,
{
type NodeWeight = N;
type EdgeWeight = E;
@@ -442,35 +457,38 @@
}
}
-GraphProp!{delegate_impl []}
+GraphProp! {delegate_impl []}
impl<N, E, Ty, Ix> GraphProp for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeType = Ty;
}
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> GraphProp for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeType = Ty;
}
#[cfg(feature = "graphmap")]
impl<N, E, Ty> GraphProp for GraphMap<N, E, Ty>
- where N: NodeTrait,
- Ty: EdgeType,
+where
+ N: NodeTrait,
+ Ty: EdgeType,
{
type EdgeType = Ty;
}
-
impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type EdgeRef = graph::EdgeReference<'a, E, Ix>;
type EdgeReferences = graph::EdgeReferences<'a, E, Ix>;
@@ -479,8 +497,7 @@
}
}
-
-trait_template!{
+trait_template! {
/// The graph’s `NodeId`s map to indices
pub trait NodeIndexable : GraphBase {
@section self
@@ -494,7 +511,7 @@
}
}
-NodeIndexable!{delegate_impl []}
+NodeIndexable! {delegate_impl []}
trait_template! {
/// A graph with a known node count.
@@ -504,7 +521,7 @@
}
}
-NodeCount!{delegate_impl []}
+NodeCount! {delegate_impl []}
trait_template! {
/// The graph’s `NodeId`s map to indices, in a range without holes.
@@ -514,21 +531,30 @@
pub trait NodeCompactIndexable : NodeIndexable + NodeCount { }
}
-NodeCompactIndexable!{delegate_impl []}
+NodeCompactIndexable! {delegate_impl []}
impl<N, E, Ty, Ix> NodeIndexable for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
- fn node_bound(&self) -> usize { self.node_count() }
- fn to_index(&self, ix: NodeIndex<Ix>) -> usize { ix.index() }
- fn from_index(&self, ix: usize) -> Self::NodeId { NodeIndex::new(ix) }
+ fn node_bound(&self) -> usize {
+ self.node_count()
+ }
+ fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
+ ix.index()
+ }
+ fn from_index(&self, ix: usize) -> Self::NodeId {
+ NodeIndex::new(ix)
+ }
}
impl<N, E, Ty, Ix> NodeCompactIndexable for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
-{ }
+where
+ Ty: EdgeType,
+ Ix: IndexType,
+{
+}
/// A mapping for storing the visited status for NodeId `N`.
pub trait VisitMap<N> {
@@ -542,7 +568,8 @@
}
impl<Ix> VisitMap<graph::NodeIndex<Ix>> for FixedBitSet
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
fn visit(&mut self, x: graph::NodeIndex<Ix>) -> bool {
!self.put(x.index())
@@ -553,7 +580,8 @@
}
impl<Ix> VisitMap<graph::EdgeIndex<Ix>> for FixedBitSet
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
fn visit(&mut self, x: graph::EdgeIndex<Ix>) -> bool {
!self.put(x.index())
@@ -564,7 +592,8 @@
}
impl<Ix> VisitMap<Ix> for FixedBitSet
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
fn visit(&mut self, x: Ix) -> bool {
!self.put(x.index())
@@ -575,8 +604,9 @@
}
impl<N, S> VisitMap<N> for HashSet<N, S>
- where N: Hash + Eq,
- S: BuildHasher,
+where
+ N: Hash + Eq,
+ S: BuildHasher,
{
fn visit(&mut self, x: N) -> bool {
self.insert(x)
@@ -586,7 +616,7 @@
}
}
-trait_template!{
+trait_template! {
/// A graph that can create a map that tracks the visited status of its nodes.
pub trait Visitable : GraphBase {
@section type
@@ -599,21 +629,25 @@
fn reset_map(self: &Self, map: &mut Self::Map) -> ();
}
}
-Visitable!{delegate_impl []}
+Visitable! {delegate_impl []}
impl<N, E, Ty, Ix> GraphBase for Graph<N, E, Ty, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type NodeId = graph::NodeIndex<Ix>;
type EdgeId = graph::EdgeIndex<Ix>;
}
impl<N, E, Ty, Ix> Visitable for Graph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Map = FixedBitSet;
- fn visit_map(&self) -> FixedBitSet { FixedBitSet::with_capacity(self.node_count()) }
+ fn visit_map(&self) -> FixedBitSet {
+ FixedBitSet::with_capacity(self.node_count())
+ }
fn reset_map(&self, map: &mut Self::Map) {
map.clear();
@@ -623,7 +657,8 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> GraphBase for StableGraph<N, E, Ty, Ix>
- where Ix: IndexType,
+where
+ Ix: IndexType,
{
type NodeId = graph::NodeIndex<Ix>;
type EdgeId = graph::EdgeIndex<Ix>;
@@ -631,8 +666,9 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> Visitable for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type Map = FixedBitSet;
fn visit_map(&self) -> FixedBitSet {
@@ -646,17 +682,18 @@
#[cfg(feature = "stable_graph")]
impl<N, E, Ty, Ix> Data for StableGraph<N, E, Ty, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
type NodeWeight = N;
type EdgeWeight = E;
}
-
#[cfg(feature = "graphmap")]
impl<N, E, Ty> GraphBase for GraphMap<N, E, Ty>
- where N: Copy + PartialEq,
+where
+ N: Copy + PartialEq,
{
type NodeId = N;
type EdgeId = (N, N);
@@ -664,11 +701,14 @@
#[cfg(feature = "graphmap")]
impl<N, E, Ty> Visitable for GraphMap<N, E, Ty>
- where N: Copy + Ord + Hash,
- Ty: EdgeType,
+where
+ N: Copy + Ord + Hash,
+ Ty: EdgeType,
{
type Map = HashSet<N>;
- fn visit_map(&self) -> HashSet<N> { HashSet::with_capacity(self.node_count()) }
+ fn visit_map(&self) -> HashSet<N> {
+ HashSet::with_capacity(self.node_count())
+ }
fn reset_map(&self, map: &mut Self::Map) {
map.clear();
}
@@ -693,18 +733,18 @@
}
}
-
-GetAdjacencyMatrix!{delegate_impl []}
+GetAdjacencyMatrix! {delegate_impl []}
#[cfg(feature = "graphmap")]
/// The `GraphMap` keeps an adjacency matrix internally.
impl<N, E, Ty> GetAdjacencyMatrix for GraphMap<N, E, Ty>
- where N: Copy + Ord + Hash,
- Ty: EdgeType,
+where
+ N: Copy + Ord + Hash,
+ Ty: EdgeType,
{
type AdjMatrix = ();
#[inline]
- fn adjacency_matrix(&self) { }
+ fn adjacency_matrix(&self) {}
#[inline]
fn is_adjacent(&self, _: &(), a: N, b: N) -> bool {
self.contains_edge(a, b)
diff --git a/src/visit/reversed.rs b/src/visit/reversed.rs
index ee5c772..c332c70 100644
--- a/src/visit/reversed.rs
+++ b/src/visit/reversed.rs
@@ -1,26 +1,9 @@
-
-use crate::{
- Direction,
- Incoming,
-};
+use crate::{Direction, Incoming};
use crate::visit::{
- GraphBase,
- GraphRef,
- IntoEdges,
- IntoEdgesDirected,
- IntoNodeIdentifiers,
- IntoNodeReferences,
- IntoNeighbors,
- IntoNeighborsDirected,
- IntoEdgeReferences,
- NodeCompactIndexable,
- NodeCount,
- NodeIndexable,
- Visitable,
- EdgeRef,
- Data,
- GraphProp,
+ Data, EdgeRef, GraphBase, GraphProp, GraphRef, IntoEdgeReferences, IntoEdges,
+ IntoEdgesDirected, IntoNeighbors, IntoNeighborsDirected, IntoNodeIdentifiers,
+ IntoNodeReferences, NodeCompactIndexable, NodeCount, NodeIndexable, Visitable,
};
/// An edge-reversing graph adaptor.
@@ -34,33 +17,33 @@
type EdgeId = G::EdgeId;
}
-impl<G: GraphRef> GraphRef for Reversed<G> { }
+impl<G: GraphRef> GraphRef for Reversed<G> {}
-Data!{delegate_impl [[G], G, Reversed<G>, access0]}
+Data! {delegate_impl [[G], G, Reversed<G>, access0]}
impl<G> IntoNeighbors for Reversed<G>
- where G: IntoNeighborsDirected
+where
+ G: IntoNeighborsDirected,
{
type Neighbors = G::NeighborsDirected;
- fn neighbors(self, n: G::NodeId) -> G::NeighborsDirected
- {
+ fn neighbors(self, n: G::NodeId) -> G::NeighborsDirected {
self.0.neighbors_directed(n, Incoming)
}
}
impl<G> IntoNeighborsDirected for Reversed<G>
- where G: IntoNeighborsDirected
+where
+ G: IntoNeighborsDirected,
{
type NeighborsDirected = G::NeighborsDirected;
- fn neighbors_directed(self, n: G::NodeId, d: Direction)
- -> G::NeighborsDirected
- {
+ fn neighbors_directed(self, n: G::NodeId, d: Direction) -> G::NeighborsDirected {
self.0.neighbors_directed(n, d.opposite())
}
}
impl<G> IntoEdges for Reversed<G>
- where G: IntoEdgesDirected
+where
+ G: IntoEdgesDirected,
{
type Edges = ReversedEdges<G::EdgesDirected>;
fn edges(self, a: Self::NodeId) -> Self::Edges {
@@ -71,7 +54,8 @@
}
impl<G> IntoEdgesDirected for Reversed<G>
- where G: IntoEdgesDirected
+where
+ G: IntoEdgesDirected,
{
type EdgesDirected = ReversedEdges<G::EdgesDirected>;
fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::Edges {
@@ -81,8 +65,7 @@
}
}
-impl<G: Visitable> Visitable for Reversed<G>
-{
+impl<G: Visitable> Visitable for Reversed<G> {
type Map = G::Map;
fn visit_map(&self) -> G::Map {
self.0.visit_map()
@@ -98,7 +81,9 @@
}
impl<I> Iterator for ReversedEdges<I>
- where I: Iterator, I::Item: EdgeRef
+where
+ I: Iterator,
+ I::Item: EdgeRef,
{
type Item = ReversedEdgeReference<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
@@ -112,7 +97,8 @@
/// An edge reference
impl<R> EdgeRef for ReversedEdgeReference<R>
- where R: EdgeRef,
+where
+ R: EdgeRef,
{
type NodeId = R::NodeId;
type EdgeId = R::EdgeId;
@@ -132,7 +118,8 @@
}
impl<G> IntoEdgeReferences for Reversed<G>
- where G: IntoEdgeReferences
+where
+ G: IntoEdgeReferences,
{
type EdgeRef = ReversedEdgeReference<G::EdgeRef>;
type EdgeReferences = ReversedEdgeReferences<G::EdgeReferences>;
@@ -149,8 +136,9 @@
}
impl<I> Iterator for ReversedEdgeReferences<I>
- where I: Iterator,
- I::Item: EdgeRef,
+where
+ I: Iterator,
+ I::Item: EdgeRef,
{
type Item = ReversedEdgeReference<I::Item>;
fn next(&mut self) -> Option<Self::Item> {
@@ -159,14 +147,14 @@
}
macro_rules! access0 {
- ($e:expr) => ($e.0)
+ ($e:expr) => {
+ $e.0
+ };
}
-NodeIndexable!{delegate_impl [[G], G, Reversed<G>, access0]}
-NodeCompactIndexable!{delegate_impl [[G], G, Reversed<G>, access0]}
-IntoNodeIdentifiers!{delegate_impl [[G], G, Reversed<G>, access0]}
-IntoNodeReferences!{delegate_impl [[G], G, Reversed<G>, access0]}
-GraphProp!{delegate_impl [[G], G, Reversed<G>, access0]}
-NodeCount!{delegate_impl [[G], G, Reversed<G>, access0]}
-
-
+NodeIndexable! {delegate_impl [[G], G, Reversed<G>, access0]}
+NodeCompactIndexable! {delegate_impl [[G], G, Reversed<G>, access0]}
+IntoNodeIdentifiers! {delegate_impl [[G], G, Reversed<G>, access0]}
+IntoNodeReferences! {delegate_impl [[G], G, Reversed<G>, access0]}
+GraphProp! {delegate_impl [[G], G, Reversed<G>, access0]}
+NodeCount! {delegate_impl [[G], G, Reversed<G>, access0]}
diff --git a/src/visit/traversal.rs b/src/visit/traversal.rs
index 36618fe..e37f359 100644
--- a/src/visit/traversal.rs
+++ b/src/visit/traversal.rs
@@ -1,7 +1,6 @@
-
-use crate::{Incoming};
-use super::{IntoNeighbors, IntoNeighborsDirected, Visitable, VisitMap};
-use super::{GraphRef, Reversed, IntoNodeIdentifiers};
+use super::{GraphRef, IntoNodeIdentifiers, Reversed};
+use super::{IntoNeighbors, IntoNeighborsDirected, VisitMap, Visitable};
+use crate::Incoming;
use std::collections::VecDeque;
/// Visit nodes of a graph in a depth-first-search (DFS) emitting nodes in
@@ -43,13 +42,15 @@
}
impl<N, VM> Dfs<N, VM>
- where N: Copy + PartialEq,
- VM: VisitMap<N>,
+where
+ N: Copy + PartialEq,
+ VM: VisitMap<N>,
{
/// Create a new **Dfs**, using the graph's visitor map, and put **start**
/// in the stack of nodes to visit.
pub fn new<G>(graph: G, start: N) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
let mut dfs = Dfs::empty(graph);
dfs.move_to(start);
@@ -58,15 +59,13 @@
/// Create a `Dfs` from a vector and a visit map
pub fn from_parts(stack: Vec<N>, discovered: VM) -> Self {
- Dfs {
- stack,
- discovered,
- }
+ Dfs { stack, discovered }
}
/// Clear the visit state
pub fn reset<G>(&mut self, graph: G)
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
graph.reset_map(&mut self.discovered);
self.stack.clear();
@@ -74,7 +73,8 @@
/// Create a new **Dfs** using the graph's visitor map, and no stack.
pub fn empty<G>(graph: G) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
Dfs {
stack: Vec::new(),
@@ -84,15 +84,15 @@
/// Keep the discovered map, but clear the visit stack and restart
/// the dfs from a particular node.
- pub fn move_to(&mut self, start: N)
- {
+ pub fn move_to(&mut self, start: N) {
self.stack.clear();
self.stack.push(start);
}
/// Return the next node in the dfs, or **None** if the traversal is done.
pub fn next<G>(&mut self, graph: G) -> Option<N>
- where G: IntoNeighbors<NodeId=N>,
+ where
+ G: IntoNeighbors<NodeId = N>,
{
while let Some(node) = self.stack.pop() {
if self.discovered.visit(node) {
@@ -126,13 +126,15 @@
}
impl<N, VM> DfsPostOrder<N, VM>
- where N: Copy + PartialEq,
- VM: VisitMap<N>,
+where
+ N: Copy + PartialEq,
+ VM: VisitMap<N>,
{
/// Create a new `DfsPostOrder` using the graph's visitor map, and put
/// `start` in the stack of nodes to visit.
pub fn new<G>(graph: G, start: N) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
let mut dfs = Self::empty(graph);
dfs.move_to(start);
@@ -141,7 +143,8 @@
/// Create a new `DfsPostOrder` using the graph's visitor map, and no stack.
pub fn empty<G>(graph: G) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
DfsPostOrder {
stack: Vec::new(),
@@ -152,7 +155,8 @@
/// Clear the visit state
pub fn reset<G>(&mut self, graph: G)
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
graph.reset_map(&mut self.discovered);
graph.reset_map(&mut self.finished);
@@ -161,15 +165,15 @@
/// Keep the discovered and finished map, but clear the visit stack and restart
/// the dfs from a particular node.
- pub fn move_to(&mut self, start: N)
- {
+ pub fn move_to(&mut self, start: N) {
self.stack.clear();
self.stack.push(start);
}
/// Return the next node in the traversal, or `None` if the traversal is done.
pub fn next<G>(&mut self, graph: G) -> Option<N>
- where G: IntoNeighbors<NodeId=N>,
+ where
+ G: IntoNeighbors<NodeId = N>,
{
while let Some(&nx) = self.stack.last() {
if self.discovered.visit(nx) {
@@ -229,27 +233,27 @@
}
impl<N, VM> Bfs<N, VM>
- where N: Copy + PartialEq,
- VM: VisitMap<N>,
+where
+ N: Copy + PartialEq,
+ VM: VisitMap<N>,
{
/// Create a new **Bfs**, using the graph's visitor map, and put **start**
/// in the stack of nodes to visit.
pub fn new<G>(graph: G, start: N) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
let mut discovered = graph.visit_map();
discovered.visit(start);
let mut stack = VecDeque::new();
stack.push_front(start);
- Bfs {
- stack,
- discovered,
- }
+ Bfs { stack, discovered }
}
/// Return the next node in the bfs, or **None** if the traversal is done.
pub fn next<G>(&mut self, graph: G) -> Option<N>
- where G: IntoNeighbors<NodeId=N>
+ where
+ G: IntoNeighbors<NodeId = N>,
{
if let Some(node) = self.stack.pop_front() {
for succ in graph.neighbors(node) {
@@ -262,7 +266,6 @@
}
None
}
-
}
/// A topological order traversal for a graph.
@@ -277,13 +280,15 @@
}
impl<N, VM> Topo<N, VM>
- where N: Copy + PartialEq,
- VM: VisitMap<N>,
+where
+ N: Copy + PartialEq,
+ VM: VisitMap<N>,
{
/// Create a new `Topo`, using the graph's visitor map, and put all
/// initial nodes in the to visit list.
pub fn new<G>(graph: G) -> Self
- where G: IntoNodeIdentifiers + IntoNeighborsDirected + Visitable<NodeId=N, Map=VM>,
+ where
+ G: IntoNodeIdentifiers + IntoNeighborsDirected + Visitable<NodeId = N, Map = VM>,
{
let mut topo = Self::empty(graph);
topo.extend_with_initials(graph);
@@ -291,18 +296,22 @@
}
fn extend_with_initials<G>(&mut self, g: G)
- where G: IntoNodeIdentifiers + IntoNeighborsDirected<NodeId=N>,
+ where
+ G: IntoNodeIdentifiers + IntoNeighborsDirected<NodeId = N>,
{
// find all initial nodes (nodes without incoming edges)
- self.tovisit.extend(g.node_identifiers()
- .filter(move |&a| g.neighbors_directed(a, Incoming).next().is_none()));
+ self.tovisit.extend(
+ g.node_identifiers()
+ .filter(move |&a| g.neighbors_directed(a, Incoming).next().is_none()),
+ );
}
/* Private until it has a use */
/// Create a new `Topo`, using the graph's visitor map with *no* starting
/// index specified.
fn empty<G>(graph: G) -> Self
- where G: GraphRef + Visitable<NodeId=N, Map=VM>
+ where
+ G: GraphRef + Visitable<NodeId = N, Map = VM>,
{
Topo {
ordered: graph.visit_map(),
@@ -312,7 +321,8 @@
/// Clear visited state, and put all initial nodes in the to visit list.
pub fn reset<G>(&mut self, graph: G)
- where G: IntoNodeIdentifiers + IntoNeighborsDirected + Visitable<NodeId=N, Map=VM>,
+ where
+ G: IntoNodeIdentifiers + IntoNeighborsDirected + Visitable<NodeId = N, Map = VM>,
{
graph.reset_map(&mut self.ordered);
self.tovisit.clear();
@@ -325,7 +335,8 @@
/// *Note:* The graph may not have a complete topological order, and the only
/// way to know is to run the whole traversal and make sure it visits every node.
pub fn next<G>(&mut self, g: G) -> Option<N>
- where G: IntoNeighborsDirected + Visitable<NodeId=N, Map=VM>,
+ where
+ G: IntoNeighborsDirected + Visitable<NodeId = N, Map = VM>,
{
// Take an unvisited element and find which of its neighbors are next
while let Some(nix) = self.tovisit.pop() {
@@ -336,7 +347,10 @@
for neigh in g.neighbors(nix) {
// Look at each neighbor, and those that only have incoming edges
// from the already ordered list, they are the next to visit.
- if Reversed(g).neighbors(neigh).all(|b| self.ordered.is_visited(&b)) {
+ if Reversed(g)
+ .neighbors(neigh)
+ .all(|b| self.ordered.is_visited(&b))
+ {
self.tovisit.push(neigh);
}
}
@@ -346,7 +360,6 @@
}
}
-
/// A walker is a traversal state, but where part of the traversal
/// information is supplied manually to each next call.
///
@@ -359,8 +372,9 @@
/// Create an iterator out of the walker and given `context`.
fn iter(self, context: Context) -> WalkerIter<Self, Context>
- where Self: Sized,
- Context: Clone,
+ where
+ Self: Sized,
+ Context: Clone,
{
WalkerIter {
walker: self,
@@ -377,8 +391,9 @@
}
impl<W, C> WalkerIter<W, C>
- where W: Walker<C>,
- C: Clone,
+where
+ W: Walker<C>,
+ C: Clone,
{
pub fn context(&self) -> C {
self.context.clone()
@@ -394,8 +409,9 @@
}
impl<W, C> Iterator for WalkerIter<W, C>
- where W: Walker<C>,
- C: Clone,
+where
+ W: Walker<C>,
+ C: Clone,
{
type Item = W::Item;
fn next(&mut self) -> Option<Self::Item> {
@@ -404,7 +420,8 @@
}
impl<'a, C, W: ?Sized> Walker<C> for &'a mut W
- where W: Walker<C>,
+where
+ W: Walker<C>,
{
type Item = W::Item;
fn walk_next(&mut self, context: C) -> Option<Self::Item> {
@@ -413,7 +430,8 @@
}
impl<G> Walker<G> for Dfs<G::NodeId, G::Map>
- where G: IntoNeighbors + Visitable
+where
+ G: IntoNeighbors + Visitable,
{
type Item = G::NodeId;
fn walk_next(&mut self, context: G) -> Option<Self::Item> {
@@ -422,7 +440,8 @@
}
impl<G> Walker<G> for DfsPostOrder<G::NodeId, G::Map>
- where G: IntoNeighbors + Visitable
+where
+ G: IntoNeighbors + Visitable,
{
type Item = G::NodeId;
fn walk_next(&mut self, context: G) -> Option<Self::Item> {
@@ -431,7 +450,8 @@
}
impl<G> Walker<G> for Bfs<G::NodeId, G::Map>
- where G: IntoNeighbors + Visitable
+where
+ G: IntoNeighbors + Visitable,
{
type Item = G::NodeId;
fn walk_next(&mut self, context: G) -> Option<Self::Item> {
@@ -440,7 +460,8 @@
}
impl<G> Walker<G> for Topo<G::NodeId, G::Map>
- where G: IntoNeighborsDirected + Visitable,
+where
+ G: IntoNeighborsDirected + Visitable,
{
type Item = G::NodeId;
fn walk_next(&mut self, context: G) -> Option<Self::Item> {
diff --git a/tests/graph.rs b/tests/graph.rs
index 758007d..a8e4097 100644
--- a/tests/graph.rs
+++ b/tests/graph.rs
@@ -4,56 +4,36 @@
use std::hash::Hash;
use petgraph::prelude::*;
-use petgraph::{
- EdgeType,
-};
+use petgraph::EdgeType;
use petgraph as pg;
use petgraph::algo::{
- dominators,
- has_path_connecting,
- is_cyclic_undirected,
+ dominators, has_path_connecting, is_cyclic_undirected, is_isomorphic_matching,
min_spanning_tree,
- is_isomorphic_matching,
};
use petgraph::graph::node_index as n;
-use petgraph::graph::{
- IndexType,
-};
+use petgraph::graph::IndexType;
+use petgraph::algo::{astar, dijkstra, DfsSpace};
use petgraph::visit::{
- IntoEdges,
- IntoEdgesDirected,
- IntoNodeIdentifiers,
- NodeFiltered,
- Reversed,
- Topo,
- IntoNeighbors,
- VisitMap,
- Walker,
-};
-use petgraph::algo::{
- DfsSpace,
- dijkstra,
- astar,
+ IntoEdges, IntoEdgesDirected, IntoNeighbors, IntoNodeIdentifiers, NodeFiltered, Reversed, Topo,
+ VisitMap, Walker,
};
-use petgraph::dot::{
- Dot,
-};
+use petgraph::dot::Dot;
fn set<I>(iter: I) -> HashSet<I::Item>
- where I: IntoIterator,
- I::Item: Hash + Eq,
+where
+ I: IntoIterator,
+ I::Item: Hash + Eq,
{
iter.into_iter().collect()
}
#[test]
-fn undirected()
-{
+fn undirected() {
let mut og = Graph::new_undirected();
let a = og.add_node(0);
let b = og.add_node(1);
@@ -89,7 +69,6 @@
assert!(og.find_edge(a, a).is_none());
assert!(og.find_edge(b, c).is_some());
assert_graph_consistent(&og);
-
}
#[test]
@@ -147,7 +126,6 @@
}
}
-
#[test]
fn bfs() {
let mut gr = Graph::new();
@@ -187,13 +165,11 @@
assert_eq!(bfs.next(&gr), None);
}
-
-
#[test]
fn mst() {
use petgraph::data::FromElements;
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node("A");
let b = gr.add_node("B");
let c = gr.add_node("C");
@@ -245,7 +221,6 @@
assert!(mst.find_edge(d, b).is_none());
assert!(mst.find_edge(b, c).is_none());
-
}
#[test]
@@ -312,7 +287,6 @@
gr.add_edge(a, b, ());
gr.add_edge(a, b, ());
assert_eq!(gr.edge_count(), 2);
-
}
#[test]
@@ -380,8 +354,7 @@
}
#[test]
-fn update_edge()
-{
+fn update_edge() {
{
let mut gr = Graph::new();
let a = gr.add_node("a");
@@ -432,8 +405,17 @@
let scores = dijkstra(&g, a, None, |e| *e.weight());
let mut scores: Vec<_> = scores.into_iter().map(|(n, s)| (g[n], s)).collect();
scores.sort();
- assert_eq!(scores,
- vec![("A", 0), ("B", 7), ("C", 9), ("D", 11), ("E", 20), ("F", 20)]);
+ assert_eq!(
+ scores,
+ vec![
+ ("A", 0),
+ ("B", 7),
+ ("C", 9),
+ ("D", 11),
+ ("E", 20),
+ ("F", 20)
+ ]
+ );
let scores = dijkstra(&g, a, Some(c), |e| *e.weight());
assert_eq!(scores[&c], 9);
@@ -496,7 +478,13 @@
(x2 - x1).abs() + (y2 - y1).abs()
}
};
- let path = astar(&g, a, |finish| finish == f, |e| *e.weight(), heuristic_for(f));
+ let path = astar(
+ &g,
+ a,
+ |finish| finish == f,
+ |e| *e.weight(),
+ heuristic_for(f),
+ );
assert_eq!(path, Some((6., vec![a, d, e, f])));
@@ -504,10 +492,14 @@
let dijkstra_run = dijkstra(&g, a, None, |e| *e.weight());
for end in g.node_indices() {
- let astar_path = astar(&g, a, |finish| finish == end, |e| *e.weight(),
- heuristic_for(end));
- assert_eq!(dijkstra_run.get(&end).cloned(),
- astar_path.map(|t| t.0));
+ let astar_path = astar(
+ &g,
+ a,
+ |finish| finish == end,
+ |e| *e.weight(),
+ heuristic_for(end),
+ );
+ assert_eq!(dijkstra_run.get(&end).cloned(), astar_path.map(|t| t.0));
}
}
@@ -568,20 +560,25 @@
assert_eq!(graphs.len(), 1 << nedges);
// check that all generated graphs have unique adjacency matrices
- let mut adjmats = graphs.iter().map(Graph::adjacency_matrix).collect::<Vec<_>>();
+ let mut adjmats = graphs
+ .iter()
+ .map(Graph::adjacency_matrix)
+ .collect::<Vec<_>>();
adjmats.sort();
adjmats.dedup();
assert_eq!(adjmats.len(), graphs.len());
for gr in &graphs {
- assert!(!petgraph::algo::is_cyclic_directed(gr),
- "Assertion failed: {:?} acyclic", gr);
+ assert!(
+ !petgraph::algo::is_cyclic_directed(gr),
+ "Assertion failed: {:?} acyclic",
+ gr
+ );
}
}
}
#[test]
-fn without()
-{
+fn without() {
let mut og = Graph::new_undirected();
let a = og.add_node(0);
let b = og.add_node(1);
@@ -605,8 +602,7 @@
assert_eq!(term, vec![b, c, d]);
}
-fn assert_is_topo_order<N, E>(gr: &Graph<N, E, Directed>, order: &[NodeIndex])
-{
+fn assert_is_topo_order<N, E>(gr: &Graph<N, E, Directed>, order: &[NodeIndex]) {
assert_eq!(gr.node_count(), order.len());
// check all the edges of the graph
for edge in gr.raw_edges() {
@@ -615,14 +611,18 @@
let ai = order.iter().position(|x| *x == a).unwrap();
let bi = order.iter().position(|x| *x == b).unwrap();
println!("Check that {:?} is before {:?}", a, b);
- assert!(ai < bi, "Topo order: assertion that node {:?} is before {:?} failed",
- a, b);
+ assert!(
+ ai < bi,
+ "Topo order: assertion that node {:?} is before {:?} failed",
+ a,
+ b
+ );
}
}
#[test]
fn test_toposort() {
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node("A");
let b = gr.add_node("B");
let c = gr.add_node("C");
@@ -661,7 +661,7 @@
#[test]
fn test_toposort_eq() {
- let mut g = Graph::<_,_>::new();
+ let mut g = Graph::<_, _>::new();
let a = g.add_node("A");
let b = g.add_node("B");
g.add_edge(a, b, ());
@@ -671,7 +671,7 @@
#[test]
fn is_cyclic_directed() {
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node("A");
let b = gr.add_node("B");
let c = gr.add_node("C");
@@ -708,8 +708,11 @@
/// Compare two scc sets. Inside each scc, the order does not matter,
/// but the order of the sccs is significant.
-fn assert_sccs_eq(mut res: Vec<Vec<NodeIndex>>, mut answer: Vec<Vec<NodeIndex>>,
- scc_order_matters: bool) {
+fn assert_sccs_eq(
+ mut res: Vec<Vec<NodeIndex>>,
+ mut answer: Vec<Vec<NodeIndex>>,
+ scc_order_matters: bool,
+) {
// normalize the result and compare with the answer.
for scc in &mut res {
scc.sort();
@@ -737,20 +740,28 @@
(7, 5),
(1, 7),
(7, 4),
- (4, 1)]);
+ (4, 1),
+ ]);
- assert_sccs_eq(petgraph::algo::kosaraju_scc(&gr), vec![
- vec![n(0), n(3), n(6)],
- vec![n(2), n(5), n(8)],
- vec![n(1), n(4), n(7)],
- ], true);
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(&gr),
+ vec![
+ vec![n(0), n(3), n(6)],
+ vec![n(2), n(5), n(8)],
+ vec![n(1), n(4), n(7)],
+ ],
+ true,
+ );
// Reversed edges gives the same sccs (when sorted)
- assert_sccs_eq(petgraph::algo::kosaraju_scc(Reversed(&gr)), vec![
- vec![n(1), n(4), n(7)],
- vec![n(2), n(5), n(8)],
- vec![n(0), n(3), n(6)],
- ], true);
-
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(Reversed(&gr)),
+ vec![
+ vec![n(1), n(4), n(7)],
+ vec![n(2), n(5), n(8)],
+ vec![n(0), n(3), n(6)],
+ ],
+ true,
+ );
// Test an undirected graph just for fun.
// Sccs are just connected components.
@@ -759,11 +770,14 @@
let ed = hr.find_edge(n(6), n(8)).unwrap();
assert!(hr.remove_edge(ed).is_some());
- assert_sccs_eq(petgraph::algo::kosaraju_scc(&hr), vec![
- vec![n(0), n(3), n(6)],
- vec![n(1), n(2), n(4), n(5), n(7), n(8)],
- ], false);
-
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(&hr),
+ vec![
+ vec![n(0), n(3), n(6)],
+ vec![n(1), n(2), n(4), n(5), n(7), n(8)],
+ ],
+ false,
+ );
// acyclic non-tree, #14
let n = NodeIndex::new;
@@ -777,27 +791,24 @@
gr.add_edge(n(2), n(0), ());
gr.add_edge(n(1), n(0), ());
- assert_sccs_eq(petgraph::algo::kosaraju_scc(&gr), vec![
- vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)],
- ], true);
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(&gr),
+ vec![vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)]],
+ true,
+ );
// Kosaraju bug from PR #60
let mut gr = Graph::<(), ()>::new();
- gr.extend_with_edges(&[
- (0, 0),
- (1, 0),
- (2, 0),
- (2, 1),
- (2, 2),
- ]);
+ gr.extend_with_edges(&[(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]);
gr.add_node(());
// no order for the disconnected one
- assert_sccs_eq(petgraph::algo::kosaraju_scc(&gr), vec![
- vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)],
- ], false);
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(&gr),
+ vec![vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)]],
+ false,
+ );
}
-
#[test]
fn tarjan_scc() {
let gr: Graph<(), ()> = Graph::from_edges(&[
@@ -811,14 +822,18 @@
(7, 5),
(1, 7),
(7, 4),
- (4, 1)]);
+ (4, 1),
+ ]);
- assert_sccs_eq(petgraph::algo::tarjan_scc(&gr), vec![
- vec![n(0), n(3), n(6)],
- vec![n(2), n(5), n(8)],
- vec![n(1), n(4), n(7)],
- ], true);
-
+ assert_sccs_eq(
+ petgraph::algo::tarjan_scc(&gr),
+ vec![
+ vec![n(0), n(3), n(6)],
+ vec![n(2), n(5), n(8)],
+ vec![n(1), n(4), n(7)],
+ ],
+ true,
+ );
// Test an undirected graph just for fun.
// Sccs are just connected components.
@@ -827,11 +842,14 @@
let ed = hr.find_edge(n(6), n(8)).unwrap();
assert!(hr.remove_edge(ed).is_some());
- assert_sccs_eq(petgraph::algo::tarjan_scc(&hr), vec![
- vec![n(1), n(2), n(4), n(5), n(7), n(8)],
- vec![n(0), n(3), n(6)],
- ], false);
-
+ assert_sccs_eq(
+ petgraph::algo::tarjan_scc(&hr),
+ vec![
+ vec![n(1), n(2), n(4), n(5), n(7), n(8)],
+ vec![n(0), n(3), n(6)],
+ ],
+ false,
+ );
// acyclic non-tree, #14
let n = NodeIndex::new;
@@ -845,30 +863,26 @@
gr.add_edge(n(2), n(0), ());
gr.add_edge(n(1), n(0), ());
- assert_sccs_eq(petgraph::algo::tarjan_scc(&gr), vec![
- vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)],
- ], true);
+ assert_sccs_eq(
+ petgraph::algo::tarjan_scc(&gr),
+ vec![vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)]],
+ true,
+ );
// Kosaraju bug from PR #60
let mut gr = Graph::<(), ()>::new();
- gr.extend_with_edges(&[
- (0, 0),
- (1, 0),
- (2, 0),
- (2, 1),
- (2, 2),
- ]);
+ gr.extend_with_edges(&[(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]);
gr.add_node(());
// no order for the disconnected one
- assert_sccs_eq(petgraph::algo::tarjan_scc(&gr), vec![
- vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)],
- ], false);
+ assert_sccs_eq(
+ petgraph::algo::tarjan_scc(&gr),
+ vec![vec![n(0)], vec![n(1)], vec![n(2)], vec![n(3)]],
+ false,
+ );
}
-
#[test]
-fn condensation()
-{
+fn condensation() {
let gr: Graph<(), ()> = Graph::from_edges(&[
(6, 0),
(0, 3),
@@ -881,8 +895,8 @@
(7, 5),
(1, 7),
(7, 4),
- (4, 1)]);
-
+ (4, 1),
+ ]);
// make_acyclic = true
@@ -890,9 +904,11 @@
assert!(cond.node_count() == 3);
assert!(cond.edge_count() == 2);
- assert!(!petgraph::algo::is_cyclic_directed(&cond),
- "Assertion failed: {:?} acyclic", cond);
-
+ assert!(
+ !petgraph::algo::is_cyclic_directed(&cond),
+ "Assertion failed: {:?} acyclic",
+ cond
+ );
// make_acyclic = false
@@ -903,8 +919,7 @@
}
#[test]
-fn connected_comp()
-{
+fn connected_comp() {
let n = NodeIndex::new;
let mut gr = Graph::new();
gr.add_node(0);
@@ -942,8 +957,7 @@
#[should_panic]
#[test]
-fn oob_index()
-{
+fn oob_index() {
let mut gr = Graph::<_, ()>::new();
let a = gr.add_node(0);
let b = gr.add_node(1);
@@ -952,8 +966,7 @@
}
#[test]
-fn usize_index()
-{
+fn usize_index() {
let mut gr = Graph::<_, _, Directed, usize>::with_capacity(0, 0);
let a = gr.add_node(0);
let b = gr.add_node(1);
@@ -968,8 +981,7 @@
}
#[test]
-fn u8_index()
-{
+fn u8_index() {
let mut gr = Graph::<_, (), Undirected, u8>::with_capacity(0, 0);
for _ in 0..255 {
gr.add_node(());
@@ -978,8 +990,7 @@
#[should_panic]
#[test]
-fn u8_index_overflow()
-{
+fn u8_index_overflow() {
let mut gr = Graph::<_, (), Undirected, u8>::with_capacity(0, 0);
for _ in 0..256 {
gr.add_node(());
@@ -988,8 +999,7 @@
#[should_panic]
#[test]
-fn u8_index_overflow_edges()
-{
+fn u8_index_overflow_edges() {
let mut gr = Graph::<_, (), Undirected, u8>::with_capacity(0, 0);
let a = gr.add_node('a');
let b = gr.add_node('b');
@@ -1000,7 +1010,7 @@
#[test]
fn test_weight_iterators() {
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node("A");
let b = gr.add_node("B");
let c = gr.add_node("C");
@@ -1044,7 +1054,7 @@
let old = gr.clone();
for (index, ew) in gr.edge_weights_mut().enumerate() {
assert_eq!(old[EdgeIndex::new(index)], *ew);
- *ew = - *ew;
+ *ew = -*ew;
}
for (index, edge) in gr.raw_edges().iter().enumerate() {
assert_eq!(edge.weight, -1. * old[EdgeIndex::new(index)]);
@@ -1053,7 +1063,7 @@
#[test]
fn walk_edges() {
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node(0.);
let b = gr.add_node(1.);
let c = gr.add_node(2.);
@@ -1096,7 +1106,7 @@
#[test]
fn index_twice_mut() {
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let a = gr.add_node(0.);
let b = gr.add_node(0.);
let c = gr.add_node(0.);
@@ -1117,7 +1127,9 @@
gr.add_edge(e, g, 9.);
for dir in &[Incoming, Outgoing] {
- for nw in gr.node_weights_mut() { *nw = 0.; }
+ for nw in gr.node_weights_mut() {
+ *nw = 0.;
+ }
// walk the graph and sum incoming edges
let mut dfs = Dfs::new(&gr, a);
@@ -1132,7 +1144,10 @@
// check the sums
for i in 0..gr.node_count() {
let ni = NodeIndex::new(i);
- let s = gr.edges_directed(ni, *dir).map(|e| *e.weight()).fold(0., |a, b| a + b);
+ let s = gr
+ .edges_directed(ni, *dir)
+ .map(|e| *e.weight())
+ .fold(0., |a, b| a + b);
assert_eq!(s, gr[ni]);
}
println!("Sum {:?}: {:?}", dir, gr);
@@ -1169,20 +1184,30 @@
let gr = make_edge_iterator_graph::<Directed>();
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Outgoing),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Outgoing), gr.edges(i));
// Reversed reverses edges, so target and source need to be reversed once more.
itertools::assert_equal(
- gr.edges_directed(i, Outgoing).map(|edge| (edge.source(), edge.target())),
- Reversed(&gr).edges_directed(i, Incoming).map(|edge| (edge.target(), edge.source())));
+ gr.edges_directed(i, Outgoing)
+ .map(|edge| (edge.source(), edge.target())),
+ Reversed(&gr)
+ .edges_directed(i, Incoming)
+ .map(|edge| (edge.target(), edge.source())),
+ );
for edge in gr.edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "outgoing edges should have a fixed source"
+ );
}
for edge in Reversed(&gr).edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "reversed incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "reversed incoming edges should have a fixed target"
+ );
}
}
@@ -1192,20 +1217,30 @@
println!("{:#?}", gr);
for i in gr.node_indices() {
// Compare against reversed graphs two different ways: using .reverse() and Reversed.
- itertools::assert_equal(
- gr.edges_directed(i, Incoming),
- reversed_gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Incoming), reversed_gr.edges(i));
// Reversed reverses edges, so target and source need to be reversed once more.
itertools::assert_equal(
- gr.edges_directed(i, Incoming).map(|edge| (edge.source(), edge.target())),
- Reversed(&gr).edges(i).map(|edge| (edge.target(), edge.source())));
+ gr.edges_directed(i, Incoming)
+ .map(|edge| (edge.source(), edge.target())),
+ Reversed(&gr)
+ .edges(i)
+ .map(|edge| (edge.target(), edge.source())),
+ );
for edge in gr.edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "incoming edges should have a fixed target"
+ );
}
for edge in Reversed(&gr).edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "reversed outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "reversed outgoing edges should have a fixed source"
+ );
}
}
}
@@ -1215,38 +1250,58 @@
let gr = make_edge_iterator_graph::<Undirected>();
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Outgoing),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Outgoing), gr.edges(i));
// Reversed reverses edges, so target and source need to be reversed once more.
itertools::assert_equal(
- gr.edges_directed(i, Outgoing).map(|edge| (edge.source(), edge.target())),
- Reversed(&gr).edges_directed(i, Incoming).map(|edge| (edge.target(), edge.source())));
+ gr.edges_directed(i, Outgoing)
+ .map(|edge| (edge.source(), edge.target())),
+ Reversed(&gr)
+ .edges_directed(i, Incoming)
+ .map(|edge| (edge.target(), edge.source())),
+ );
for edge in gr.edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "outgoing edges should have a fixed source"
+ );
}
for edge in Reversed(&gr).edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "reversed incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "reversed incoming edges should have a fixed target"
+ );
}
}
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Incoming),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Incoming), gr.edges(i));
// Reversed reverses edges, so target and source need to be reversed once more.
itertools::assert_equal(
- gr.edges_directed(i, Incoming).map(|edge| (edge.source(), edge.target())),
- Reversed(&gr).edges(i).map(|edge| (edge.target(), edge.source())));
+ gr.edges_directed(i, Incoming)
+ .map(|edge| (edge.source(), edge.target())),
+ Reversed(&gr)
+ .edges(i)
+ .map(|edge| (edge.target(), edge.source())),
+ );
for edge in gr.edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "incoming edges should have a fixed target"
+ );
}
for edge in Reversed(&gr).edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "reversed outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "reversed outgoing edges should have a fixed source"
+ );
}
}
}
@@ -1254,7 +1309,7 @@
#[test]
fn toposort_generic() {
// This is a DAG, visit it in order
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let b = gr.add_node(("B", 0.));
let a = gr.add_node(("A", 0.));
let c = gr.add_node(("C", 0.));
@@ -1314,7 +1369,7 @@
#[test]
fn test_has_path() {
// This is a DAG, visit it in order
- let mut gr = Graph::<_,_>::new();
+ let mut gr = Graph::<_, _>::new();
let b = gr.add_node(("B", 0.));
let a = gr.add_node(("A", 0.));
let c = gr.add_node(("C", 0.));
@@ -1376,24 +1431,27 @@
g.add_edge(e, f, 6);
println!("{:?}", g);
- let g2 = g.filter_map(|_, name| Some(*name), |_, &weight| if weight >= 10 {
- Some(weight)
- } else { None });
+ let g2 = g.filter_map(
+ |_, name| Some(*name),
+ |_, &weight| if weight >= 10 { Some(weight) } else { None },
+ );
assert_eq!(g2.edge_count(), 4);
for edge in g2.raw_edges() {
assert!(edge.weight >= 10);
}
- let g3 = g.filter_map(|i, &name| if i == a || i == e { None } else { Some(name) },
- |i, &weight| {
- let (source, target) = g.edge_endpoints(i).unwrap();
- // don't map edges from a removed node
- assert!(source != a);
- assert!(target != a);
- assert!(source != e);
- assert!(target != e);
- Some(weight)
- });
+ let g3 = g.filter_map(
+ |i, &name| if i == a || i == e { None } else { Some(name) },
+ |i, &weight| {
+ let (source, target) = g.edge_endpoints(i).unwrap();
+ // don't map edges from a removed node
+ assert!(source != a);
+ assert!(target != a);
+ assert!(source != e);
+ assert!(target != e);
+ Some(weight)
+ },
+ );
assert_eq!(g3.node_count(), g.node_count() - 2);
assert_eq!(g3.edge_count(), g.edge_count() - 5);
assert_graph_consistent(&g3);
@@ -1410,11 +1468,8 @@
#[test]
fn from_edges() {
let n = NodeIndex::new;
- let gr = Graph::<(), (), Undirected>::from_edges(&[
- (0, 1), (0, 2), (0, 3),
- (1, 2), (1, 3),
- (2, 3),
- ]);
+ let gr =
+ Graph::<(), (), Undirected>::from_edges(&[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]);
assert_eq!(gr.node_count(), 4);
assert_eq!(gr.edge_count(), 6);
assert_eq!(gr.neighbors(n(0)).count(), 3);
@@ -1434,8 +1489,9 @@
(2, 3, 3),
]);
gr.retain_edges(|mut gr, i| {
- if gr[i] <= 0 { false }
- else {
+ if gr[i] <= 0 {
+ false
+ } else {
gr[i] -= 1;
let (s, t) = gr.edge_endpoints(i).unwrap();
gr[s] += 1;
@@ -1456,30 +1512,30 @@
}
fn assert_graph_consistent<N, E, Ty, Ix>(g: &Graph<N, E, Ty, Ix>)
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
assert_eq!(g.node_count(), g.node_indices().count());
assert_eq!(g.edge_count(), g.edge_indices().count());
for edge in g.raw_edges() {
- assert!(g.find_edge(edge.source(), edge.target()).is_some(),
- "Edge not in graph! {:?} to {:?}", edge.source(), edge.target());
+ assert!(
+ g.find_edge(edge.source(), edge.target()).is_some(),
+ "Edge not in graph! {:?} to {:?}",
+ edge.source(),
+ edge.target()
+ );
}
}
#[test]
fn neighbors_selfloops() {
// Directed graph
- let mut gr = Graph::<_ ,()>::new();
+ let mut gr = Graph::<_, ()>::new();
let a = gr.add_node("a");
let b = gr.add_node("b");
let c = gr.add_node("c");
- gr.extend_with_edges(&[
- (a, a),
- (a, b),
- (c, a),
- (a, a),
- ]);
+ gr.extend_with_edges(&[(a, a), (a, b), (c, a), (a, a)]);
let out_edges = [a, a, b];
let in_edges = [a, a, c];
@@ -1501,19 +1557,25 @@
let mut seen_walk = Vec::new();
let mut walk = gr.neighbors(a).detach();
- while let Some(n) = walk.next_node(&gr) { seen_walk.push(n); }
+ while let Some(n) = walk.next_node(&gr) {
+ seen_walk.push(n);
+ }
seen_walk.sort();
assert_eq!(&seen_walk, &out_edges);
seen_walk.clear();
let mut walk = gr.neighbors_directed(a, Incoming).detach();
- while let Some(n) = walk.next_node(&gr) { seen_walk.push(n); }
+ while let Some(n) = walk.next_node(&gr) {
+ seen_walk.push(n);
+ }
seen_walk.sort();
assert_eq!(&seen_walk, &in_edges);
seen_walk.clear();
let mut walk = gr.neighbors_undirected(a).detach();
- while let Some(n) = walk.next_node(&gr) { seen_walk.push(n); }
+ while let Some(n) = walk.next_node(&gr) {
+ seen_walk.push(n);
+ }
seen_walk.sort();
assert_eq!(&seen_walk, &undir_edges);
@@ -1522,11 +1584,7 @@
let a = gr.add_node("a");
let b = gr.add_node("b");
let c = gr.add_node("c");
- gr.extend_with_edges(&[
- (a, a),
- (a, b),
- (c, a),
- ]);
+ gr.extend_with_edges(&[(a, a), (a, b), (c, a)]);
let out_edges = [a, b, c];
let in_edges = [a, b, c];
@@ -1548,10 +1606,10 @@
assert_eq!(&seen_undir, &undir_edges);
}
-
fn degree<'a, G>(g: G, node: G::NodeId) -> usize
- where G: IntoNeighbors,
- G::NodeId: PartialEq,
+where
+ G: IntoNeighbors,
+ G::NodeId: PartialEq,
{
// self loops count twice
let original_node = node.clone();
@@ -1567,30 +1625,35 @@
fn degree_sequence() {
let mut gr = Graph::<usize, (), Undirected>::from_edges(&[
(0, 1),
- (1, 2), (1, 3),
- (2, 4), (3, 4),
+ (1, 2),
+ (1, 3),
+ (2, 4),
+ (3, 4),
(4, 4),
- (4, 5), (3, 5),
+ (4, 5),
+ (3, 5),
]);
gr.add_node(0); // add isolated node
- let mut degree_sequence = gr.node_indices()
- .map(|i| degree(&gr, i))
- .collect::<Vec<_>>();
+ let mut degree_sequence = gr
+ .node_indices()
+ .map(|i| degree(&gr, i))
+ .collect::<Vec<_>>();
degree_sequence.sort_by(|x, y| Ord::cmp(y, x));
assert_eq!(°ree_sequence, &[5, 3, 3, 2, 2, 1, 0]);
let mut gr = GraphMap::<_, (), Undirected>::from_edges(&[
(0, 1),
- (1, 2), (1, 3),
- (2, 4), (3, 4),
+ (1, 2),
+ (1, 3),
+ (2, 4),
+ (3, 4),
(4, 4),
- (4, 5), (3, 5),
+ (4, 5),
+ (3, 5),
]);
gr.add_node(6); // add isolated node
- let mut degree_sequence = gr.nodes()
- .map(|i| degree(&gr, i))
- .collect::<Vec<_>>();
+ let mut degree_sequence = gr.nodes().map(|i| degree(&gr, i)).collect::<Vec<_>>();
degree_sequence.sort_by(|x, y| Ord::cmp(y, x));
assert_eq!(°ree_sequence, &[5, 3, 3, 2, 2, 1, 0]);
@@ -1613,10 +1676,11 @@
gr.add_edge(b, a, 5);
// neighbors (edges) are in lifo order, if it's a directed graph
- assert_eq!(gr.neighbors(a).collect::<Vec<_>>(),
- vec![c, a, b]);
- assert_eq!(gr.neighbors_directed(a, Incoming).collect::<Vec<_>>(),
- vec![b, c, c, a]);
+ assert_eq!(gr.neighbors(a).collect::<Vec<_>>(), vec![c, a, b]);
+ assert_eq!(
+ gr.neighbors_directed(a, Incoming).collect::<Vec<_>>(),
+ vec![b, c, c, a]
+ );
}
#[test]
@@ -1631,13 +1695,15 @@
let a = gr.add_node(Record { a: 1, b: r"abc\" });
gr.add_edge(a, a, (1, 2));
let dot_output = format!("{:?}", Dot::new(&gr));
- assert_eq!(dot_output,
- // The single \ turns into four \\\\ because of Debug which turns it to \\ and then escaping each \ to \\.
-r#"digraph {
+ assert_eq!(
+ dot_output,
+ // The single \ turns into four \\\\ because of Debug which turns it to \\ and then escaping each \ to \\.
+ r#"digraph {
0 [label="Record { a: 1, b: \"abc\\\\\" }"]
0 -> 0 [label="(1, 2)"]
}
-"#);
+"#
+ );
}
#[test]
@@ -1700,7 +1766,6 @@
}
assert_eq!(set(po), set(vec![a]));
-
let mut g = Graph::new();
let a = g.add_node("A");
let b = g.add_node("B");
@@ -1813,15 +1878,20 @@
#[test]
fn dfs_visit() {
- use petgraph::visit::{Visitable, VisitMap};
- use petgraph::visit::DfsEvent::*;
- use petgraph::visit::{Time, depth_first_search};
use petgraph::visit::Control;
+ use petgraph::visit::DfsEvent::*;
+ use petgraph::visit::{depth_first_search, Time};
+ use petgraph::visit::{VisitMap, Visitable};
let gr: Graph<(), ()> = Graph::from_edges(&[
- (0, 5), (0, 2), (0, 3), (0, 1),
+ (0, 5),
+ (0, 2),
+ (0, 3),
+ (0, 1),
(1, 3),
- (2, 3), (2, 4),
- (4, 0), (4, 5),
+ (2, 3),
+ (2, 4),
+ (4, 0),
+ (4, 5),
]);
let invalid_time = Time(!0);
@@ -1856,7 +1926,10 @@
assert!(discover_time.iter().all(|x| *x != invalid_time));
assert!(finish_time.iter().all(|x| *x != invalid_time));
assert_eq!(edges.len(), gr.edge_count());
- assert_eq!(edges, set(gr.edge_references().map(|e| (e.source(), e.target()))));
+ assert_eq!(
+ edges,
+ set(gr.edge_references().map(|e| (e.source(), e.target())))
+ );
println!("{:?}", discover_time);
println!("{:?}", finish_time);
@@ -1906,23 +1979,15 @@
assert!(ret.break_value().is_none());
}
-
#[test]
fn filtered_post_order() {
use petgraph::visit::NodeFiltered;
- let mut gr: Graph<(), ()> = Graph::from_edges(&[
- (0, 2),
- (1, 2),
- (0, 3),
- (1, 4),
- (2, 4),
- (4, 5),
- (3, 5),
- ]);
+ let mut gr: Graph<(), ()> =
+ Graph::from_edges(&[(0, 2), (1, 2), (0, 3), (1, 4), (2, 4), (4, 5), (3, 5)]);
// map reachable nodes
let mut dfs = Dfs::new(&gr, n(0));
- while let Some(_) = dfs.next(&gr) { }
+ while let Some(_) = dfs.next(&gr) {}
let map = dfs.discovered;
gr.add_edge(n(0), n(1), ());
@@ -1937,39 +2002,78 @@
#[test]
fn filter_elements() {
- use petgraph::data::Element::{Node, Edge};
- use petgraph::data::FromElements;
+ use petgraph::data::Element::{Edge, Node};
use petgraph::data::ElementIterator;
+ use petgraph::data::FromElements;
let elements = vec![
- Node { weight: "A"},
- Node { weight: "B"},
- Node { weight: "C"},
- Node { weight: "D"},
- Node { weight: "E"},
- Node { weight: "F"},
-
- Edge { source: 0, target: 1, weight: 7 },
- Edge { source: 2, target: 0, weight: 9 },
- Edge { source: 0, target: 3, weight: 14 },
- Edge { source: 1, target: 2, weight: 10 },
- Edge { source: 3, target: 2, weight: 2 },
- Edge { source: 3, target: 4, weight: 9 },
- Edge { source: 1, target: 5, weight: 15 },
- Edge { source: 2, target: 5, weight: 11 },
- Edge { source: 4, target: 5, weight: 6 },
+ Node { weight: "A" },
+ Node { weight: "B" },
+ Node { weight: "C" },
+ Node { weight: "D" },
+ Node { weight: "E" },
+ Node { weight: "F" },
+ Edge {
+ source: 0,
+ target: 1,
+ weight: 7,
+ },
+ Edge {
+ source: 2,
+ target: 0,
+ weight: 9,
+ },
+ Edge {
+ source: 0,
+ target: 3,
+ weight: 14,
+ },
+ Edge {
+ source: 1,
+ target: 2,
+ weight: 10,
+ },
+ Edge {
+ source: 3,
+ target: 2,
+ weight: 2,
+ },
+ Edge {
+ source: 3,
+ target: 4,
+ weight: 9,
+ },
+ Edge {
+ source: 1,
+ target: 5,
+ weight: 15,
+ },
+ Edge {
+ source: 2,
+ target: 5,
+ weight: 11,
+ },
+ Edge {
+ source: 4,
+ target: 5,
+ weight: 6,
+ },
];
let mut g = DiGraph::<_, _>::from_elements(elements.iter().cloned());
println!("{:#?}", g);
assert!(g.contains_edge(n(1), n(5)));
- let g2 = DiGraph::<_, _>::from_elements(elements.iter().cloned().filter_elements(|elt| {
- match elt {
+ let g2 =
+ DiGraph::<_, _>::from_elements(elements.iter().cloned().filter_elements(|elt| match elt {
Node { ref weight } if **weight == "B" => false,
_ => true,
- }
- }));
+ }));
println!("{:#?}", g2);
g.remove_node(n(1));
- assert!(is_isomorphic_matching(&g, &g2, PartialEq::eq, PartialEq::eq));
+ assert!(is_isomorphic_matching(
+ &g,
+ &g2,
+ PartialEq::eq,
+ PartialEq::eq
+ ));
}
#[test]
@@ -1979,29 +2083,29 @@
use petgraph::visit::IntoEdgeReferences;
let gr = UnGraph::<(), _>::from_edges(&[
- // cycle
- (0, 1, 7),
- (1, 2, 9),
- (2, 1, 14),
-
- // cycle
- (3, 4, 10),
- (4, 5, 2),
- (5, 3, 9),
-
- // cross edges
- (0, 3, -1),
- (1, 4, -2),
- (2, 5, -3),
+ // cycle
+ (0, 1, 7),
+ (1, 2, 9),
+ (2, 1, 14),
+ // cycle
+ (3, 4, 10),
+ (4, 5, 2),
+ (5, 3, 9),
+ // cross edges
+ (0, 3, -1),
+ (1, 4, -2),
+ (2, 5, -3),
]);
assert_eq!(connected_components(&gr), 1);
let positive_edges = EdgeFiltered::from_fn(&gr, |edge| *edge.weight() >= 0);
assert_eq!(positive_edges.edge_references().count(), 6);
- assert!(positive_edges.edge_references().all(|edge| *edge.weight() >= 0));
+ assert!(positive_edges
+ .edge_references()
+ .all(|edge| *edge.weight() >= 0));
assert_eq!(connected_components(&positive_edges), 2);
let mut dfs = DfsPostOrder::new(&positive_edges, n(0));
- while let Some(_) = dfs.next(&positive_edges) { }
+ while let Some(_) = dfs.next(&positive_edges) {}
let n = n::<u32>;
for node in &[n(0), n(1), n(2)] {
@@ -2116,37 +2220,79 @@
let doms = dominators::simple_fast(&graph, r);
assert_eq!(doms.root(), r);
- assert_eq!(doms.immediate_dominator(r), None,
- "The root node has no idom");
+ assert_eq!(
+ doms.immediate_dominator(r),
+ None,
+ "The root node has no idom"
+ );
- assert_eq!(doms.immediate_dominator(a), Some(r),
- "r is the immediate dominator of a");
- assert_eq!(doms.immediate_dominator(b), Some(r),
- "r is the immediate dominator of b");
- assert_eq!(doms.immediate_dominator(c), Some(r),
- "r is the immediate dominator of c");
- assert_eq!(doms.immediate_dominator(f), Some(c),
- "c is the immediate dominator of f");
- assert_eq!(doms.immediate_dominator(g), Some(c),
- "c is the immediate dominator of g");
- assert_eq!(doms.immediate_dominator(j), Some(g),
- "g is the immediate dominator of j");
- assert_eq!(doms.immediate_dominator(d), Some(r),
- "r is the immediate dominator of d");
- assert_eq!(doms.immediate_dominator(l), Some(d),
- "d is the immediate dominator of l");
- assert_eq!(doms.immediate_dominator(e), Some(r),
- "r is the immediate dominator of e");
- assert_eq!(doms.immediate_dominator(i), Some(r),
- "r is the immediate dominator of i");
- assert_eq!(doms.immediate_dominator(k), Some(r),
- "r is the immediate dominator of k");
- assert_eq!(doms.immediate_dominator(h), Some(r),
- "r is the immediate dominator of h");
+ assert_eq!(
+ doms.immediate_dominator(a),
+ Some(r),
+ "r is the immediate dominator of a"
+ );
+ assert_eq!(
+ doms.immediate_dominator(b),
+ Some(r),
+ "r is the immediate dominator of b"
+ );
+ assert_eq!(
+ doms.immediate_dominator(c),
+ Some(r),
+ "r is the immediate dominator of c"
+ );
+ assert_eq!(
+ doms.immediate_dominator(f),
+ Some(c),
+ "c is the immediate dominator of f"
+ );
+ assert_eq!(
+ doms.immediate_dominator(g),
+ Some(c),
+ "c is the immediate dominator of g"
+ );
+ assert_eq!(
+ doms.immediate_dominator(j),
+ Some(g),
+ "g is the immediate dominator of j"
+ );
+ assert_eq!(
+ doms.immediate_dominator(d),
+ Some(r),
+ "r is the immediate dominator of d"
+ );
+ assert_eq!(
+ doms.immediate_dominator(l),
+ Some(d),
+ "d is the immediate dominator of l"
+ );
+ assert_eq!(
+ doms.immediate_dominator(e),
+ Some(r),
+ "r is the immediate dominator of e"
+ );
+ assert_eq!(
+ doms.immediate_dominator(i),
+ Some(r),
+ "r is the immediate dominator of i"
+ );
+ assert_eq!(
+ doms.immediate_dominator(k),
+ Some(r),
+ "r is the immediate dominator of k"
+ );
+ assert_eq!(
+ doms.immediate_dominator(h),
+ Some(r),
+ "r is the immediate dominator of h"
+ );
let mut graph = graph.clone();
let z = graph.add_node("z");
let doms = dominators::simple_fast(&graph, r);
- assert_eq!(doms.immediate_dominator(z), None,
- "nodes that aren't reachable from the root do not have an idom");
+ assert_eq!(
+ doms.immediate_dominator(z),
+ None,
+ "nodes that aren't reachable from the root do not have an idom"
+ );
}
diff --git a/tests/graphmap.rs b/tests/graphmap.rs
index c8fbeed..6891cf7 100644
--- a/tests/graphmap.rs
+++ b/tests/graphmap.rs
@@ -5,11 +5,11 @@
use std::fmt;
use petgraph::prelude::*;
-use petgraph::visit::{ Walker, };
+use petgraph::visit::Walker;
-use petgraph::algo::{ dijkstra, };
+use petgraph::algo::dijkstra;
-use petgraph::dot::{Dot, Config};
+use petgraph::dot::{Config, Dot};
#[test]
fn simple() {
@@ -47,13 +47,21 @@
let scores = dijkstra(&gr, a, None, |e| *e.weight());
let mut scores: Vec<_> = scores.into_iter().collect();
scores.sort();
- assert_eq!(scores,
- vec![("A", 0), ("B", 7), ("C", 9), ("D", 11), ("E", 20), ("F", 20)]);
+ assert_eq!(
+ scores,
+ vec![
+ ("A", 0),
+ ("B", 7),
+ ("C", 9),
+ ("D", 11),
+ ("E", 20),
+ ("F", 20)
+ ]
+ );
}
#[test]
-fn remov()
-{
+fn remov() {
let mut g = UnGraphMap::new();
g.add_node(1);
g.add_node(2);
@@ -75,8 +83,7 @@
}
#[test]
-fn remove_directed()
-{
+fn remove_directed() {
let mut g = GraphMap::<_, _, Directed>::with_capacity(0, 0);
g.add_edge(1, 2, -1);
println!("{:?}", g);
@@ -118,13 +125,17 @@
{
let mut cnt = 0;
let mut dfs = Dfs::new(&gr, h);
- while let Some(_) = dfs.next(&gr) { cnt += 1; }
+ while let Some(_) = dfs.next(&gr) {
+ cnt += 1;
+ }
assert_eq!(cnt, 4);
}
{
let mut cnt = 0;
let mut dfs = Dfs::new(&gr, z);
- while let Some(_) = dfs.next(&gr) { cnt += 1; }
+ while let Some(_) = dfs.next(&gr) {
+ cnt += 1;
+ }
assert_eq!(cnt, 1);
}
@@ -146,30 +157,28 @@
gr.add_edge(i, k, 4);
let real_edges: HashSet<_> = gr.all_edges().map(|(a, b, &w)| (a, b, w)).collect();
- let expected_edges: HashSet<_> = vec![
- ("H", "I", 1),
- ("H", "J", 2),
- ("I", "J", 3),
- ("I", "K", 4)
- ].into_iter().collect();
+ let expected_edges: HashSet<_> =
+ vec![("H", "I", 1), ("H", "J", 2), ("I", "J", 3), ("I", "K", 4)]
+ .into_iter()
+ .collect();
assert_eq!(real_edges, expected_edges);
}
#[test]
fn from_edges() {
- let gr = GraphMap::<_, _, Undirected>::from_edges(&[
- ("a", "b", 1),
- ("a", "c", 2),
- ("c", "d", 3),
- ]);
+ let gr =
+ GraphMap::<_, _, Undirected>::from_edges(&[("a", "b", 1), ("a", "c", 2), ("c", "d", 3)]);
assert_eq!(gr.node_count(), 4);
assert_eq!(gr.edge_count(), 3);
assert_eq!(gr[("a", "c")], 2);
let gr = GraphMap::<_, (), Undirected>::from_edges(&[
- (0, 1), (0, 2), (0, 3),
- (1, 2), (1, 3),
+ (0, 1),
+ (0, 2),
+ (0, 3),
+ (1, 2),
+ (1, 3),
(2, 3),
]);
assert_eq!(gr.node_count(), 4);
@@ -182,7 +191,6 @@
println!("{:?}", Dot::with_config(&gr, &[Config::EdgeNoLabel]));
}
-
#[test]
fn graphmap_directed() {
//let root = TypedArena::<Node<_>>::new();
@@ -193,15 +201,7 @@
let c = gr.add_node("C");
let d = gr.add_node("D");
let e = gr.add_node("E");
- let edges = [
- (a, b),
- (a, c),
- (a, d),
- (b, c),
- (c, d),
- (d, e),
- (b, b),
- ];
+ let edges = [(a, b), (a, c), (a, d), (b, c), (c, d), (d, e), (b, b)];
gr.extend(&edges);
// Add reverse edges -- ok!
@@ -215,7 +215,8 @@
}
fn assert_sccs_eq<N>(mut res: Vec<Vec<N>>, mut answer: Vec<Vec<N>>)
- where N: Ord + fmt::Debug,
+where
+ N: Ord + fmt::Debug,
{
// normalize the result and compare with the answer.
for scc in &mut res {
@@ -242,13 +243,13 @@
(7, 5, 7),
(1, 7, 8),
(7, 4, 9),
- (4, 1, 10)]);
-
- assert_sccs_eq(petgraph::algo::kosaraju_scc(&gr), vec![
- vec![0, 3, 6],
- vec![1, 4, 7],
- vec![2, 5, 8],
+ (4, 1, 10),
]);
+
+ assert_sccs_eq(
+ petgraph::algo::kosaraju_scc(&gr),
+ vec![vec![0, 3, 6], vec![1, 4, 7], vec![2, 5, 8]],
+ );
}
#[test]
@@ -264,7 +265,8 @@
(7, 5, 7),
(1, 7, 8),
(7, 4, 9),
- (4, 1, 10)]);
+ (4, 1, 10),
+ ]);
let graph: Graph<_, _, _> = gr.clone().into_graph();
println!("{}", Dot::new(&gr));
@@ -283,11 +285,8 @@
#[test]
fn test_all_edges_mut() {
// graph with edge weights equal to in+out
- let mut graph: GraphMap<_, u32, Directed> = GraphMap::from_edges(&[
- (0, 1, 1),
- (1, 2, 3),
- (2, 0, 2),
- ]);
+ let mut graph: GraphMap<_, u32, Directed> =
+ GraphMap::from_edges(&[(0, 1, 1), (1, 2, 3), (2, 0, 2)]);
// change it so edge weight is equal to 2 * (in+out)
for (start, end, weight) in graph.all_edges_mut() {
diff --git a/tests/iso.rs b/tests/iso.rs
index 539e81b..2ddeb52 100644
--- a/tests/iso.rs
+++ b/tests/iso.rs
@@ -3,19 +3,11 @@
use std::fs::File;
use std::io::prelude::*;
+use petgraph::graph::{edge_index, node_index};
use petgraph::prelude::*;
-use petgraph::{
- EdgeType,
-};
-use petgraph::graph::{
- node_index,
- edge_index,
-};
+use petgraph::EdgeType;
-use petgraph::algo::{
- is_isomorphic,
- is_isomorphic_matching,
-};
+use petgraph::algo::{is_isomorphic, is_isomorphic_matching};
/// Petersen A and B are isomorphic
///
@@ -208,16 +200,12 @@
";
/// Parse a text adjacency matrix format into a directed graph
-fn parse_graph<Ty: EdgeType>(s: &str) -> Graph<(), (), Ty>
-{
+fn parse_graph<Ty: EdgeType>(s: &str) -> Graph<(), (), Ty> {
let mut gr = Graph::with_capacity(0, 0);
let s = s.trim();
let lines = s.lines().filter(|l| !l.is_empty());
for (row, line) in lines.enumerate() {
- for (col, word) in line.split(' ')
- .filter(|s| !s.is_empty())
- .enumerate()
- {
+ for (col, word) in line.split(' ').filter(|s| !s.is_empty()).enumerate() {
let has_edge = word.parse::<i32>().unwrap();
assert!(has_edge == 0 || has_edge == 1);
if has_edge == 0 {
@@ -241,11 +229,11 @@
}
/// Parse a file in adjacency matrix format into a directed graph
-fn graph_from_file(path: &str) -> Graph<(), (), Directed>
-{
+fn graph_from_file(path: &str) -> Graph<(), (), Directed> {
let mut f = File::open(path).expect("file not found");
let mut contents = String::new();
- f.read_to_string(&mut contents).expect("failed to read from file");
+ f.read_to_string(&mut contents)
+ .expect("failed to read from file");
parse_graph(&contents)
}
@@ -269,8 +257,7 @@
*/
#[test]
-fn petersen_iso()
-{
+fn petersen_iso() {
// The correct isomorphism is
// 0 => 0, 1 => 3, 2 => 1, 3 => 4, 5 => 2, 6 => 5, 7 => 7, 8 => 6, 9 => 8, 4 => 9
let peta = str_to_digraph(PETERSEN_A);
@@ -286,8 +273,7 @@
}
#[test]
-fn petersen_undir_iso()
-{
+fn petersen_undir_iso() {
// The correct isomorphism is
// 0 => 0, 1 => 3, 2 => 1, 3 => 4, 5 => 2, 6 => 5, 7 => 7, 8 => 6, 9 => 8, 4 => 9
let peta = str_to_digraph(PETERSEN_A);
@@ -297,8 +283,7 @@
}
#[test]
-fn full_iso()
-{
+fn full_iso() {
let a = str_to_graph(FULL_A);
let b = str_to_graph(FULL_B);
@@ -306,8 +291,7 @@
}
#[test]
-fn praust_dir_no_iso()
-{
+fn praust_dir_no_iso() {
let a = str_to_digraph(PRAUST_A);
let b = str_to_digraph(PRAUST_B);
@@ -315,8 +299,7 @@
}
#[test]
-fn praust_undir_no_iso()
-{
+fn praust_undir_no_iso() {
let a = str_to_graph(PRAUST_A);
let b = str_to_graph(PRAUST_B);
@@ -324,8 +307,7 @@
}
#[test]
-fn coxeter_di_iso()
-{
+fn coxeter_di_iso() {
// The correct isomorphism is
let a = str_to_digraph(COXETER_A);
let b = str_to_digraph(COXETER_B);
@@ -333,8 +315,7 @@
}
#[test]
-fn coxeter_undi_iso()
-{
+fn coxeter_undi_iso() {
// The correct isomorphism is
let a = str_to_graph(COXETER_A);
let b = str_to_graph(COXETER_B);
@@ -342,40 +323,35 @@
}
#[test]
-fn g14_dir_not_iso()
-{
+fn g14_dir_not_iso() {
let a = str_to_digraph(G1D);
let b = str_to_digraph(G4D);
assert!(!petgraph::algo::is_isomorphic(&a, &b));
}
#[test]
-fn g14_undir_not_iso()
-{
+fn g14_undir_not_iso() {
let a = str_to_digraph(G1U);
let b = str_to_digraph(G4U);
assert!(!petgraph::algo::is_isomorphic(&a, &b));
}
#[test]
-fn g12_undir_iso()
-{
+fn g12_undir_iso() {
let a = str_to_digraph(G1U);
let b = str_to_digraph(G2U);
assert!(petgraph::algo::is_isomorphic(&a, &b));
}
#[test]
-fn g3_not_iso()
-{
+fn g3_not_iso() {
let a = str_to_digraph(G3_1);
let b = str_to_digraph(G3_2);
assert!(!petgraph::algo::is_isomorphic(&a, &b));
}
#[test]
-fn g8_not_iso()
-{
+fn g8_not_iso() {
let a = str_to_digraph(G8_1);
let b = str_to_digraph(G8_2);
assert_eq!(a.edge_count(), b.edge_count());
@@ -384,8 +360,7 @@
}
#[test]
-fn s12_not_iso()
-{
+fn s12_not_iso() {
let a = str_to_digraph(S1);
let b = str_to_digraph(S2);
assert_eq!(a.edge_count(), b.edge_count());
@@ -394,8 +369,7 @@
}
#[test]
-fn iso1()
-{
+fn iso1() {
let mut g0 = Graph::<_, ()>::new();
let mut g1 = Graph::<_, ()>::new();
assert!(petgraph::algo::is_isomorphic(&g0, &g1));
@@ -418,8 +392,7 @@
}
#[test]
-fn iso2()
-{
+fn iso2() {
let mut g0 = Graph::<_, ()>::new();
let mut g1 = Graph::<_, ()>::new();
@@ -467,19 +440,24 @@
#[test]
fn iso_matching() {
- let g0 = Graph::<(), _>::from_edges(&[
- (0, 0, 1),
- (0, 1, 2),
- (0, 2, 3),
- (1, 2, 4),
- ]);
+ let g0 = Graph::<(), _>::from_edges(&[(0, 0, 1), (0, 1, 2), (0, 2, 3), (1, 2, 4)]);
let mut g1 = g0.clone();
g1[edge_index(0)] = 0;
- assert!(!is_isomorphic_matching(&g0, &g1, |x, y| x == y, |x, y| x == y));
+ assert!(!is_isomorphic_matching(
+ &g0,
+ &g1,
+ |x, y| x == y,
+ |x, y| x == y
+ ));
let mut g2 = g0.clone();
g2[edge_index(1)] = 0;
- assert!(!is_isomorphic_matching(&g0, &g2, |x, y| x == y, |x, y| x == y));
+ assert!(!is_isomorphic_matching(
+ &g0,
+ &g2,
+ |x, y| x == y,
+ |x, y| x == y
+ ));
}
#[test]
@@ -501,27 +479,12 @@
#[should_panic]
#[test]
fn iso_multigraph_failure() {
- let g0 = Graph::<(), ()>::from_edges(&[
- (0, 0),
- (0, 0),
- (0, 1),
- (1, 1),
- (1, 1),
- (1, 0),
- ]);
+ let g0 = Graph::<(), ()>::from_edges(&[(0, 0), (0, 0), (0, 1), (1, 1), (1, 1), (1, 0)]);
- let g1 = Graph::<(), ()>::from_edges(&[
- (0, 0),
- (0, 1),
- (0, 1),
- (1, 1),
- (1, 0),
- (1, 0),
- ]);
+ let g1 = Graph::<(), ()>::from_edges(&[(0, 0), (0, 1), (0, 1), (1, 1), (1, 0), (1, 0)]);
assert!(!is_isomorphic(&g0, &g1));
}
-
/// Isomorphic pair
const COXETER_A: &str = "
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
@@ -588,4 +551,3 @@
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0
";
-
diff --git a/tests/quickcheck.rs b/tests/quickcheck.rs
index 2831a2d..f95eb1c 100644
--- a/tests/quickcheck.rs
+++ b/tests/quickcheck.rs
@@ -1,11 +1,13 @@
-#![cfg(feature="quickcheck")]
-#[macro_use] extern crate quickcheck;
-extern crate rand;
+#![cfg(feature = "quickcheck")]
+#[macro_use]
+extern crate quickcheck;
extern crate petgraph;
-#[macro_use] extern crate defmac;
+extern crate rand;
+#[macro_use]
+extern crate defmac;
-extern crate odds;
extern crate itertools;
+extern crate odds;
mod utils;
@@ -15,45 +17,29 @@
use std::collections::HashSet;
use std::hash::Hash;
-use rand::Rng;
use itertools::assert_equal;
use itertools::cloned;
+use rand::Rng;
-use petgraph::prelude::*;
-use petgraph::{
- EdgeType,
-};
-use petgraph::dot::{Dot, Config};
use petgraph::algo::{
- condensation,
- min_spanning_tree,
- is_cyclic_undirected,
- is_cyclic_directed,
- is_isomorphic,
- is_isomorphic_matching,
- toposort,
- kosaraju_scc,
- tarjan_scc,
- dijkstra,
- bellman_ford,
-};
-use petgraph::visit::{Topo, Reversed};
-use petgraph::visit::{
- IntoNodeReferences,
- IntoEdgeReferences,
- NodeIndexable,
- EdgeRef,
+ bellman_ford, condensation, dijkstra, is_cyclic_directed, is_cyclic_undirected, is_isomorphic,
+ is_isomorphic_matching, kosaraju_scc, min_spanning_tree, tarjan_scc, toposort,
};
use petgraph::data::FromElements;
-use petgraph::graph::{IndexType, node_index, edge_index};
-use petgraph::graphmap::{
- NodeTrait,
-};
+use petgraph::dot::{Config, Dot};
+use petgraph::graph::{edge_index, node_index, IndexType};
+use petgraph::graphmap::NodeTrait;
+use petgraph::prelude::*;
+use petgraph::visit::{EdgeRef, IntoEdgeReferences, IntoNodeReferences, NodeIndexable};
+use petgraph::visit::{Reversed, Topo};
+use petgraph::EdgeType;
fn mst_graph<N, E, Ty, Ix>(g: &Graph<N, E, Ty, Ix>) -> Graph<N, E, Undirected, Ix>
- where Ty: EdgeType,
- Ix: IndexType,
- N: Clone, E: Clone + PartialOrd,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
+ N: Clone,
+ E: Clone + PartialOrd,
{
Graph::from_elements(min_spanning_tree(&g))
}
@@ -101,34 +87,43 @@
}
fn assert_graph_consistent<N, E, Ty, Ix>(g: &Graph<N, E, Ty, Ix>)
- where Ty: EdgeType,
- Ix: IndexType,
+where
+ Ty: EdgeType,
+ Ix: IndexType,
{
assert_eq!(g.node_count(), g.node_indices().count());
assert_eq!(g.edge_count(), g.edge_indices().count());
for edge in g.raw_edges() {
- assert!(g.find_edge(edge.source(), edge.target()).is_some(),
- "Edge not in graph! {:?} to {:?}", edge.source(), edge.target());
+ assert!(
+ g.find_edge(edge.source(), edge.target()).is_some(),
+ "Edge not in graph! {:?} to {:?}",
+ edge.source(),
+ edge.target()
+ );
}
}
#[test]
fn reverse_directed() {
fn prop<Ty: EdgeType>(mut g: Graph<(), (), Ty>) -> bool {
- let node_outdegrees = g.node_indices()
- .map(|i| g.neighbors_directed(i, Outgoing).count())
- .collect::<Vec<_>>();
- let node_indegrees = g.node_indices()
- .map(|i| g.neighbors_directed(i, Incoming).count())
- .collect::<Vec<_>>();
+ let node_outdegrees = g
+ .node_indices()
+ .map(|i| g.neighbors_directed(i, Outgoing).count())
+ .collect::<Vec<_>>();
+ let node_indegrees = g
+ .node_indices()
+ .map(|i| g.neighbors_directed(i, Incoming).count())
+ .collect::<Vec<_>>();
g.reverse();
- let new_outdegrees = g.node_indices()
- .map(|i| g.neighbors_directed(i, Outgoing).count())
- .collect::<Vec<_>>();
- let new_indegrees = g.node_indices()
- .map(|i| g.neighbors_directed(i, Incoming).count())
- .collect::<Vec<_>>();
+ let new_outdegrees = g
+ .node_indices()
+ .map(|i| g.neighbors_directed(i, Outgoing).count())
+ .collect::<Vec<_>>();
+ let new_indegrees = g
+ .node_indices()
+ .map(|i| g.neighbors_directed(i, Incoming).count())
+ .collect::<Vec<_>>();
assert_eq!(node_outdegrees, new_indegrees);
assert_eq!(node_indegrees, new_outdegrees);
assert_graph_consistent(&g);
@@ -160,14 +155,21 @@
assert_eq!(num_pos_post, g.node_count());
// check against filter_map
- let filtered = og.filter_map(|_, w| if *w >= 0 { Some(*w) } else { None },
- |_, w| Some(*w));
+ let filtered = og.filter_map(
+ |_, w| if *w >= 0 { Some(*w) } else { None },
+ |_, w| Some(*w),
+ );
assert_eq!(g.node_count(), filtered.node_count());
/*
println!("Iso of graph with nodes={}, edges={}",
g.node_count(), g.edge_count());
*/
- assert!(is_isomorphic_matching(&filtered, &g, PartialEq::eq, PartialEq::eq));
+ assert!(is_isomorphic_matching(
+ &filtered,
+ &g,
+ PartialEq::eq,
+ PartialEq::eq
+ ));
true
}
@@ -200,7 +202,8 @@
// check against filter_map
let filtered = og.filter_map(
|_, w| Some(*w),
- |_, w| if *w >= 0 { Some(*w) } else { None });
+ |_, w| if *w >= 0 { Some(*w) } else { None },
+ );
assert_eq!(g.node_count(), filtered.node_count());
assert!(is_isomorphic(&filtered, &g));
}
@@ -235,7 +238,8 @@
// check against filter_map
let filtered = og.filter_map(
|_, w| Some(*w),
- |_, w| if *w >= 0 { Some(*w) } else { None });
+ |_, w| if *w >= 0 { Some(*w) } else { None },
+ );
assert_eq!(g.node_count(), filtered.node_count());
}
true
@@ -267,14 +271,17 @@
// Add edges
for i in g.edge_indices() {
let (s, t) = g.edge_endpoints(i).unwrap();
- ng.add_edge(map[s.index()],
- map[t.index()],
- g[i]);
+ ng.add_edge(map[s.index()], map[t.index()], g[i]);
}
if g.node_count() < 20 && g.edge_count() < 50 {
assert!(is_isomorphic(&g, &ng));
}
- assert!(is_isomorphic_matching(&g, &ng, PartialEq::eq, PartialEq::eq));
+ assert!(is_isomorphic_matching(
+ &g,
+ &ng,
+ PartialEq::eq,
+ PartialEq::eq
+ ));
}
true
}
@@ -297,9 +304,19 @@
ng[j] = (g[j] == 0) as i8;
}
if i.index() < g.node_count() || j.index() < g.edge_count() {
- assert!(!is_isomorphic_matching(&g, &ng, PartialEq::eq, PartialEq::eq));
+ assert!(!is_isomorphic_matching(
+ &g,
+ &ng,
+ PartialEq::eq,
+ PartialEq::eq
+ ));
} else {
- assert!(is_isomorphic_matching(&g, &ng, PartialEq::eq, PartialEq::eq));
+ assert!(is_isomorphic_matching(
+ &g,
+ &ng,
+ PartialEq::eq,
+ PartialEq::eq
+ ));
}
true
}
@@ -378,7 +395,12 @@
assert!(g.remove_edge(ex).is_some());
}
//assert_graph_consistent(&g);
- assert!(g.find_edge(a, b).is_none(), "failed to remove edge {:?} from graph {:?}", (a, b), g);
+ assert!(
+ g.find_edge(a, b).is_none(),
+ "failed to remove edge {:?} from graph {:?}",
+ (a, b),
+ g
+ );
assert!(g.neighbors(a).find(|x| *x == b).is_none());
if !g.is_directed() {
assert!(g.find_edge(b, a).is_none());
@@ -392,17 +414,30 @@
}
fn assert_graphmap_consistent<N, E, Ty>(g: &GraphMap<N, E, Ty>)
- where Ty: EdgeType,
- N: NodeTrait + fmt::Debug,
+where
+ Ty: EdgeType,
+ N: NodeTrait + fmt::Debug,
{
for (a, b, _weight) in g.all_edges() {
- assert!(g.contains_edge(a, b),
- "Edge not in graph! {:?} to {:?}", a, b);
- assert!(g.neighbors(a).find(|x| *x == b).is_some(),
- "Edge {:?} not in neighbor list for {:?}", (a, b), a);
+ assert!(
+ g.contains_edge(a, b),
+ "Edge not in graph! {:?} to {:?}",
+ a,
+ b
+ );
+ assert!(
+ g.neighbors(a).find(|x| *x == b).is_some(),
+ "Edge {:?} not in neighbor list for {:?}",
+ (a, b),
+ a
+ );
if !g.is_directed() {
- assert!(g.neighbors(b).find(|x| *x == a).is_some(),
- "Edge {:?} not in neighbor list for {:?}", (b, a), b);
+ assert!(
+ g.neighbors(b).find(|x| *x == a).is_some(),
+ "Edge {:?} not in neighbor list for {:?}",
+ (b, a),
+ b
+ );
}
}
}
@@ -417,9 +452,8 @@
assert_eq!(contains, g.contains_edge(b, a));
}
assert_eq!(g.remove_edge(a, b).is_some(), contains);
- assert!(!g.contains_edge(a, b) &&
- g.neighbors(a).find(|x| *x == b).is_none());
- //(g.is_directed() || g.neighbors(b).find(|x| *x == a).is_none()));
+ assert!(!g.contains_edge(a, b) && g.neighbors(a).find(|x| *x == b).is_none());
+ //(g.is_directed() || g.neighbors(b).find(|x| *x == a).is_none()));
assert!(g.remove_edge(a, b).is_none());
assert_graphmap_consistent(&g);
true
@@ -433,9 +467,9 @@
fn prop(mut g: UnGraphMap<i8, ()>, a: i8, b: i8) -> bool {
assert_eq!(g.contains_edge(a, b), g.add_edge(a, b, ()).is_some());
g.remove_edge(a, b);
- !g.contains_edge(a, b) &&
- g.neighbors(a).find(|x| *x == b).is_none() &&
- g.neighbors(b).find(|x| *x == a).is_none()
+ !g.contains_edge(a, b)
+ && g.neighbors(a).find(|x| *x == b).is_none()
+ && g.neighbors(b).find(|x| *x == a).is_none()
}
quickcheck::quickcheck(prop as fn(_, _, _) -> bool);
}
@@ -481,7 +515,6 @@
}
}
-
quickcheck! {
// Reversed edges gives the same sccs (when sorted)
fn graph_reverse_sccs(g: Graph<(), ()>) -> bool {
@@ -565,17 +598,18 @@
// shrink the graph by splitting it in two by a very
// simple algorithm, just even and odd node indices
- fn shrink(&self) -> Box<dyn Iterator<Item=Self>> {
+ fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
let self_ = self.clone();
Box::new((0..2).filter_map(move |x| {
- let gr = self_.0.filter_map(|i, w| {
- if i.index() % 2 == x {
- Some(w.clone())
- } else {
- None
- }
- },
- |_, w| Some(w.clone())
+ let gr = self_.0.filter_map(
+ |i, w| {
+ if i.index() % 2 == x {
+ Some(w.clone())
+ } else {
+ None
+ }
+ },
+ |_, w| Some(w.clone()),
);
// make sure we shrink
if gr.node_count() < self_.0.node_count() {
@@ -589,7 +623,11 @@
fn is_topo_order<N>(gr: &Graph<N, (), Directed>, order: &[NodeIndex]) -> bool {
if gr.node_count() != order.len() {
- println!("Graph ({}) and count ({}) had different amount of nodes.", gr.node_count(), order.len());
+ println!(
+ "Graph ({}) and count ({}) had different amount of nodes.",
+ gr.node_count(),
+ order.len()
+ );
return false;
}
// check all the edges of the graph
@@ -606,10 +644,13 @@
true
}
-
fn subset_is_topo_order<N>(gr: &Graph<N, (), Directed>, order: &[NodeIndex]) -> bool {
if gr.node_count() < order.len() {
- println!("Graph (len={}) had less nodes than order (len={})", gr.node_count(), order.len());
+ println!(
+ "Graph (len={}) had less nodes than order (len={})",
+ gr.node_count(),
+ order.len()
+ );
return false;
}
// check all the edges of the graph
@@ -711,13 +752,13 @@
}
fn set<I>(iter: I) -> HashSet<I::Item>
- where I: IntoIterator,
- I::Item: Hash + Eq,
+where
+ I: IntoIterator,
+ I::Item: Hash + Eq,
{
iter.into_iter().collect()
}
-
quickcheck! {
fn dfs_visit(gr: Graph<(), ()>, node: usize) -> bool {
use petgraph::visit::{Visitable, VisitMap};
diff --git a/tests/stable_graph.rs b/tests/stable_graph.rs
index 8645865..9ac401e 100644
--- a/tests/stable_graph.rs
+++ b/tests/stable_graph.rs
@@ -1,20 +1,17 @@
#![cfg(feature = "stable_graph")]
-extern crate petgraph;
extern crate itertools;
-#[macro_use] extern crate defmac;
+extern crate petgraph;
+#[macro_use]
+extern crate defmac;
+use itertools::assert_equal;
+use petgraph::algo::{kosaraju_scc, min_spanning_tree, tarjan_scc};
+use petgraph::dot::Dot;
use petgraph::prelude::*;
use petgraph::stable_graph::node_index as n;
+use petgraph::visit::{IntoEdgeReferences, IntoNodeReferences, NodeIndexable};
use petgraph::EdgeType;
-use petgraph::algo::{kosaraju_scc, tarjan_scc, min_spanning_tree};
-use petgraph::visit::{
- NodeIndexable,
- IntoNodeReferences,
- IntoEdgeReferences,
-};
-use petgraph::dot::Dot;
-use itertools::assert_equal;
#[test]
fn node_indices() {
@@ -72,11 +69,15 @@
(6, 0),
(0, 3),
(3, 6),
- (8, 6), (8, 2),
- (2, 5), (5, 8), (7, 5),
+ (8, 6),
+ (8, 2),
+ (2, 5),
+ (5, 8),
+ (7, 5),
(1, 7),
(7, 4),
- (4, 1)]);
+ (4, 1),
+ ]);
// make an identical replacement of n(4) and leave a hole
let x = gr.add_node(());
gr.add_edge(n(7), x, ());
@@ -91,28 +92,34 @@
println!("{:?}", gr);
let x = n(gr.node_bound() - 1);
- assert_sccs_eq(kosaraju_scc(&gr), vec![
- vec![n(0), n(3), n(6)],
- vec![n(1), n(7), x ],
- vec![n(2), n(5), n(8)],
- ]);
+ assert_sccs_eq(
+ kosaraju_scc(&gr),
+ vec![
+ vec![n(0), n(3), n(6)],
+ vec![n(1), n(7), x],
+ vec![n(2), n(5), n(8)],
+ ],
+ );
}
-
#[test]
fn test_tarjan_scc() {
let gr = scc_graph();
let x = n(gr.node_bound() - 1);
- assert_sccs_eq(tarjan_scc(&gr), vec![
- vec![n(0), n(3), n(6)],
- vec![n(1), n(7), x ],
- vec![n(2), n(5), n(8)],
- ]);
+ assert_sccs_eq(
+ tarjan_scc(&gr),
+ vec![
+ vec![n(0), n(3), n(6)],
+ vec![n(1), n(7), x],
+ vec![n(2), n(5), n(8)],
+ ],
+ );
}
fn make_graph<Ty>() -> StableGraph<(), i32, Ty>
- where Ty: EdgeType,
+where
+ Ty: EdgeType,
{
let mut gr = StableGraph::default();
let mut c = 0..;
@@ -129,7 +136,8 @@
(1, 7, e()),
(7, 4, e()),
(8, 6, e()), // parallel edge
- (4, 1, e())]);
+ (4, 1, e()),
+ ]);
// make an identical replacement of n(4) and leave a hole
let x = gr.add_node(());
gr.add_edge(n(7), x, e());
@@ -164,7 +172,10 @@
fn test_edges_undirected() {
let gr = make_graph::<Undirected>();
let x = n(9);
- assert_equal(edges!(gr, x), vec![(x, 16), (x, 14), (n(1), 13), (n(7), 12)]);
+ assert_equal(
+ edges!(gr, x),
+ vec![(x, 16), (x, 14), (n(1), 13), (n(7), 12)],
+ );
assert_equal(edges!(gr, n(0)), vec![(n(3), 1)]);
assert_equal(edges!(gr, n(4)), vec![]);
}
@@ -173,11 +184,13 @@
fn test_edge_iterators_directed() {
let gr = make_graph::<Directed>();
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Outgoing),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Outgoing), gr.edges(i));
for edge in gr.edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "outgoing edges should have a fixed source"
+ );
}
}
let mut incoming = vec![Vec::new(); gr.node_bound()];
@@ -192,9 +205,14 @@
for i in gr.node_indices() {
itertools::assert_equal(
gr.edges_directed(i, Incoming).map(|e| e.source()),
- incoming[i.index()].iter().rev().cloned());
+ incoming[i.index()].iter().rev().cloned(),
+ );
for edge in gr.edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "incoming edges should have a fixed target"
+ );
}
}
}
@@ -203,25 +221,29 @@
fn test_edge_iterators_undir() {
let gr = make_graph::<Undirected>();
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Outgoing),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Outgoing), gr.edges(i));
for edge in gr.edges_directed(i, Outgoing) {
- assert_eq!(edge.source(), i, "outgoing edges should have a fixed source");
+ assert_eq!(
+ edge.source(),
+ i,
+ "outgoing edges should have a fixed source"
+ );
}
}
for i in gr.node_indices() {
- itertools::assert_equal(
- gr.edges_directed(i, Incoming),
- gr.edges(i));
+ itertools::assert_equal(gr.edges_directed(i, Incoming), gr.edges(i));
for edge in gr.edges_directed(i, Incoming) {
- assert_eq!(edge.target(), i, "incoming edges should have a fixed target");
+ assert_eq!(
+ edge.target(),
+ i,
+ "incoming edges should have a fixed target"
+ );
}
}
}
#[test]
-#[should_panic(expected="is not a node")]
+#[should_panic(expected = "is not a node")]
fn add_edge_vacant() {
let mut g = StableGraph::<_, _>::new();
let a = g.add_node(0);
@@ -232,7 +254,7 @@
}
#[test]
-#[should_panic(expected="is not a node")]
+#[should_panic(expected = "is not a node")]
fn add_edge_oob() {
let mut g = StableGraph::<_, _>::new();
let a = g.add_node(0);
@@ -245,9 +267,7 @@
fn test_node_references() {
let gr = scc_graph();
- itertools::assert_equal(
- gr.node_references().map(|(i, _)| i),
- gr.node_indices());
+ itertools::assert_equal(gr.node_references().map(|(i, _)| i), gr.node_indices());
}
#[test]
@@ -257,40 +277,19 @@
let b = g.add_node(1);
let c = g.add_node(2);
let d = g.add_node(3);
- g.extend_with_edges(&[
- (a, b, 1),
- (a, c, 2),
- (b, c, 3),
- (c, c, 4),
- (a, d, 5),
- ]);
+ g.extend_with_edges(&[(a, b, 1), (a, c, 2), (b, c, 3), (c, c, 4), (a, d, 5)]);
g.remove_node(b);
- itertools::assert_equal(
- g.neighbors(a),
- vec![d, c],
- );
- itertools::assert_equal(
- g.neighbors(c),
- vec![c, a],
- );
- itertools::assert_equal(
- g.neighbors(d),
- vec![a],
- );
+ itertools::assert_equal(g.neighbors(a), vec![d, c]);
+ itertools::assert_equal(g.neighbors(c), vec![c, a]);
+ itertools::assert_equal(g.neighbors(d), vec![a]);
// the node that was removed
- itertools::assert_equal(
- g.neighbors(b),
- vec![],
- );
+ itertools::assert_equal(g.neighbors(b), vec![]);
// remove one more
g.remove_node(c);
- itertools::assert_equal(
- g.neighbors(c),
- vec![],
- );
+ itertools::assert_equal(g.neighbors(c), vec![]);
}
#[test]
@@ -301,14 +300,16 @@
gr.add_edge(a, a, "10");
gr.add_edge(a, b, "20");
let dot_output = format!("{}", Dot::new(&gr));
- assert_eq!(dot_output,
-r#"digraph {
+ assert_eq!(
+ dot_output,
+ r#"digraph {
0 [label="x"]
1 [label="y"]
0 -> 0 [label="10"]
0 -> 1 [label="20"]
}
-"#);
+"#
+ );
}
defmac!(iter_eq a, b => a.eq(b));
@@ -355,8 +356,8 @@
assert!(edges_eq!(gr5, ans));
}
-use petgraph::stable_graph::StableGraph;
use petgraph::data::FromElements;
+use petgraph::stable_graph::StableGraph;
#[test]
fn from_min_spanning_tree() {
@@ -372,5 +373,5 @@
for i in 0..3 {
let _ = g.remove_node(nodes[i]);
}
- let _ = StableGraph::<(),(),Undirected,usize>::from_elements(min_spanning_tree(&g));
+ let _ = StableGraph::<(), (), Undirected, usize>::from_elements(min_spanning_tree(&g));
}
diff --git a/tests/unionfind.rs b/tests/unionfind.rs
index ff8a51f..8b54db7 100644
--- a/tests/unionfind.rs
+++ b/tests/unionfind.rs
@@ -1,9 +1,9 @@
-extern crate rand;
extern crate petgraph;
+extern crate rand;
-use rand::{Rng, thread_rng, ChaChaRng, SeedableRng};
-use std::collections::HashSet;
use petgraph::unionfind::UnionFind;
+use rand::{thread_rng, ChaChaRng, Rng, SeedableRng};
+use std::collections::HashSet;
#[test]
fn uf_test() {
@@ -90,8 +90,7 @@
}
#[test]
-fn labeling()
-{
+fn labeling() {
let mut u = UnionFind::<u32>::new(48);
for i in 0..24 {
u.union(i + 1, i);
diff --git a/tests/utils/mod.rs b/tests/utils/mod.rs
index 09de454..95b9b37 100644
--- a/tests/utils/mod.rs
+++ b/tests/utils/mod.rs
@@ -1,5 +1,3 @@
-
-
mod qc;
pub use self::qc::*;
diff --git a/tests/utils/qc.rs b/tests/utils/qc.rs
index 2715ab1..f335625 100644
--- a/tests/utils/qc.rs
+++ b/tests/utils/qc.rs
@@ -1,4 +1,3 @@
-
use quickcheck::{Arbitrary, Gen, StdGen};
use std::ops::Deref;
@@ -8,19 +7,21 @@
impl<T> Deref for Small<T> {
type Target = T;
- fn deref(&self) -> &T { &self.0 }
+ fn deref(&self) -> &T {
+ &self.0
+ }
}
impl<T> Arbitrary for Small<T>
- where T: Arbitrary
+where
+ T: Arbitrary,
{
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let sz = g.size() / 2;
Small(T::arbitrary(&mut StdGen::new(g, sz)))
}
- fn shrink(&self) -> Box<dyn Iterator<Item=Self>> {
+ fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
Box::new((**self).shrink().map(Small))
}
}
-