Skip to main content

zrx_graph/graph/iter/
group_sinks.rs

1// Copyright (c) 2025-2026 Zensical and contributors
2
3// SPDX-License-Identifier: MIT
4// All contributions are certified under the DCO
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to
8// deal in the Software without restriction, including without limitation the
9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10// sell copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22// IN THE SOFTWARE.
23
24// ----------------------------------------------------------------------------
25
26//! Iterator over sinks of each key-group.
27
28use std::collections::btree_map::{self, BTreeMap};
29
30use crate::graph::topology::{Topology, Transitive};
31use crate::graph::Graph;
32
33// ----------------------------------------------------------------------------
34// Structs
35// ----------------------------------------------------------------------------
36
37/// Iterator over sinks of each key-group.
38pub struct GroupSinks<'a, K> {
39    /// Graph topology.
40    topology: &'a Topology<Transitive>,
41    /// Iterator over groups.
42    inner: btree_map::IntoIter<K, Vec<usize>>,
43}
44
45// ----------------------------------------------------------------------------
46// Implementations
47// ----------------------------------------------------------------------------
48
49impl<T> Graph<T, Transitive> {
50    /// Creates an iterator over the sinks of each key-group.
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// # use std::error::Error;
56    /// # fn main() -> Result<(), Box<dyn Error>> {
57    /// use zrx_graph::Graph;
58    ///
59    /// // Create graph builder and add nodes
60    /// let mut builder = Graph::builder();
61    /// let a = builder.add_node("a");
62    /// let b = builder.add_node("b");
63    /// let c = builder.add_node("c");
64    ///
65    /// // Create edges between nodes
66    /// builder.add_edge(a, b)?;
67    /// builder.add_edge(b, c)?;
68    ///
69    /// // Create graph from builder
70    /// let graph = builder.build().into_transitive();
71    ///
72    /// // Create iterator over sinks of key-groups
73    /// for (key, nodes) in graph.group_sinks(|node| node.len()) {
74    ///     println!("{key}: {nodes:?}");
75    /// }
76    /// # Ok(())
77    /// # }
78    /// ```
79    #[must_use]
80    pub fn group_sinks<'a, F, K>(&'a self, f: F) -> GroupSinks<'a, K>
81    where
82        F: Fn(&'a T) -> K,
83        K: Ord,
84    {
85        let mut groups: BTreeMap<K, Vec<usize>> = BTreeMap::new();
86        for node in self {
87            groups.entry(f(&self[node])).or_default().push(node);
88        }
89        GroupSinks {
90            topology: &self.topology,
91            inner: groups.into_iter(),
92        }
93    }
94}
95
96// ----------------------------------------------------------------------------
97// Trait implementations
98// ----------------------------------------------------------------------------
99
100impl<K> Iterator for GroupSinks<'_, K> {
101    type Item = (K, Vec<usize>);
102
103    /// Returns the next key-group.
104    fn next(&mut self) -> Option<Self::Item> {
105        let (key, nodes) = self.inner.next()?;
106        let iter = nodes.iter().copied().filter(|&node| {
107            !nodes.iter().any(|&descendant| {
108                node != descendant && self.topology.has_path(node, descendant)
109            })
110        });
111
112        // Return key-group
113        Some((key, iter.collect()))
114    }
115}