Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions library/alloc/src/collections/binary_heap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,33 @@ impl<T: Ord, A: Allocator> BinaryHeap<T, A> {
})
}

/// Removes and returns the greatest item from the binary heap if the predicate
/// returns `true`, or [`None`] if the predicate returns false or the heap
/// is empty (the predicate will not be called in that case).
///
/// # Examples
///
/// ```
/// #![feature(binary_heap_pop_if)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::from([1, 2]);
/// let pred = |x: &i32| *x % 2 == 0;
///
/// assert_eq!(heap.pop_if(pred), Some(2));
/// assert_eq!(heap.as_slice(), [1]);
/// assert_eq!(heap.pop_if(pred), None);
/// assert_eq!(heap.as_slice(), [1]);
/// ```
///
/// # Time complexity
///
/// The worst case cost of `pop_if` on a heap containing *n* elements is *O*(log(*n*)).
#[unstable(feature = "binary_heap_pop_if", issue = "151828")]
pub fn pop_if(&mut self, predicate: impl FnOnce(&T) -> bool) -> Option<T> {
let first = self.peek()?;
if predicate(first) { self.pop() } else { None }
}

/// Pushes an item onto the binary heap.
///
/// # Examples
Expand Down
12 changes: 12 additions & 0 deletions library/alloctests/tests/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,18 @@ fn test_peek_and_pop() {
}
}

#[test]
fn test_pop_if() {
let data = vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
let mut sorted = data.clone();
sorted.sort();
let mut heap = BinaryHeap::from(data);
while let Some(popped) = heap.pop_if(|x| *x > 2) {
assert_eq!(popped, sorted.pop().unwrap());
}
assert_eq!(heap.into_sorted_vec(), vec![0, 1, 2]);
}

#[test]
fn test_peek_mut() {
let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];
Expand Down
1 change: 1 addition & 0 deletions library/alloctests/tests/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![feature(allocator_api)]
#![feature(binary_heap_pop_if)]
#![feature(const_heap)]
#![feature(deque_extend_front)]
#![feature(iter_array_chunks)]
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/mem/maybe_dangling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use crate::{mem, ptr};
/// mem::forget(boxed); // <-- this is UB!
/// ```
///
/// Even though the `Box`e's destructor is not run (and thus we don't have a double free bug), this
/// Even though the `Box`'s destructor is not run (and thus we don't have a double free bug), this
/// code is still UB. This is because when moving `boxed` into `forget`, its validity invariants
/// are asserted, causing UB since the `Box` is dangling. The safety comment is as such wrong, as
/// moving the `boxed` variable as part of the `forget` call *is* a use.
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/ops/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -773,7 +773,7 @@ impl<T: Copy> Bound<&T> {
/// ```
#[unstable(feature = "bound_copied", issue = "145966")]
#[must_use]
pub fn copied(self) -> Bound<T> {
pub const fn copied(self) -> Bound<T> {
match self {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(x) => Bound::Included(*x),
Expand Down
45 changes: 44 additions & 1 deletion library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@
use crate::clone::TrivialClone;
use crate::iter::{self, FusedIterator, TrustedLen};
use crate::marker::Destruct;
use crate::ops::{self, ControlFlow, Deref, DerefMut};
use crate::ops::{self, ControlFlow, Deref, DerefMut, Residual, Try};
use crate::panicking::{panic, panic_display};
use crate::pin::Pin;
use crate::{cmp, convert, hint, mem, slice};
Expand Down Expand Up @@ -1816,6 +1816,49 @@ impl<T> Option<T> {
unsafe { self.as_mut().unwrap_unchecked() }
}

/// If the option is `None`, calls the closure and inserts its output if successful.
///
/// If the closure returns a residual value such as `Err` or `None`,
/// that residual value is returned and nothing is inserted.
///
/// If the option is `Some`, nothing is inserted.
///
/// Unless a residual is returned, a mutable reference to the value
/// of the option will be output.
///
/// # Examples
///
/// ```
/// #![feature(option_get_or_try_insert_with)]
/// let mut o1: Option<u32> = None;
/// let mut o2: Option<u8> = None;
///
/// let number = "12345";
///
/// assert_eq!(o1.get_or_try_insert_with(|| number.parse()).copied(), Ok(12345));
/// assert!(o2.get_or_try_insert_with(|| number.parse()).is_err());
/// assert_eq!(o1, Some(12345));
/// assert_eq!(o2, None);
/// ```
#[inline]
#[unstable(feature = "option_get_or_try_insert_with", issue = "143648")]
pub fn get_or_try_insert_with<'a, R, F>(
&'a mut self,
f: F,
) -> <R::Residual as Residual<&'a mut T>>::TryType
where
F: FnOnce() -> R,
R: Try<Output = T, Residual: Residual<&'a mut T>>,
{
if let None = self {
*self = Some(f()?);
}
// SAFETY: a `None` variant for `self` would have been replaced by a `Some`
// variant in the code above.

Try::from_output(unsafe { self.as_mut().unwrap_unchecked() })
}

/////////////////////////////////////////////////////////////////////////
// Misc
/////////////////////////////////////////////////////////////////////////
Expand Down
44 changes: 6 additions & 38 deletions library/core/src/slice/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -910,29 +910,7 @@ where
R: [const] ops::RangeBounds<usize> + [const] Destruct,
{
let len = bounds.end;

let end = match range.end_bound() {
ops::Bound::Included(&end) if end >= len => slice_index_fail(0, end, len),
// Cannot overflow because `end < len` implies `end < usize::MAX`.
ops::Bound::Included(&end) => end + 1,

ops::Bound::Excluded(&end) if end > len => slice_index_fail(0, end, len),
ops::Bound::Excluded(&end) => end,
ops::Bound::Unbounded => len,
};

let start = match range.start_bound() {
ops::Bound::Excluded(&start) if start >= end => slice_index_fail(start, end, len),
// Cannot overflow because `start < end` implies `start < usize::MAX`.
ops::Bound::Excluded(&start) => start + 1,

ops::Bound::Included(&start) if start > end => slice_index_fail(start, end, len),
ops::Bound::Included(&start) => start,

ops::Bound::Unbounded => 0,
};

ops::Range { start, end }
into_slice_range(len, (range.start_bound().copied(), range.end_bound().copied()))
}

/// Performs bounds checking of a range without panicking.
Expand Down Expand Up @@ -972,20 +950,8 @@ where
R: ops::RangeBounds<usize>,
{
let len = bounds.end;

let start = match range.start_bound() {
ops::Bound::Included(&start) => start,
ops::Bound::Excluded(start) => start.checked_add(1)?,
ops::Bound::Unbounded => 0,
};

let end = match range.end_bound() {
ops::Bound::Included(end) => end.checked_add(1)?,
ops::Bound::Excluded(&end) => end,
ops::Bound::Unbounded => len,
};

if start > end || end > len { None } else { Some(ops::Range { start, end }) }
let r = into_range(len, (range.start_bound().copied(), range.end_bound().copied()))?;
if r.start > r.end || r.end > len { None } else { Some(r) }
}

/// Converts a pair of `ops::Bound`s into `ops::Range` without performing any
Expand All @@ -1011,6 +977,7 @@ pub(crate) const fn into_range_unchecked(
/// Converts pair of `ops::Bound`s into `ops::Range`.
/// Returns `None` on overflowing indices.
#[rustc_const_unstable(feature = "const_range", issue = "none")]
#[inline]
pub(crate) const fn into_range(
len: usize,
(start, end): (ops::Bound<usize>, ops::Bound<usize>),
Expand All @@ -1036,7 +1003,8 @@ pub(crate) const fn into_range(

/// Converts pair of `ops::Bound`s into `ops::Range`.
/// Panics on overflowing indices.
pub(crate) fn into_slice_range(
#[inline]
pub(crate) const fn into_slice_range(
len: usize,
(start, end): (ops::Bound<usize>, ops::Bound<usize>),
) -> ops::Range<usize> {
Expand Down
Loading
Loading