Skip to content

Commit 9587e89

Browse files
authored
Add BinaryHeap::replace_cmp() and unsafe version BinaryHeap::replace_cmp_raw() (sekineh#26)
1 parent a989137 commit 9587e89

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99
### Added
1010

1111
* generic constructor `from_vec_cmp_raw()`.
12+
* `replace_cmp()` which replace the comparator of heap and its unsafe version `replace_cmp_raw()`.
1213

1314
## [0.3.0] - 2020-07-08
1415

src/binary_heap.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,56 @@ where
607607
}
608608

609609
impl<T, C: Compare<T>> BinaryHeap<T, C> {
610+
/// Replaces the comparator of binary heap.
611+
///
612+
/// # Examples
613+
///
614+
/// Basic usage:
615+
///
616+
/// ```
617+
/// use binary_heap_plus::*;
618+
/// use compare::Compare;
619+
/// use std::cmp::Ordering;
620+
///
621+
/// struct Comparator {
622+
/// ascending: bool
623+
/// }
624+
///
625+
/// impl Compare<i32> for Comparator {
626+
/// fn compare(&self,l: &i32,r: &i32) -> Ordering {
627+
/// if self.ascending {
628+
/// r.cmp(l)
629+
/// } else {
630+
/// l.cmp(r)
631+
/// }
632+
/// }
633+
/// }
634+
///
635+
/// // construct a heap in ascending order.
636+
/// let mut heap = BinaryHeap::from_vec_cmp(vec![3, 1, 5], Comparator { ascending: true });
637+
///
638+
/// // replace the comparor
639+
/// heap.replace_cmp(Comparator { ascending: false });
640+
/// assert_eq!(heap.into_iter_sorted().collect::<Vec<_>>(), vec![5, 3, 1]);
641+
/// ```
642+
#[inline]
643+
pub fn replace_cmp(&mut self, cmp: C) {
644+
unsafe {
645+
self.replace_cmp_raw(cmp, true);
646+
}
647+
}
648+
649+
/// Replaces the comparator of binary heap.
650+
///
651+
/// # Safety
652+
/// User is responsible for providing valid `rebuild` value.
653+
pub unsafe fn replace_cmp_raw(&mut self, cmp: C, rebuild: bool) {
654+
self.cmp = cmp;
655+
if rebuild && !self.data.is_empty() {
656+
self.rebuild();
657+
}
658+
}
659+
610660
/// Returns an iterator visiting all values in the underlying vector, in
611661
/// arbitrary order.
612662
///

0 commit comments

Comments
 (0)