petgraph/graph_impl/stable_graph/
mod.rs

1//! `StableGraph` keeps indices stable across removals.
2//!
3//! Depends on `feature = "stable_graph"`.
4//!
5
6use std::cmp;
7use std::fmt;
8use std::iter;
9use std::marker::PhantomData;
10use std::mem::replace;
11use std::mem::size_of;
12use std::ops::{Index, IndexMut};
13use std::slice;
14
15use {
16    Graph,
17    EdgeType,
18    Directed,
19    Undirected,
20    Direction,
21    Incoming,
22    Outgoing,
23};
24
25use iter_format::{
26    IterFormatExt,
27    NoPretty,
28    DebugMap,
29};
30use iter_utils::IterUtilsExt;
31
32use super::{
33    Edge,
34    index_twice,
35    Node,
36    DIRECTIONS,
37    Pair,
38    Frozen,
39};
40use IntoWeightedEdge;
41use visit::{
42    EdgeRef,
43    IntoNodeReferences,
44    IntoEdges,
45    IntoEdgesDirected,
46    IntoEdgeReferences,
47    NodeIndexable,
48};
49
50// reexport those things that are shared with Graph
51#[doc(no_inline)]
52pub use graph::{
53    NodeIndex,
54    EdgeIndex,
55    GraphIndex,
56    IndexType,
57    DefaultIx,
58    node_index,
59    edge_index,
60};
61
62use util::enumerate;
63
64#[cfg(feature = "serde-1")]
65mod serialization;
66
67/// `StableGraph<N, E, Ty, Ix>` is a graph datastructure using an adjacency
68/// list representation.
69///
70/// The graph **does not invalidate** any unrelated node or edge indices when
71/// items are removed.
72///
73/// `StableGraph` is parameterized over:
74///
75/// - Associated data `N` for nodes and `E` for edges, also called *weights*.
76///   The associated data can be of arbitrary type.
77/// - Edge type `Ty` that determines whether the graph edges are directed or undirected.
78/// - Index type `Ix`, which determines the maximum size of the graph.
79///
80/// The graph uses **O(|V| + |E|)** space, and allows fast node and edge insert
81/// and efficient graph search.
82///
83/// It implements **O(e')** edge lookup and edge and node removals, where **e'**
84/// is some local measure of edge count.
85///
86/// - Nodes and edges are each numbered in an interval from *0* to some number
87/// *m*, but *not all* indices in the range are valid, since gaps are formed
88/// by deletions.
89///
90/// - You can select graph index integer type after the size of the graph. A smaller
91/// size may have better performance.
92///
93/// - Using indices allows mutation while traversing the graph, see `Dfs`.
94///
95/// - The `StableGraph` is a regular rust collection and is `Send` and `Sync`
96/// (as long as associated data `N` and `E` are).
97///
98/// - Indices don't allow as much compile time checking as references.
99///
100/// Depends on crate feature `stable_graph` (default). *Stable Graph is still
101/// missing a few methods compared to Graph. You can contribute to help it
102/// achieve parity.*
103pub struct StableGraph<N, E, Ty = Directed, Ix = DefaultIx>
104{
105    g: Graph<Option<N>, Option<E>, Ty, Ix>,
106    node_count: usize,
107    edge_count: usize,
108
109    // node and edge free lists (both work the same way)
110    //
111    // free_node, if not NodeIndex::end(), points to a node index
112    // that is vacant (after a deletion).  The next item in the list is kept in
113    // that Node's Node.next[0] field. For Node, it's a node index stored
114    // in an EdgeIndex location, and the _into_edge()/_into_node() methods
115    // convert.
116    free_node: NodeIndex<Ix>,
117    free_edge: EdgeIndex<Ix>,
118}
119
120/// A `StableGraph` with directed edges.
121///
122/// For example, an edge from *1* to *2* is distinct from an edge from *2* to
123/// *1*.
124pub type StableDiGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Directed, Ix>;
125
126/// A `StableGraph` with undirected edges.
127///
128/// For example, an edge between *1* and *2* is equivalent to an edge between
129/// *2* and *1*.
130pub type StableUnGraph<N, E, Ix = DefaultIx> = StableGraph<N, E, Undirected, Ix>;
131
132impl<N, E, Ty, Ix> fmt::Debug for StableGraph<N, E, Ty, Ix>
133    where N: fmt::Debug,
134          E: fmt::Debug,
135          Ty: EdgeType,
136          Ix: IndexType,
137{
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        let etype = if self.is_directed() { "Directed" } else { "Undirected" };
140        let mut fmt_struct = f.debug_struct("StableGraph");
141        fmt_struct.field("Ty", &etype);
142        fmt_struct.field("node_count", &self.node_count);
143        fmt_struct.field("edge_count", &self.edge_count);
144        if self.g.edges.iter().any(|e| e.weight.is_some()) {
145            fmt_struct.field("edges", &self.g.edges.iter()
146                .filter(|e| e.weight.is_some())
147                .map(|e| NoPretty((e.source().index(), e.target().index())))
148                .format(", "));
149        }
150        // skip weights if they are ZST!
151        if size_of::<N>() != 0 {
152            fmt_struct.field("node weights",
153            &DebugMap(||
154                self.g.nodes.iter()
155                    .map(|n| n.weight.as_ref())
156                    .enumerate()
157                    .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
158                   ));
159        }
160        if size_of::<E>() != 0 {
161            fmt_struct.field("edge weights",
162            &DebugMap(||
163                self.g.edges.iter()
164                    .map(|n| n.weight.as_ref())
165                    .enumerate()
166                    .filter_map(|(i, wo)| wo.map(move |w| (i, w)))
167                   ));
168        }
169        fmt_struct.field("free_node", &self.free_node);
170        fmt_struct.field("free_edge", &self.free_edge);
171        fmt_struct.finish()
172    }
173}
174
175
176impl<N, E> StableGraph<N, E, Directed> {
177    /// Create a new `StableGraph` with directed edges.
178    ///
179    /// This is a convenience method. See `StableGraph::with_capacity`
180    /// or `StableGraph::default` for a constructor that is generic in all the
181    /// type parameters of `StableGraph`.
182    pub fn new() -> Self {
183        Self::with_capacity(0, 0)
184    }
185}
186
187impl<N, E, Ty, Ix> StableGraph<N, E, Ty, Ix>
188    where Ty: EdgeType,
189          Ix: IndexType,
190{
191    /// Create a new `StableGraph` with estimated capacity.
192    pub fn with_capacity(nodes: usize, edges: usize) -> Self {
193        StableGraph {
194            g: Graph::with_capacity(nodes, edges),
195            node_count: 0,
196            edge_count: 0,
197            free_node: NodeIndex::end(),
198            free_edge: EdgeIndex::end(),
199        }
200    }
201
202    /// Return the current node and edge capacity of the graph.
203    pub fn capacity(&self) -> (usize, usize) {
204        self.g.capacity()
205    }
206
207    /// Remove all nodes and edges
208    pub fn clear(&mut self) {
209        self.node_count = 0;
210        self.edge_count = 0;
211        self.free_node = NodeIndex::end();
212        self.free_edge = EdgeIndex::end();
213        self.g.clear();
214    }
215
216    /// Remove all edges
217    pub fn clear_edges(&mut self) {
218        self.edge_count = 0;
219        self.free_edge = EdgeIndex::end();
220        self.g.edges.clear();
221        // clear edges without touching the free list
222        for node in &mut self.g.nodes {
223            if let Some(_) = node.weight {
224                node.next = [EdgeIndex::end(), EdgeIndex::end()];
225            }
226        }
227    }
228
229    /// Return the number of nodes (vertices) in the graph.
230    ///
231    /// Computes in **O(1)** time.
232    pub fn node_count(&self) -> usize {
233        self.node_count
234    }
235
236    /// Return the number of edges in the graph.
237    ///
238    /// Computes in **O(1)** time.
239    pub fn edge_count(&self) -> usize {
240        self.edge_count
241    }
242
243    /// Whether the graph has directed edges or not.
244    #[inline]
245    pub fn is_directed(&self) -> bool {
246        Ty::is_directed()
247    }
248
249    /// Add a node (also called vertex) with associated data `weight` to the graph.
250    ///
251    /// Computes in **O(1)** time.
252    ///
253    /// Return the index of the new node.
254    ///
255    /// **Panics** if the `StableGraph` is at the maximum number of nodes for
256    /// its index type.
257    pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
258        let index = if self.free_node != NodeIndex::end() {
259            let node_idx = self.free_node;
260            let node_slot = &mut self.g.nodes[node_idx.index()];
261            let _old = replace(&mut node_slot.weight, Some(weight));
262            debug_assert!(_old.is_none());
263            self.free_node = node_slot.next[0]._into_node();
264            node_slot.next[0] = EdgeIndex::end();
265            node_idx
266        } else {
267            self.g.add_node(Some(weight))
268        };
269        self.node_count += 1;
270        index
271    }
272
273    /// free_node: Which free list to update for the vacancy
274    fn add_vacant_node(&mut self, free_node: &mut NodeIndex<Ix>) {
275        let node_idx = self.g.add_node(None);
276        // link the free list
277        let node_slot = &mut self.g.nodes[node_idx.index()];
278        node_slot.next[0] = free_node._into_edge();
279        *free_node = node_idx;
280    }
281
282    /// Remove `a` from the graph if it exists, and return its weight.
283    /// If it doesn't exist in the graph, return `None`.
284    ///
285    /// The node index `a` is invalidated, but none other.
286    /// Edge indices are invalidated as they would be following the removal of
287    /// each edge with an endpoint in `a`.
288    ///
289    /// Computes in **O(e')** time, where **e'** is the number of affected
290    /// edges, including *n* calls to `.remove_edge()` where *n* is the number
291    /// of edges with an endpoint in `a`.
292    pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> Option<N> {
293        let node_weight = match self.g.nodes.get_mut(a.index()) {
294            None => return None,
295            Some(n) => n.weight.take(),
296        };
297        if let None = node_weight {
298            return None;
299        }
300        for d in &DIRECTIONS {
301            let k = d.index();
302
303            // Remove all edges from and to this node.
304            loop {
305                let next = self.g.nodes[a.index()].next[k];
306                if next == EdgeIndex::end() {
307                    break
308                }
309                let ret = self.remove_edge(next);
310                debug_assert!(ret.is_some());
311                let _ = ret;
312            }
313        }
314
315        let node_slot = &mut self.g.nodes[a.index()];
316        //let node_weight = replace(&mut self.g.nodes[a.index()].weight, Entry::Empty(self.free_node));
317        //self.g.nodes[a.index()].next = [EdgeIndex::end(), EdgeIndex::end()];
318        node_slot.next = [self.free_node._into_edge(), EdgeIndex::end()];
319        self.free_node = a;
320        self.node_count -= 1;
321
322        node_weight
323    }
324
325    pub fn contains_node(&self, a: NodeIndex<Ix>) -> bool {
326        self.get_node(a).is_some()
327    }
328
329    // Return the Node if it is not vacant (non-None weight)
330    fn get_node(&self, a: NodeIndex<Ix>) -> Option<&Node<Option<N>, Ix>> {
331        self.g.nodes.get(a.index())
332                    .and_then(|node| node.weight.as_ref().map(move |_| node))
333    }
334
335    /// Add an edge from `a` to `b` to the graph, with its associated
336    /// data `weight`.
337    ///
338    /// Return the index of the new edge.
339    ///
340    /// Computes in **O(1)** time.
341    ///
342    /// **Panics** if any of the nodes don't exist.<br>
343    /// **Panics** if the `StableGraph` is at the maximum number of edges for
344    /// its index type.
345    ///
346    /// **Note:** `StableGraph` allows adding parallel (“duplicate”) edges.
347    pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
348        -> EdgeIndex<Ix>
349    {
350        let edge_idx;
351        let mut new_edge = None::<Edge<_, _>>;
352        {
353            let edge: &mut Edge<_, _>;
354
355            if self.free_edge != EdgeIndex::end() {
356                edge_idx = self.free_edge;
357                edge = &mut self.g.edges[edge_idx.index()];
358                let _old = replace(&mut edge.weight, Some(weight));
359                debug_assert!(_old.is_none());
360                self.free_edge = edge.next[0];
361                edge.node = [a, b];
362            } else {
363                edge_idx = EdgeIndex::new(self.g.edges.len());
364                assert!(<Ix as IndexType>::max().index() == !0 || EdgeIndex::end() != edge_idx);
365                new_edge = Some(Edge {
366                    weight: Some(weight),
367                    node: [a, b],
368                    next: [EdgeIndex::end(); 2],
369                });
370                edge = new_edge.as_mut().unwrap();
371            }
372
373            let wrong_index = match index_twice(&mut self.g.nodes, a.index(), b.index()) {
374                Pair::None => Some(cmp::max(a.index(), b.index())),
375                Pair::One(an) => {
376                    if an.weight.is_none() {
377                        Some(a.index())
378                    } else {
379                        edge.next = an.next;
380                        an.next[0] = edge_idx;
381                        an.next[1] = edge_idx;
382                        None
383                    }
384                }
385                Pair::Both(an, bn) => {
386                    // a and b are different indices
387                    if an.weight.is_none() {
388                        Some(a.index())
389                    } else if bn.weight.is_none() {
390                        Some(b.index())
391                    } else {
392                        edge.next = [an.next[0], bn.next[1]];
393                        an.next[0] = edge_idx;
394                        bn.next[1] = edge_idx;
395                        None
396                    }
397                }
398            };
399            if let Some(i) = wrong_index {
400                panic!("StableGraph::add_edge: node index {} is not a node in the graph", i);
401            }
402            self.edge_count += 1;
403        }
404        if let Some(edge) = new_edge {
405            self.g.edges.push(edge);
406        }
407        edge_idx
408    }
409
410    /// free_edge: Which free list to update for the vacancy
411    fn add_vacant_edge(&mut self, free_edge: &mut EdgeIndex<Ix>) {
412        let edge_idx = EdgeIndex::new(self.g.edges.len());
413        debug_assert!(edge_idx != EdgeIndex::end());
414        let mut edge = Edge {
415            weight: None,
416            node: [NodeIndex::end(); 2],
417            next: [EdgeIndex::end(); 2],
418        };
419        edge.next[0] = *free_edge;
420        *free_edge = edge_idx;
421        self.g.edges.push(edge);
422    }
423
424    /// Add or update an edge from `a` to `b`.
425    /// If the edge already exists, its weight is updated.
426    ///
427    /// Return the index of the affected edge.
428    ///
429    /// Computes in **O(e')** time, where **e'** is the number of edges
430    /// connected to `a` (and `b`, if the graph edges are undirected).
431    ///
432    /// **Panics** if any of the nodes don't exist.
433    pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E)
434        -> EdgeIndex<Ix>
435    {
436        if let Some(ix) = self.find_edge(a, b) {
437            self[ix] = weight;
438            return ix;
439        }
440        self.add_edge(a, b, weight)
441    }
442
443    /// Remove an edge and return its edge weight, or `None` if it didn't exist.
444    ///
445    /// Invalidates the edge index `e` but no other.
446    ///
447    /// Computes in **O(e')** time, where **e'** is the number of edges
448    /// conneced to the same endpoints as `e`.
449    pub fn remove_edge(&mut self, e: EdgeIndex<Ix>) -> Option<E> {
450        // every edge is part of two lists,
451        // outgoing and incoming edges.
452        // Remove it from both
453        let (is_edge, edge_node, edge_next) = match self.g.edges.get(e.index()) {
454            None => return None,
455            Some(x) => (x.weight.is_some(), x.node, x.next),
456        };
457        if !is_edge {
458            return None;
459        }
460
461        // Remove the edge from its in and out lists by replacing it with
462        // a link to the next in the list.
463        self.g.change_edge_links(edge_node, e, edge_next);
464
465        // Clear the edge and put it in the free list
466        let edge = &mut self.g.edges[e.index()];
467        edge.next = [self.free_edge, EdgeIndex::end()];
468        edge.node = [NodeIndex::end(), NodeIndex::end()];
469        self.free_edge = e;
470        self.edge_count -= 1;
471        edge.weight.take()
472    }
473
474    /// Access the weight for node `a`.
475    ///
476    /// Also available with indexing syntax: `&graph[a]`.
477    pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
478        match self.g.nodes.get(a.index()) {
479            Some(no) => no.weight.as_ref(),
480            None => None,
481        }
482    }
483
484    /// Access the weight for node `a`, mutably.
485    ///
486    /// Also available with indexing syntax: `&mut graph[a]`.
487    pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> Option<&mut N> {
488        match self.g.nodes.get_mut(a.index()) {
489            Some(no) => no.weight.as_mut(),
490            None => None,
491        }
492    }
493
494    /// Return an iterator over the node indices of the graph
495    pub fn node_indices(&self) -> NodeIndices<N, Ix> {
496        NodeIndices {
497            iter: enumerate(self.raw_nodes())
498        }
499    }
500
501    /// Access the weight for edge `e`.
502    ///
503    /// Also available with indexing syntax: `&graph[e]`.
504    pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
505        match self.g.edges.get(e.index()) {
506            Some(ed) => ed.weight.as_ref(),
507            None => None,
508        }
509    }
510
511    /// Access the weight for edge `e`, mutably
512    ///
513    /// Also available with indexing syntax: `&mut graph[e]`.
514    pub fn edge_weight_mut(&mut self, e: EdgeIndex<Ix>) -> Option<&mut E> {
515        match self.g.edges.get_mut(e.index()) {
516            Some(ed) => ed.weight.as_mut(),
517            None => None,
518        }
519    }
520
521    /// Access the source and target nodes for `e`.
522    pub fn edge_endpoints(&self, e: EdgeIndex<Ix>)
523        -> Option<(NodeIndex<Ix>, NodeIndex<Ix>)>
524    {
525        match self.g.edges.get(e.index()) {
526            Some(ed) if ed.weight.is_some() => Some((ed.source(), ed.target())),
527            _otherwise => None,
528        }
529    }
530
531    /// Return an iterator over the node indices of the graph
532    pub fn edge_indices(&self) -> EdgeIndices<E, Ix> {
533        EdgeIndices {
534            iter: enumerate(self.raw_edges())
535        }
536    }
537
538    /// Lookup an edge from `a` to `b`.
539    ///
540    /// Computes in **O(e')** time, where **e'** is the number of edges
541    /// connected to `a` (and `b`, if the graph edges are undirected).
542    pub fn find_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>
543    {
544        if !self.is_directed() {
545            self.find_edge_undirected(a, b).map(|(ix, _)| ix)
546        } else {
547            match self.get_node(a) {
548                None => None,
549                Some(node) => self.g.find_edge_directed_from_node(node, b)
550            }
551        }
552    }
553
554    /// Lookup an edge between `a` and `b`, in either direction.
555    ///
556    /// If the graph is undirected, then this is equivalent to `.find_edge()`.
557    ///
558    /// Return the edge index and its directionality, with `Outgoing` meaning
559    /// from `a` to `b` and `Incoming` the reverse,
560    /// or `None` if the edge does not exist.
561    pub fn find_edge_undirected(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<(EdgeIndex<Ix>, Direction)>
562    {
563        match self.get_node(a) {
564            None => None,
565            Some(node) => self.g.find_edge_undirected_from_node(node, b),
566        }
567    }
568
569
570    /// Return an iterator of all nodes with an edge starting from `a`.
571    ///
572    /// - `Directed`: Outgoing edges from `a`.
573    /// - `Undirected`: All edges connected to `a`.
574    ///
575    /// Produces an empty iterator if the node doesn't exist.<br>
576    /// Iterator element type is `NodeIndex<Ix>`.
577    ///
578    /// Use [`.neighbors(a).detach()`][1] to get a neighbor walker that does
579    /// not borrow from the graph.
580    ///
581    /// [1]: struct.Neighbors.html#method.detach
582    pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix> {
583        self.neighbors_directed(a, Outgoing)
584    }
585
586    /// Return an iterator of all neighbors that have an edge between them and `a`,
587    /// in the specified direction.
588    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
589    ///
590    /// - `Directed`, `Outgoing`: All edges from `a`.
591    /// - `Directed`, `Incoming`: All edges to `a`.
592    /// - `Undirected`: All edges connected to `a`.
593    ///
594    /// Produces an empty iterator if the node doesn't exist.<br>
595    /// Iterator element type is `NodeIndex<Ix>`.
596    ///
597    /// Use [`.neighbors_directed(a, dir).detach()`][1] to get a neighbor walker that does
598    /// not borrow from the graph.
599    ///
600    /// [1]: struct.Neighbors.html#method.detach
601    pub fn neighbors_directed(&self, a: NodeIndex<Ix>, dir: Direction)
602        -> Neighbors<E, Ix>
603    {
604        let mut iter = self.neighbors_undirected(a);
605        if self.is_directed() {
606            let k = dir.index();
607            iter.next[1 - k] = EdgeIndex::end();
608            iter.skip_start = NodeIndex::end();
609        }
610        iter
611    }
612
613    /// Return an iterator of all neighbors that have an edge between them and `a`,
614    /// in either direction.
615    /// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
616    ///
617    /// - `Directed` and `Undirected`: All edges connected to `a`.
618    ///
619    /// Produces an empty iterator if the node doesn't exist.<br>
620    /// Iterator element type is `NodeIndex<Ix>`.
621    ///
622    /// Use [`.neighbors_undirected(a).detach()`][1] to get a neighbor walker that does
623    /// not borrow from the graph.
624    ///
625    /// [1]: struct.Neighbors.html#method.detach
626    pub fn neighbors_undirected(&self, a: NodeIndex<Ix>) -> Neighbors<E, Ix>
627    {
628        Neighbors {
629            skip_start: a,
630            edges: &self.g.edges,
631            next: match self.get_node(a) {
632                None => [EdgeIndex::end(), EdgeIndex::end()],
633                Some(n) => n.next,
634            }
635        }
636    }
637
638    /// Return an iterator of all edges of `a`.
639    ///
640    /// - `Directed`: Outgoing edges from `a`.
641    /// - `Undirected`: All edges connected to `a`.
642    ///
643    /// Produces an empty iterator if the node doesn't exist.<br>
644    /// Iterator element type is `EdgeReference<E, Ix>`.
645    pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
646        self.edges_directed(a, Outgoing)
647    }
648
649    /// Return an iterator of all edges of `a`, in the specified direction.
650    ///
651    /// - `Directed`, `Outgoing`: All edges from `a`.
652    /// - `Directed`, `Incoming`: All edges to `a`.
653    /// - `Undirected`: All edges connected to `a`.
654    ///
655    /// Produces an empty iterator if the node `a` doesn't exist.<br>
656    /// Iterator element type is `EdgeReference<E, Ix>`.
657    pub fn edges_directed(&self, a: NodeIndex<Ix>, dir: Direction) -> Edges<E, Ty, Ix>
658    {
659        let mut iter = self.edges_undirected(a);
660        if self.is_directed() {
661            iter.direction = Some(dir);
662        }
663        if self.is_directed() && dir == Incoming {
664            iter.next.swap(0, 1);
665        }
666        iter
667    }
668
669    /// Return an iterator over all edges connected to `a`.
670    ///
671    /// - `Directed` and `Undirected`: All edges connected to `a`.
672    ///
673    /// Produces an empty iterator if the node `a` doesn't exist.<br>
674    /// Iterator element type is `EdgeReference<E, Ix>`.
675    fn edges_undirected(&self, a: NodeIndex<Ix>) -> Edges<E, Ty, Ix> {
676        Edges {
677            skip_start: a,
678            edges: &self.g.edges,
679            direction: None,
680            next: match self.get_node(a) {
681                None => [EdgeIndex::end(), EdgeIndex::end()],
682                Some(n) => n.next,
683            },
684            ty: PhantomData,
685        }
686    }
687
688    /// Index the `StableGraph` by two indices, any combination of
689    /// node or edge indices is fine.
690    ///
691    /// **Panics** if the indices are equal or if they are out of bounds.
692    pub fn index_twice_mut<T, U>(&mut self, i: T, j: U)
693        -> (&mut <Self as Index<T>>::Output,
694            &mut <Self as Index<U>>::Output)
695        where Self: IndexMut<T> + IndexMut<U>,
696              T: GraphIndex,
697              U: GraphIndex,
698    {
699        assert!(T::is_node_index() != U::is_node_index() ||
700                i.index() != j.index());
701
702        // Allow two mutable indexes here -- they are nonoverlapping
703        unsafe {
704            let self_mut = self as *mut _;
705            (<Self as IndexMut<T>>::index_mut(&mut *self_mut, i),
706             <Self as IndexMut<U>>::index_mut(&mut *self_mut, j))
707        }
708    }
709
710    /// Keep all nodes that return `true` from the `visit` closure,
711    /// remove the others.
712    ///
713    /// `visit` is provided a proxy reference to the graph, so that
714    /// the graph can be walked and associated data modified.
715    ///
716    /// The order nodes are visited is not specified.
717    ///
718    /// The node indices of the removed nodes are invalidated, but none other.
719    /// Edge indices are invalidated as they would be following the removal of
720    /// each edge with an endpoint in a removed node.
721    ///
722    /// Computes in **O(n + e')** time, where **n** is the number of node indices and
723    ///  **e'** is the number of affected edges, including *n* calls to `.remove_edge()`
724    /// where *n* is the number of edges with an endpoint in a removed node.
725    pub fn retain_nodes<F>(&mut self, mut visit: F) where F: FnMut(Frozen<Self>, NodeIndex<Ix>) -> bool {
726        for i in 0..self.node_bound() {
727            let ix = node_index(i);
728            if self.contains_node(ix) && !visit(Frozen(self), ix) {
729                self.remove_node(ix);
730            }
731        }
732        self.check_free_lists();
733    }
734
735    /// Keep all edges that return `true` from the `visit` closure,
736    /// remove the others.
737    ///
738    /// `visit` is provided a proxy reference to the graph, so that
739    /// the graph can be walked and associated data modified.
740    ///
741    /// The order edges are visited is not specified.
742    ///
743    /// The edge indices of the removed edes are invalidated, but none other.
744    ///
745    /// Computes in **O(e'')** time, **e'** is the number of affected edges,
746    /// including the calls to `.remove_edge()` for each removed edge.
747    pub fn retain_edges<F>(&mut self, mut visit: F)
748        where F: FnMut(Frozen<Self>, EdgeIndex<Ix>) -> bool
749    {
750        for i in 0..self.edge_bound() {
751            let ix = edge_index(i);
752            if self.edge_weight(ix).is_some() && !visit(Frozen(self), ix) {
753                self.remove_edge(ix);
754            }
755        }
756        self.check_free_lists();
757    }
758
759    /// Create a new `StableGraph` from an iterable of edges.
760    ///
761    /// Node weights `N` are set to default values.
762    /// Edge weights `E` may either be specified in the list,
763    /// or they are filled with default values.
764    ///
765    /// Nodes are inserted automatically to match the edges.
766    ///
767    /// ```
768    /// use petgraph::stable_graph::StableGraph;
769    ///
770    /// let gr = StableGraph::<(), i32>::from_edges(&[
771    ///     (0, 1), (0, 2), (0, 3),
772    ///     (1, 2), (1, 3),
773    ///     (2, 3),
774    /// ]);
775    /// ```
776    pub fn from_edges<I>(iterable: I) -> Self
777        where I: IntoIterator,
778              I::Item: IntoWeightedEdge<E>,
779              <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
780              N: Default,
781    {
782        let mut g = Self::with_capacity(0, 0);
783        g.extend_with_edges(iterable);
784        g
785    }
786
787    /// Create a new `StableGraph` by mapping node and
788    /// edge weights to new values.
789    ///
790    /// The resulting graph has the same structure and the same
791    /// graph indices as `self`.
792    pub fn map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
793        -> StableGraph<N2, E2, Ty, Ix>
794        where F: FnMut(NodeIndex<Ix>, &'a N) -> N2,
795              G: FnMut(EdgeIndex<Ix>, &'a E) -> E2,
796    {
797        let g = self.g.map(
798            move |i, w| w.as_ref().map(|w| node_map(i, w)),
799            move |i, w| w.as_ref().map(|w| edge_map(i, w)));
800        StableGraph {
801            g: g,
802            node_count: self.node_count,
803            edge_count: self.edge_count,
804            free_node: self.free_node,
805            free_edge: self.free_edge,
806        }
807    }
808
809    /// Create a new `StableGraph` by mapping nodes and edges.
810    /// A node or edge may be mapped to `None` to exclude it from
811    /// the resulting graph.
812    ///
813    /// Nodes are mapped first with the `node_map` closure, then
814    /// `edge_map` is called for the edges that have not had any endpoint
815    /// removed.
816    ///
817    /// The resulting graph has the structure of a subgraph of the original graph.
818    /// Nodes and edges that are not removed maintain their old node or edge
819    /// indices.
820    pub fn filter_map<'a, F, G, N2, E2>(&'a self, mut node_map: F, mut edge_map: G)
821        -> StableGraph<N2, E2, Ty, Ix>
822        where F: FnMut(NodeIndex<Ix>, &'a N) -> Option<N2>,
823              G: FnMut(EdgeIndex<Ix>, &'a E) -> Option<E2>,
824    {
825        let node_bound = self.node_bound();
826        let edge_bound = self.edge_bound();
827        let mut result_g = StableGraph::with_capacity(node_bound, edge_bound);
828        // use separate free lists so that
829        // add_node / add_edge below do not reuse the tombstones
830        let mut free_node = NodeIndex::end();
831        let mut free_edge = EdgeIndex::end();
832
833        // the stable graph keeps the node map itself
834
835        for (i, node) in enumerate(self.raw_nodes()) {
836            if i >= node_bound { break; }
837            if let Some(node_weight) = node.weight.as_ref() {
838                if let Some(new_weight) = node_map(NodeIndex::new(i), node_weight) {
839                    result_g.add_node(new_weight);
840                    continue;
841                }
842            }
843            result_g.add_vacant_node(&mut free_node);
844        }
845        for (i, edge) in enumerate(self.raw_edges()) {
846            if i >= edge_bound { break; }
847            let source = edge.source();
848            let target = edge.target();
849            if let Some(edge_weight) = edge.weight.as_ref() {
850                if result_g.contains_node(source) && result_g.contains_node(target) {
851                    if let Some(new_weight) = edge_map(EdgeIndex::new(i), edge_weight) {
852                        result_g.add_edge(source, target, new_weight);
853                        continue;
854                    }
855                }
856            }
857            result_g.add_vacant_edge(&mut free_edge);
858        }
859        result_g.free_node = free_node;
860        result_g.free_edge = free_edge;
861        result_g.check_free_lists();
862        result_g
863    }
864
865    /// Extend the graph from an iterable of edges.
866    ///
867    /// Node weights `N` are set to default values.
868    /// Edge weights `E` may either be specified in the list,
869    /// or they are filled with default values.
870    ///
871    /// Nodes are inserted automatically to match the edges.
872    pub fn extend_with_edges<I>(&mut self, iterable: I)
873        where I: IntoIterator,
874              I::Item: IntoWeightedEdge<E>,
875              <I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
876              N: Default,
877    {
878        let iter = iterable.into_iter();
879
880        for elt in iter {
881            let (source, target, weight) = elt.into_weighted_edge();
882            let (source, target) = (source.into(), target.into());
883            let nx = cmp::max(source, target);
884            while nx.index() >= self.node_count() {
885                self.add_node(N::default());
886            }
887            self.add_edge(source, target, weight);
888        }
889    }
890
891    //
892    // internal methods
893    //
894    fn raw_nodes(&self) -> &[Node<Option<N>, Ix>] {
895        self.g.raw_nodes()
896    }
897
898    fn raw_edges(&self) -> &[Edge<Option<E>, Ix>] {
899        self.g.raw_edges()
900    }
901
902    fn edge_bound(&self) -> usize {
903        self.edge_references()
904            .next_back()
905            .map_or(0, |edge| edge.id().index() + 1)
906    }
907
908    #[cfg(feature = "serde-1")]
909    /// Fix up node and edge links after deserialization
910    fn link_edges(&mut self) -> Result<(), NodeIndex<Ix>> {
911        // set up free node list
912        self.node_count = 0;
913        self.edge_count = 0;
914        let mut free_node = NodeIndex::end();
915        for (node_index, node) in enumerate(&mut self.g.nodes) {
916            if node.weight.is_some() {
917                self.node_count += 1;
918            } else {
919                // free node
920                node.next = [free_node._into_edge(), EdgeIndex::end()];
921                free_node = NodeIndex::new(node_index);
922            }
923        }
924        self.free_node = free_node;
925
926        let mut free_edge = EdgeIndex::end();
927        for (edge_index, edge) in enumerate(&mut self.g.edges) {
928            if edge.weight.is_none() {
929                // free edge
930                edge.next = [free_edge, EdgeIndex::end()];
931                free_edge = EdgeIndex::new(edge_index);
932                continue;
933            }
934            let a = edge.source();
935            let b = edge.target();
936            let edge_idx = EdgeIndex::new(edge_index);
937            match index_twice(&mut self.g.nodes, a.index(), b.index()) {
938                Pair::None => return Err(if a > b { a } else { b }),
939                Pair::One(an) => {
940                    edge.next = an.next;
941                    an.next[0] = edge_idx;
942                    an.next[1] = edge_idx;
943                }
944                Pair::Both(an, bn) => {
945                    // a and b are different indices
946                    edge.next = [an.next[0], bn.next[1]];
947                    an.next[0] = edge_idx;
948                    bn.next[1] = edge_idx;
949                }
950            }
951            self.edge_count += 1;
952        }
953        self.free_edge = free_edge;
954        Ok(())
955    }
956
957    #[cfg(not(debug_assertions))]
958    fn check_free_lists(&self) { }
959    #[cfg(debug_assertions)]
960    // internal method to debug check the free lists (linked lists)
961    fn check_free_lists(&self) {
962        let mut free_node = self.free_node;
963        let mut free_node_len = 0;
964        while free_node != NodeIndex::end() {
965            if let Some(n) = self.g.nodes.get(free_node.index()) {
966                if let None = n.weight {
967                    free_node = n.next[0]._into_node();
968                    free_node_len += 1;
969                    continue;
970                }
971                debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
972                              free_node.index());
973            }
974            debug_assert!(false, "Corrupt free list: missing {:?}", free_node.index());
975        }
976        debug_assert_eq!(self.node_count(), self.raw_nodes().len() - free_node_len);
977
978        let mut free_edge_len = 0;
979        let mut free_edge = self.free_edge;
980        while free_edge != EdgeIndex::end() {
981            if let Some(n) = self.g.edges.get(free_edge.index()) {
982                if let None = n.weight {
983                    free_edge = n.next[0];
984                    free_edge_len += 1;
985                    continue;
986                }
987                debug_assert!(false, "Corrupt free list: pointing to existing {:?}",
988                              free_node.index());
989            }
990            debug_assert!(false, "Corrupt free list: missing {:?}", free_edge.index());
991        }
992        debug_assert_eq!(self.edge_count(), self.raw_edges().len() - free_edge_len);
993    }
994}
995
996/// The resulting cloned graph has the same graph indices as `self`.
997impl<N, E, Ty, Ix: IndexType> Clone for StableGraph<N, E, Ty, Ix>
998    where N: Clone, E: Clone,
999{
1000    fn clone(&self) -> Self {
1001        StableGraph {
1002            g: self.g.clone(),
1003            node_count: self.node_count,
1004            edge_count: self.edge_count,
1005            free_node: self.free_node,
1006            free_edge: self.free_edge,
1007        }
1008    }
1009
1010    fn clone_from(&mut self, rhs: &Self) {
1011        self.g.clone_from(&rhs.g);
1012        self.node_count = rhs.node_count;
1013        self.edge_count = rhs.edge_count;
1014        self.free_node = rhs.free_node;
1015        self.free_edge = rhs.free_edge;
1016    }
1017}
1018
1019/// Index the `StableGraph` by `NodeIndex` to access node weights.
1020///
1021/// **Panics** if the node doesn't exist.
1022impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1023    Ty: EdgeType,
1024    Ix: IndexType,
1025{
1026    type Output = N;
1027    fn index(&self, index: NodeIndex<Ix>) -> &N {
1028        self.node_weight(index).unwrap()
1029    }
1030}
1031
1032/// Index the `StableGraph` by `NodeIndex` to access node weights.
1033///
1034/// **Panics** if the node doesn't exist.
1035impl<N, E, Ty, Ix> IndexMut<NodeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1036    Ty: EdgeType,
1037    Ix: IndexType,
1038{
1039    fn index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N {
1040        self.node_weight_mut(index).unwrap()
1041    }
1042
1043}
1044
1045/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1046///
1047/// **Panics** if the edge doesn't exist.
1048impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1049    Ty: EdgeType,
1050    Ix: IndexType,
1051{
1052    type Output = E;
1053    fn index(&self, index: EdgeIndex<Ix>) -> &E {
1054        self.edge_weight(index).unwrap()
1055    }
1056}
1057
1058/// Index the `StableGraph` by `EdgeIndex` to access edge weights.
1059///
1060/// **Panics** if the edge doesn't exist.
1061impl<N, E, Ty, Ix> IndexMut<EdgeIndex<Ix>> for StableGraph<N, E, Ty, Ix> where
1062    Ty: EdgeType,
1063    Ix: IndexType,
1064{
1065    fn index_mut(&mut self, index: EdgeIndex<Ix>) -> &mut E {
1066        self.edge_weight_mut(index).unwrap()
1067    }
1068}
1069
1070/// Create a new empty `StableGraph`.
1071impl<N, E, Ty, Ix> Default for StableGraph<N, E, Ty, Ix>
1072    where Ty: EdgeType,
1073          Ix: IndexType,
1074{
1075    fn default() -> Self { Self::with_capacity(0, 0) }
1076}
1077
1078/// Convert a `Graph` into a `StableGraph`
1079///
1080/// Computes in **O(|V| + |E|)** time.
1081///
1082/// The resulting graph has the same node and edge indices as
1083/// the original graph.
1084impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
1085    where Ty: EdgeType,
1086          Ix: IndexType,
1087{
1088    fn from(g: Graph<N, E, Ty, Ix>) -> Self {
1089        let nodes = g.nodes.into_iter().map(|e| Node {
1090            weight: Some(e.weight),
1091            next: e.next,
1092        });
1093        let edges = g.edges.into_iter().map(|e| Edge {
1094            weight: Some(e.weight),
1095            node: e.node,
1096            next: e.next,
1097        });
1098        StableGraph {
1099            node_count: nodes.len(),
1100            edge_count: edges.len(),
1101            g: Graph { edges: edges.collect(), nodes: nodes.collect(), ty: g.ty },
1102            free_node: NodeIndex::end(),
1103            free_edge: EdgeIndex::end(),
1104        }
1105    }
1106}
1107
1108/// Convert a `StableGraph` into a `Graph`
1109///
1110/// Computes in **O(|V| + |E|)** time.
1111///
1112/// This translates the stable graph into a graph with node and edge indices in
1113/// a compact interval without holes (like `Graph`s always are).
1114///
1115/// Only if the stable graph had no vacancies after deletions (if node bound was
1116/// equal to node count, and the same for edges), would the resulting graph have
1117/// the same node and edge indices as the input.
1118impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
1119    where Ty: EdgeType,
1120          Ix: IndexType,
1121{
1122    fn from(graph: StableGraph<N, E, Ty, Ix>) -> Self {
1123        let mut result_g = Graph::with_capacity(graph.node_count(), graph.edge_count());
1124        // mapping from old node index to new node index
1125        let mut node_index_map = vec![NodeIndex::end(); graph.node_bound()];
1126
1127        for (i, node) in enumerate(graph.g.nodes) {
1128            if let Some(nw) = node.weight {
1129                node_index_map[i] = result_g.add_node(nw);
1130            }
1131        }
1132        for edge in graph.g.edges {
1133            let source_index = edge.source().index();
1134            let target_index = edge.target().index();
1135            if let Some(ew) = edge.weight {
1136                let source = node_index_map[source_index];
1137                let target = node_index_map[target_index];
1138                debug_assert!(source != NodeIndex::end());
1139                debug_assert!(target != NodeIndex::end());
1140                result_g.add_edge(source, target, ew);
1141            }
1142        }
1143        result_g
1144    }
1145}
1146
1147impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a StableGraph<N, E, Ty, Ix>
1148    where Ty: EdgeType,
1149          Ix: IndexType,
1150{
1151    type NodeRef = (NodeIndex<Ix>, &'a N);
1152    type NodeReferences = NodeReferences<'a, N, Ix>;
1153    fn node_references(self) -> Self::NodeReferences {
1154        NodeReferences {
1155            iter: enumerate(self.raw_nodes())
1156        }
1157    }
1158}
1159
1160/// Iterator over all nodes of a graph.
1161pub struct NodeReferences<'a, N: 'a, Ix: IndexType = DefaultIx> {
1162    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1163}
1164
1165impl<'a, N, Ix> Iterator for NodeReferences<'a, N, Ix>
1166    where Ix: IndexType
1167{
1168    type Item = (NodeIndex<Ix>, &'a N);
1169
1170    fn next(&mut self) -> Option<Self::Item> {
1171        self.iter.ex_find_map(|(i, node)| {
1172            node.weight.as_ref().map(move |w| (node_index(i), w))
1173        })
1174    }
1175
1176    fn size_hint(&self) -> (usize, Option<usize>) {
1177        let (_, hi) = self.iter.size_hint();
1178        (0, hi)
1179    }
1180}
1181
1182impl<'a, N, Ix> DoubleEndedIterator for NodeReferences<'a, N, Ix>
1183    where Ix: IndexType
1184{
1185    fn next_back(&mut self) -> Option<Self::Item> {
1186        self.iter.ex_rfind_map(|(i, node)| {
1187            node.weight.as_ref().map(move |w| (node_index(i), w))
1188        })
1189    }
1190}
1191
1192/// Reference to a `StableGraph` edge.
1193#[derive(Debug)]
1194pub struct EdgeReference<'a, E: 'a, Ix = DefaultIx> {
1195    index: EdgeIndex<Ix>,
1196    node: [NodeIndex<Ix>; 2],
1197    weight: &'a E,
1198}
1199
1200impl<'a, E, Ix: IndexType> Clone for EdgeReference<'a, E, Ix> {
1201    fn clone(&self) -> Self {
1202        *self
1203    }
1204}
1205
1206impl<'a, E, Ix: IndexType> Copy for EdgeReference<'a, E, Ix> { }
1207
1208impl<'a, E, Ix: IndexType> PartialEq for EdgeReference<'a, E, Ix>
1209    where E: PartialEq,
1210{
1211    fn eq(&self, rhs: &Self) -> bool {
1212        self.index == rhs.index && self.weight == rhs.weight
1213    }
1214}
1215
1216impl<'a, Ix, E> EdgeReference<'a, E, Ix>
1217    where Ix: IndexType,
1218{
1219    /// Access the edge’s weight.
1220    ///
1221    /// **NOTE** that this method offers a longer lifetime
1222    /// than the trait (unfortunately they don't match yet).
1223    pub fn weight(&self) -> &'a E { self.weight }
1224}
1225
1226impl<'a, Ix, E> EdgeRef for EdgeReference<'a, E, Ix>
1227    where Ix: IndexType,
1228{
1229    type NodeId = NodeIndex<Ix>;
1230    type EdgeId = EdgeIndex<Ix>;
1231    type Weight = E;
1232
1233    fn source(&self) -> Self::NodeId { self.node[0] }
1234    fn target(&self) -> Self::NodeId { self.node[1] }
1235    fn weight(&self) -> &E { self.weight }
1236    fn id(&self) -> Self::EdgeId { self.index }
1237}
1238
1239impl<'a, N, E, Ty, Ix> IntoEdges for &'a StableGraph<N, E, Ty, Ix>
1240    where Ty: EdgeType,
1241          Ix: IndexType,
1242{
1243    type Edges = Edges<'a, E, Ty, Ix>;
1244    fn edges(self, a: Self::NodeId) -> Self::Edges {
1245        self.edges(a)
1246    }
1247}
1248
1249impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a StableGraph<N, E, Ty, Ix>
1250    where Ty: EdgeType,
1251          Ix: IndexType,
1252{
1253    type EdgesDirected = Edges<'a, E, Ty, Ix>;
1254    fn edges_directed(self, a: Self::NodeId, dir: Direction) -> Self::EdgesDirected {
1255        self.edges_directed(a, dir)
1256    }
1257}
1258
1259
1260/// Iterator over the edges of from or to a node
1261pub struct Edges<'a, E: 'a, Ty, Ix: 'a = DefaultIx>
1262    where Ty: EdgeType,
1263          Ix: IndexType,
1264{
1265    /// starting node to skip over
1266    skip_start: NodeIndex<Ix>,
1267    edges: &'a [Edge<Option<E>, Ix>],
1268
1269    /// Next edge to visit.
1270    /// If we are only following one direction, we only use next[0] regardless.
1271    next: [EdgeIndex<Ix>; 2],
1272
1273    /// Which direction to follow
1274    /// None: Both,
1275    /// Some(d): d if Directed, Both if Undirected
1276    direction: Option<Direction>,
1277    ty: PhantomData<Ty>,
1278}
1279
1280impl<'a, E, Ty, Ix> Iterator for Edges<'a, E, Ty, Ix>
1281    where Ty: EdgeType,
1282          Ix: IndexType,
1283{
1284    type Item = EdgeReference<'a, E, Ix>;
1285
1286    fn next(&mut self) -> Option<Self::Item> {
1287        // First the outgoing or incoming edges (directionality)
1288        let k = self.direction.unwrap_or(Outgoing).index();
1289        let i = self.next[0].index();
1290        match self.edges.get(i) {
1291            None => {}
1292            Some(&Edge { ref node, weight: Some(ref weight), ref next }) => {
1293                self.next[0] = next[k];
1294                return Some(EdgeReference {
1295                    index: edge_index(i),
1296                    node: *node,
1297                    weight: weight,
1298                });
1299            }
1300            Some(_otherwise) => unreachable!(),
1301        }
1302        // Stop here if we only follow one direction
1303        if self.direction.is_some() {
1304            return None;
1305        }
1306        // Then incoming edges
1307        // For an "undirected" iterator (traverse both incoming
1308        // and outgoing edge lists), make sure we don't double
1309        // count selfloops by skipping them in the incoming list.
1310
1311        // We reach here if self.direction was None or Outgoing.
1312        debug_assert_eq!(k, 0);
1313        while let Some(edge) = self.edges.get(self.next[1].index()) {
1314            debug_assert!(edge.weight.is_some());
1315            let i = self.next[1].index();
1316            self.next[1] = edge.next[1];
1317            if edge.node[0] != self.skip_start {
1318                return Some(EdgeReference {
1319                    index: edge_index(i),
1320                    node: swap_pair(edge.node),
1321                    weight: edge.weight.as_ref().unwrap(),
1322                });
1323            }
1324        }
1325        None
1326    }
1327}
1328
1329fn swap_pair<T>(mut x: [T; 2]) -> [T; 2] {
1330    x.swap(0, 1);
1331    x
1332}
1333
1334impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences for &'a StableGraph<N, E, Ty, Ix>
1335    where Ty: EdgeType,
1336          Ix: IndexType,
1337{
1338    type EdgeRef = EdgeReference<'a, E, Ix>;
1339    type EdgeReferences = EdgeReferences<'a, E, Ix>;
1340
1341    /// Create an iterator over all edges in the graph, in indexed order.
1342    ///
1343    /// Iterator element type is `EdgeReference<E, Ix>`.
1344    fn edge_references(self) -> Self::EdgeReferences {
1345        EdgeReferences {
1346            iter: self.g.edges.iter().enumerate()
1347        }
1348    }
1349
1350}
1351
1352/// Iterator over all edges of a graph.
1353pub struct EdgeReferences<'a, E: 'a, Ix: 'a = DefaultIx> {
1354    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1355}
1356
1357impl<'a, E, Ix> Iterator for EdgeReferences<'a, E, Ix>
1358    where Ix: IndexType
1359{
1360    type Item = EdgeReference<'a, E, Ix>;
1361
1362    fn next(&mut self) -> Option<Self::Item> {
1363        self.iter.ex_find_map(|(i, edge)|
1364            edge.weight.as_ref().map(move |weight| {
1365                EdgeReference {
1366                    index: edge_index(i),
1367                    node: edge.node,
1368                    weight: weight,
1369                }
1370            }))
1371    }
1372}
1373
1374impl<'a, E, Ix> DoubleEndedIterator for EdgeReferences<'a, E, Ix>
1375    where Ix: IndexType
1376{
1377    fn next_back(&mut self) -> Option<Self::Item> {
1378        self.iter.ex_rfind_map(|(i, edge)|
1379            edge.weight.as_ref().map(move |weight| {
1380                EdgeReference {
1381                    index: edge_index(i),
1382                    node: edge.node,
1383                    weight: weight,
1384                }
1385            }))
1386    }
1387}
1388
1389
1390/// Iterator over the neighbors of a node.
1391///
1392/// Iterator element type is `NodeIndex`.
1393pub struct Neighbors<'a, E: 'a, Ix: 'a = DefaultIx>
1394{
1395    /// starting node to skip over
1396    skip_start: NodeIndex<Ix>,
1397    edges: &'a [Edge<Option<E>, Ix>],
1398    next: [EdgeIndex<Ix>; 2],
1399}
1400
1401impl<'a, E, Ix> Neighbors<'a, E, Ix>
1402    where Ix: IndexType,
1403{
1404    /// Return a “walker” object that can be used to step through the
1405    /// neighbors and edges from the origin node.
1406    ///
1407    /// Note: The walker does not borrow from the graph, this is to allow mixing
1408    /// edge walking with mutating the graph's weights.
1409    pub fn detach(&self) -> WalkNeighbors<Ix> {
1410        WalkNeighbors {
1411            inner: super::WalkNeighbors {
1412                skip_start: self.skip_start,
1413                next: self.next
1414            },
1415        }
1416    }
1417}
1418
1419impl<'a, E, Ix> Iterator for Neighbors<'a, E, Ix> where
1420    Ix: IndexType,
1421{
1422    type Item = NodeIndex<Ix>;
1423
1424    fn next(&mut self) -> Option<NodeIndex<Ix>> {
1425        // First any outgoing edges
1426        match self.edges.get(self.next[0].index()) {
1427            None => {}
1428            Some(edge) => {
1429                debug_assert!(edge.weight.is_some());
1430                self.next[0] = edge.next[0];
1431                return Some(edge.node[1]);
1432            }
1433        }
1434        // Then incoming edges
1435        // For an "undirected" iterator (traverse both incoming
1436        // and outgoing edge lists), make sure we don't double
1437        // count selfloops by skipping them in the incoming list.
1438        while let Some(edge) = self.edges.get(self.next[1].index()) {
1439            debug_assert!(edge.weight.is_some());
1440            self.next[1] = edge.next[1];
1441            if edge.node[0] != self.skip_start {
1442                return Some(edge.node[0]);
1443            }
1444        }
1445        None
1446    }
1447}
1448
1449/// A “walker” object that can be used to step through the edge list of a node.
1450///
1451/// See [*.detach()*](struct.Neighbors.html#method.detach) for more information.
1452///
1453/// The walker does not borrow from the graph, so it lets you step through
1454/// neighbors or incident edges while also mutating graph weights, as
1455/// in the following example:
1456///
1457/// ```
1458/// use petgraph::visit::Dfs;
1459/// use petgraph::Incoming;
1460/// use petgraph::stable_graph::StableGraph;
1461///
1462/// let mut gr = StableGraph::new();
1463/// let a = gr.add_node(0.);
1464/// let b = gr.add_node(0.);
1465/// let c = gr.add_node(0.);
1466/// gr.add_edge(a, b, 3.);
1467/// gr.add_edge(b, c, 2.);
1468/// gr.add_edge(c, b, 1.);
1469///
1470/// // step through the graph and sum incoming edges into the node weight
1471/// let mut dfs = Dfs::new(&gr, a);
1472/// while let Some(node) = dfs.next(&gr) {
1473///     // use a detached neighbors walker
1474///     let mut edges = gr.neighbors_directed(node, Incoming).detach();
1475///     while let Some(edge) = edges.next_edge(&gr) {
1476///         gr[node] += gr[edge];
1477///     }
1478/// }
1479///
1480/// // check the result
1481/// assert_eq!(gr[a], 0.);
1482/// assert_eq!(gr[b], 4.);
1483/// assert_eq!(gr[c], 2.);
1484/// ```
1485pub struct WalkNeighbors<Ix> {
1486    inner: super::WalkNeighbors<Ix>,
1487}
1488
1489impl<Ix: IndexType> Clone for WalkNeighbors<Ix> {
1490    clone_fields!(WalkNeighbors, inner);
1491}
1492
1493impl<Ix: IndexType> WalkNeighbors<Ix> {
1494    /// Step to the next edge and its endpoint node in the walk for graph `g`.
1495    ///
1496    /// The next node indices are always the others than the starting point
1497    /// where the `WalkNeighbors` value was created.
1498    /// For an `Outgoing` walk, the target nodes,
1499    /// for an `Incoming` walk, the source nodes of the edge.
1500    pub fn next<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1501        -> Option<(EdgeIndex<Ix>, NodeIndex<Ix>)> {
1502        self.inner.next(&g.g)
1503    }
1504
1505    pub fn next_node<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1506        -> Option<NodeIndex<Ix>>
1507    {
1508        self.next(g).map(|t| t.1)
1509    }
1510
1511    pub fn next_edge<N, E, Ty: EdgeType>(&mut self, g: &StableGraph<N, E, Ty, Ix>)
1512        -> Option<EdgeIndex<Ix>>
1513    {
1514        self.next(g).map(|t| t.0)
1515    }
1516}
1517
1518/// Iterator over the node indices of a graph.
1519pub struct NodeIndices<'a, N: 'a, Ix: 'a = DefaultIx> {
1520    iter: iter::Enumerate<slice::Iter<'a, Node<Option<N>, Ix>>>,
1521}
1522
1523impl<'a, N, Ix: IndexType> Iterator for NodeIndices<'a, N, Ix> {
1524    type Item = NodeIndex<Ix>;
1525
1526    fn next(&mut self) -> Option<Self::Item> {
1527        self.iter.ex_find_map(|(i, node)| {
1528            if node.weight.is_some() {
1529                Some(node_index(i))
1530            } else { None }
1531        })
1532    }
1533
1534    fn size_hint(&self) -> (usize, Option<usize>) {
1535        let (_, hi) = self.iter.size_hint();
1536        (0, hi)
1537    }
1538}
1539
1540impl<'a, N, Ix: IndexType> DoubleEndedIterator for NodeIndices<'a, N, Ix> {
1541    fn next_back(&mut self) -> Option<Self::Item> {
1542        self.iter.ex_rfind_map(|(i, node)| {
1543            if node.weight.is_some() {
1544                Some(node_index(i))
1545            } else { None }
1546        })
1547    }
1548}
1549
1550impl<N, E, Ty, Ix> NodeIndexable for StableGraph<N, E, Ty, Ix>
1551    where Ty: EdgeType,
1552          Ix: IndexType,
1553{
1554    /// Return an upper bound of the node indices in the graph
1555    fn node_bound(&self) -> usize {
1556        self.node_indices()
1557            .next_back()
1558            .map_or(0, |i| i.index() + 1)
1559    }
1560    fn to_index(&self, ix: NodeIndex<Ix>) -> usize { ix.index() }
1561    fn from_index(&self, ix: usize) -> Self::NodeId { NodeIndex::new(ix) }
1562}
1563
1564/// Iterator over the edge indices of a graph.
1565pub struct EdgeIndices<'a, E: 'a, Ix: 'a = DefaultIx> {
1566    iter: iter::Enumerate<slice::Iter<'a, Edge<Option<E>, Ix>>>,
1567}
1568
1569impl<'a, E, Ix: IndexType> Iterator for EdgeIndices<'a, E, Ix> {
1570    type Item = EdgeIndex<Ix>;
1571
1572    fn next(&mut self) -> Option<Self::Item> {
1573        self.iter.ex_find_map(|(i, node)| {
1574            if node.weight.is_some() {
1575                Some(edge_index(i))
1576            } else { None }
1577        })
1578    }
1579
1580    fn size_hint(&self) -> (usize, Option<usize>) {
1581        let (_, hi) = self.iter.size_hint();
1582        (0, hi)
1583    }
1584}
1585
1586impl<'a, E, Ix: IndexType> DoubleEndedIterator for EdgeIndices<'a, E, Ix> {
1587    fn next_back(&mut self) -> Option<Self::Item> {
1588        self.iter.ex_rfind_map(|(i, node)| {
1589            if node.weight.is_some() {
1590                Some(edge_index(i))
1591            } else { None }
1592        })
1593    }
1594}
1595
1596
1597#[test]
1598fn stable_graph() {
1599    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1600    let a = gr.add_node(0);
1601    let b = gr.add_node(1);
1602    let c = gr.add_node(2);
1603    let _ed = gr.add_edge(a, b, 1);
1604    println!("{:?}", gr);
1605    gr.remove_node(b);
1606    println!("{:?}", gr);
1607    let d = gr.add_node(3);
1608    println!("{:?}", gr);
1609    gr.check_free_lists();
1610    gr.remove_node(a);
1611    gr.check_free_lists();
1612    gr.remove_node(c);
1613    gr.check_free_lists();
1614    println!("{:?}", gr);
1615    gr.add_edge(d, d, 2);
1616    println!("{:?}", gr);
1617
1618    let e = gr.add_node(4);
1619    gr.add_edge(d, e, 3);
1620    println!("{:?}", gr);
1621    for neigh in gr.neighbors(d) {
1622        println!("edge {:?} -> {:?}", d, neigh);
1623    }
1624    gr.check_free_lists();
1625}
1626
1627#[test]
1628fn dfs() {
1629    use visit::Dfs;
1630
1631    let mut gr = StableGraph::<_, _>::with_capacity(0, 0);
1632    let a = gr.add_node("a");
1633    let b = gr.add_node("b");
1634    let c = gr.add_node("c");
1635    let d = gr.add_node("d");
1636    gr.add_edge(a, b, 1);
1637    gr.add_edge(a, c, 2);
1638    gr.add_edge(b, c, 3);
1639    gr.add_edge(b, d, 4);
1640    gr.add_edge(c, d, 5);
1641    gr.add_edge(d, b, 6);
1642    gr.add_edge(c, b, 7);
1643    println!("{:?}", gr);
1644
1645    let mut dfs = Dfs::new(&gr, a);
1646    while let Some(next) = dfs.next(&gr) {
1647        println!("dfs visit => {:?}, weight={:?}", next, &gr[next]);
1648    }
1649}
1650
1651#[test]
1652fn test_retain_nodes() {
1653    let mut gr = StableGraph::<_, _>::with_capacity(6, 6);
1654    let a = gr.add_node("a");
1655    let f = gr.add_node("f");
1656    let b = gr.add_node("b");
1657    let c = gr.add_node("c");
1658    let d = gr.add_node("d");
1659    let e = gr.add_node("e");
1660    gr.add_edge(a, b, 1);
1661    gr.add_edge(a, c, 2);
1662    gr.add_edge(b, c, 3);
1663    gr.add_edge(b, d, 4);
1664    gr.add_edge(c, d, 5);
1665    gr.add_edge(d, b, 6);
1666    gr.add_edge(c, b, 7);
1667    gr.add_edge(d, e, 8);
1668    gr.remove_node(f);
1669
1670    assert_eq!(gr.node_count(), 5);
1671    assert_eq!(gr.edge_count(), 8);
1672    gr.retain_nodes(|frozen_gr, ix| {frozen_gr[ix] >= "c"});
1673    assert_eq!(gr.node_count(), 3);
1674    assert_eq!(gr.edge_count(), 2);
1675
1676    gr.check_free_lists();
1677}