From fa3195651fc8b354514674f3b7c7cc324778b623 Mon Sep 17 00:00:00 2001 From: Kruno Tomola Fabro Date: Thu, 25 Apr 2024 19:35:48 +0200 Subject: [PATCH] Add peek --- src/lib.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index bccc96d..e9e5361 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -150,6 +150,19 @@ impl RadixHeapMap { ret } + /// Return the greatest element from the heap without removing it, or `None` if + /// empty. + /// + /// If there is a tie between multiple elements, the last inserted element + /// will be peeked first. + #[inline] + pub fn peek(&mut self) -> Option<&(K, V)> { + if self.buckets[0].is_empty() { + self.constrain(); + } + self.buckets[0].last() + } + /// Returns the number of elements in the heap #[inline] pub fn len(&self) -> usize { @@ -808,4 +821,22 @@ mod tests { vec.sort(); assert_eq!(vec, vec![(1, 2), (5, 4)]); } + + #[test] + fn peek() { + let mut heap = RadixHeapMap::new(); + heap.push(1, 2); + heap.push(5, 4); + heap.push(7, 1); + + assert_eq!(Some(&(7, 1)), heap.peek()); + assert_eq!(Some(&(7, 1)), heap.peek()); + assert_eq!(Some((7, 1)), heap.pop()); + assert_eq!(Some(&(5, 4)), heap.peek()); + assert_eq!(Some((5, 4)), heap.pop()); + assert_eq!(Some(&(1, 2)), heap.peek()); + assert_eq!(Some((1, 2)), heap.pop()); + assert_eq!(None, heap.peek()); + assert_eq!(None, heap.pop()); + } }