ankurah_core/util/
iterable.rs

1use std::{collections::HashSet, hash::BuildHasher};
2
3/// Trait for types that can provide an iterator over their contents without consuming self.
4/// This allows uniform iteration over both single items (`&T`) and collections (`&HashSet<T>`).
5pub trait Iterable<T> {
6    type Iter<'a>: Iterator<Item = &'a T>
7    where
8        Self: 'a,
9        T: 'a;
10
11    fn iterable(&self) -> Self::Iter<'_>;
12}
13
14// Implementation for a single reference - treats it as a collection of one
15impl<T> Iterable<T> for T {
16    type Iter<'a>
17        = std::iter::Once<&'a T>
18    where
19        Self: 'a,
20        T: 'a;
21
22    fn iterable(&self) -> Self::Iter<'_> { std::iter::once(self) }
23}
24
25// Implementation for a HashSet reference
26impl<T, S: BuildHasher> Iterable<T> for HashSet<T, S> {
27    type Iter<'a>
28        = std::collections::hash_set::Iter<'a, T>
29    where
30        Self: 'a,
31        T: 'a;
32
33    fn iterable(&self) -> Self::Iter<'_> { HashSet::iter(self) }
34}
35
36// Implementation for a Vec reference
37impl<T> Iterable<T> for Vec<T> {
38    type Iter<'a>
39        = std::slice::Iter<'a, T>
40    where
41        Self: 'a,
42        T: 'a;
43
44    fn iterable(&self) -> Self::Iter<'_> { (**self).iter() }
45}