Skip to main content

rust_igraph/algorithms/properties/
edgelist.rs

1//! Edge list extraction (ALGO-PR-042).
2//!
3//! Counterpart of `igraph_get_edgelist()` in
4//! `references/igraph/src/misc/conversion.c:327-329`.
5//!
6//! Returns all edges of a graph in edge-ID order.
7
8use crate::core::{Graph, IgraphResult, VertexId};
9
10/// Return all edges of the graph as a list of `(source, target)` pairs.
11///
12/// Edges are returned in edge-ID order (0, 1, 2, …).
13///
14/// # Examples
15///
16/// ```
17/// use rust_igraph::{create, get_edgelist};
18///
19/// let g = create(&[(0, 1), (1, 2), (2, 0)], 3, false).unwrap();
20/// let el = get_edgelist(&g).unwrap();
21/// assert_eq!(el.len(), 3);
22/// ```
23pub fn get_edgelist(graph: &Graph) -> IgraphResult<Vec<(VertexId, VertexId)>> {
24    let ecount = graph.ecount();
25    let mut result = Vec::with_capacity(ecount);
26    for eid in 0..ecount {
27        #[allow(clippy::cast_possible_truncation)]
28        let e = eid as u32;
29        result.push(graph.edge(e)?);
30    }
31    Ok(result)
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37    use crate::core::Graph;
38
39    #[test]
40    fn empty_graph() {
41        let g = Graph::new(0, false).unwrap();
42        let el = get_edgelist(&g).unwrap();
43        assert!(el.is_empty());
44    }
45
46    #[test]
47    fn no_edges() {
48        let g = Graph::new(5, false).unwrap();
49        let el = get_edgelist(&g).unwrap();
50        assert!(el.is_empty());
51    }
52
53    #[test]
54    fn triangle_undirected() {
55        let mut g = Graph::new(3, false).unwrap();
56        g.add_edges(vec![(0, 1), (1, 2), (2, 0)]).unwrap();
57        let el = get_edgelist(&g).unwrap();
58        assert_eq!(el.len(), 3);
59    }
60
61    #[test]
62    fn directed_edges_preserved() {
63        let mut g = Graph::new(3, true).unwrap();
64        g.add_edges(vec![(0, 1), (1, 2)]).unwrap();
65        let el = get_edgelist(&g).unwrap();
66        assert_eq!(el.len(), 2);
67        assert_eq!(el[0], (0, 1));
68        assert_eq!(el[1], (1, 2));
69    }
70
71    #[test]
72    fn single_vertex_no_edges() {
73        let g = Graph::new(1, false).unwrap();
74        let el = get_edgelist(&g).unwrap();
75        assert!(el.is_empty());
76    }
77
78    #[test]
79    fn self_loop() {
80        let mut g = Graph::new(2, false).unwrap();
81        g.add_edges(vec![(0, 0), (0, 1)]).unwrap();
82        let el = get_edgelist(&g).unwrap();
83        assert_eq!(el.len(), 2);
84    }
85}