Skip to main content

mid_tools/
closure_builder.rs

1use std::{
2    borrow::BorrowMut,
3    collections::{BTreeSet, VecDeque},
4    hash::Hash,
5};
6
7use hashbrown::HashSet;
8
9pub trait SetInsert<T> {
10    fn insert(&mut self, t: T) -> bool;
11}
12
13impl<T: Eq + Hash> SetInsert<T> for HashSet<T> {
14    #[inline]
15    fn insert(&mut self, t: T) -> bool { HashSet::insert(self, t) }
16}
17
18impl<T: Ord> SetInsert<T> for BTreeSet<T> {
19    #[inline]
20    fn insert(&mut self, t: T) -> bool { BTreeSet::insert(self, t) }
21}
22
23#[derive(Debug)]
24pub struct ClosureBuilder<T>(VecDeque<T>);
25
26impl<T> Default for ClosureBuilder<T> {
27    #[inline]
28    fn default() -> Self { Self(VecDeque::new()) }
29}
30
31impl<T> ClosureBuilder<T> {
32    #[inline]
33    pub fn init<I: IntoIterator<Item = T>>(&mut self, it: I) {
34        assert!(self.0.is_empty());
35        self.extend(it);
36    }
37}
38
39impl<T: Clone> ClosureBuilder<T> {
40    pub fn solve<S: BorrowMut<U>, U: SetInsert<T>, I: IntoIterator<Item = T>>(
41        &mut self,
42        mut set: S,
43        f: impl Fn(T) -> I,
44    ) -> S {
45        {
46            let set = set.borrow_mut();
47
48            while let Some(el) = self.0.pop_front() {
49                if set.insert(el.clone()) {
50                    self.0.extend(f(el));
51                }
52            }
53        }
54
55        set
56    }
57}
58
59impl<T> Extend<T> for ClosureBuilder<T> {
60    #[inline]
61    fn extend<I: IntoIterator<Item = T>>(&mut self, it: I) { self.0.extend(it); }
62}