Skip to content

Commit 13de0f7

Browse files
committed
feat(data_structures): add Stack::clear
1 parent 909a086 commit 13de0f7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

crates/oxc_data_structures/src/stack/standard.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,25 @@ impl<T> Stack<T> {
334334
unsafe { self.cursor.read() }
335335
}
336336

337+
/// Clear the stack, removing all values.
338+
///
339+
/// Note that this method has no effect on the allocated capacity
340+
/// of the stack.
341+
#[inline]
342+
pub fn clear(&mut self) {
343+
if self.is_empty() {
344+
return;
345+
}
346+
347+
debug_assert!(self.end > self.start);
348+
349+
// SAFETY: Checked above that stack is not empty, so stack is allocated.
350+
// Stack contains `self.len()` initialized entries, starting at `self.start`
351+
unsafe { self.drop_contents() };
352+
// Move cursor back to start. This is equivalent to setting len to 0
353+
self.cursor = self.start;
354+
}
355+
337356
/// Get number of entries on stack.
338357
#[inline]
339358
pub fn len(&self) -> usize {
@@ -588,6 +607,20 @@ mod tests {
588607
assert_len_cap_last!(stack, 2, 4, Some(&22));
589608
}
590609

610+
#[test]
611+
fn clear() {
612+
let mut stack = Stack::<u64>::new();
613+
assert_len_cap_last!(stack, 0, 0, None);
614+
615+
stack.clear();
616+
assert_len_cap_last!(stack, 0, 0, None);
617+
618+
stack.push(10);
619+
assert_len_cap_last!(stack, 1, 4, Some(&10));
620+
stack.clear();
621+
assert_len_cap_last!(stack, 0, 4, None);
622+
}
623+
591624
#[test]
592625
#[expect(clippy::items_after_statements)]
593626
fn drop() {

0 commit comments

Comments
 (0)