hydrate_data/
ordered_set.rs1use hydrate_base::hashing::HashSet;
2use std::hash::Hash;
3
4#[derive(Clone, Default)]
5pub struct OrderedSet<T: Eq + PartialEq + Hash + Clone> {
6 vec: Vec<T>,
7 set: HashSet<T>,
9}
10
11impl<T: Eq + PartialEq + Hash + Clone> PartialEq for OrderedSet<T> {
12 fn eq(
13 &self,
14 other: &Self,
15 ) -> bool {
16 self.vec == other.vec
17 }
18}
19
20impl<'a, T: Eq + PartialEq + Hash + Clone> IntoIterator for &'a OrderedSet<T> {
21 type Item = &'a T;
22 type IntoIter = std::slice::Iter<'a, T>;
23
24 fn into_iter(self) -> Self::IntoIter {
25 self.iter()
26 }
27}
28
29impl<T: std::fmt::Debug + Eq + PartialEq + Hash + Clone> std::fmt::Debug for OrderedSet<T> {
30 fn fmt(
31 &self,
32 f: &mut std::fmt::Formatter<'_>,
33 ) -> std::fmt::Result {
34 f.debug_struct("OrderedSet")
35 .field("vec", &self.vec)
36 .finish()
38 }
39}
40
41impl<T: Eq + PartialEq + Hash + Clone> OrderedSet<T> {
42 pub fn iter(&self) -> std::slice::Iter<T> {
43 self.vec.iter()
44 }
45
46 pub fn contains(
47 &self,
48 value: &T,
49 ) -> bool {
50 self.set.contains(value)
51 }
52
53 pub fn try_insert_at_position(
55 &mut self,
56 index: usize,
57 value: T,
58 ) -> bool {
59 let is_newly_inserted = self.set.insert(value.clone());
60 if is_newly_inserted {
61 self.vec.insert(index, value);
62 }
63
64 is_newly_inserted
65 }
66
67 pub fn try_insert_at_end(
69 &mut self,
70 value: T,
71 ) -> bool {
72 let is_newly_inserted = self.set.insert(value.clone());
73 if is_newly_inserted {
74 self.vec.push(value);
75 }
76
77 is_newly_inserted
78 }
79
80 pub fn remove(
81 &mut self,
82 value: &T,
83 ) -> bool {
84 let removed = self.set.remove(value);
85 if removed {
86 self.vec
87 .remove(self.vec.iter().position(|x| x == value).unwrap());
88 }
89
90 removed
91 }
92
93 pub fn is_empty(&self) -> bool {
94 self.vec.is_empty()
95 }
96}