Skip to content

Commit 3f72522

Browse files
committed
tidy up contains_or_insert to be more efficient
1 parent 3a621b7 commit 3f72522

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

src/recursion_guard.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -95,29 +95,26 @@ impl<T: Eq + Hash + Clone> SmallContainer<T> {
9595
pub fn contains_or_insert(&mut self, v: T) -> Option<usize> {
9696
match self {
9797
Self::Array(array) => {
98-
let mut first_slot: Option<usize> = None;
99-
for (index, op_value) in array.iter().enumerate() {
98+
for (index, op_value) in array.iter_mut().enumerate() {
10099
if let Some(existing) = op_value {
101100
if existing == &v {
102101
return None;
103102
}
104103
} else {
105-
first_slot = first_slot.or(Some(index));
104+
*op_value = Some(v);
105+
return Some(index);
106106
}
107107
}
108-
if let Some(index) = first_slot {
109-
array[index] = Some(v);
110-
first_slot
111-
} else {
112-
let mut set: AHashSet<T> = AHashSet::with_capacity(ARRAY_SIZE + 1);
113-
for existing in array.iter_mut() {
114-
set.insert(existing.take().unwrap());
115-
}
116-
set.insert(v);
117-
*self = Self::Set(set);
118-
// id doesn't matter here as we'll be removing from a set
119-
Some(0)
108+
109+
// No array slots exist; convert to set
110+
let mut set: AHashSet<T> = AHashSet::with_capacity(ARRAY_SIZE + 1);
111+
for existing in array.iter_mut() {
112+
set.insert(existing.take().unwrap());
120113
}
114+
set.insert(v);
115+
*self = Self::Set(set);
116+
// id doesn't matter here as we'll be removing from a set
117+
Some(0)
121118
}
122119
// https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.insert
123120
// "If the set did not have this value present, `true` is returned."
@@ -135,6 +132,7 @@ impl<T: Eq + Hash + Clone> SmallContainer<T> {
135132
pub fn remove(&mut self, v: &T, index: usize) {
136133
match self {
137134
Self::Array(array) => {
135+
debug_assert!(array[index].as_ref() == Some(v), "remove did not match insert");
138136
array[index] = None;
139137
}
140138
Self::Set(set) => {

0 commit comments

Comments
 (0)