Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add is_sorted to Iterator and [T] #55045

Merged
merged 7 commits into from
Jan 21, 2019
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
11 changes: 11 additions & 0 deletions src/doc/unstable-book/src/library-features/is-sorted.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# `is_sorted`

The tracking issue for this feature is: [#53485]

[#53485]: https://github.com/rust-lang/rust/issues/53485

------------------------

Add the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`;
add the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to
`Iterator`.
89 changes: 89 additions & 0 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2605,6 +2605,95 @@ pub trait Iterator {
}
}
}

/// Checks if the elements of this iterator are sorted.
///
/// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
/// iterator yields exactly zero or one element, `true` is returned.
///
/// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
/// implies that this function returns `false` if any two consecutive items are not
/// comparable.
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!([1, 2, 2, 9].iter().is_sorted());
/// assert!(![1, 3, 2, 4].iter().is_sorted());
/// assert!([0].iter().is_sorted());
/// assert!(std::iter::empty::<i32>().is_sorted());
/// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted(self) -> bool
where
Self: Sized,
Self::Item: PartialOrd,
{
self.is_sorted_by(|a, b| a.partial_cmp(b))
}

/// Checks if the elements of this iterator are sorted using the given comparator function.
///
/// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
/// function to determine the ordering of two elements. Apart from that, it's equivalent to
/// [`is_sorted`]; see its documentation for more information.
///
/// [`is_sorted`]: trait.Iterator.html#method.is_sorted
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted_by<F>(mut self, mut compare: F) -> bool
kleimkuhler marked this conversation as resolved.
Show resolved Hide resolved
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>
{
let mut last = match self.next() {
Some(e) => e,
None => return true,
};

while let Some(curr) = self.next() {
if compare(&last, &curr)
.map(|o| o == Ordering::Greater)
.unwrap_or(true)
{
return false;
}
last = curr;
}

true
}

/// Checks if the elements of this iterator are sorted using the given key extraction
/// function.
///
/// Instead of comparing the iterator's elements directly, this function compares the keys of
/// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
/// its documentation for more information.
///
/// [`is_sorted`]: trait.Iterator.html#method.is_sorted
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
/// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
/// ```
#[inline]
kleimkuhler marked this conversation as resolved.
Show resolved Hide resolved
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
fn is_sorted_by_key<F, K>(self, mut f: F) -> bool
where
Self: Sized,
F: FnMut(&Self::Item) -> K,
K: PartialOrd
{
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
}
}

/// Select an element from an iterator based on the given "projection"
Expand Down
1 change: 1 addition & 0 deletions src/libcore/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
#![feature(extern_types)]
#![feature(fundamental)]
#![feature(intrinsics)]
#![feature(is_sorted)]
#![feature(iter_once_with)]
#![feature(lang_items)]
#![feature(link_llvm_intrinsics)]
Expand Down
97 changes: 93 additions & 4 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1783,7 +1783,7 @@ impl<T> [T] {
/// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
/// a[1..5].rotate_left(1);
/// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
/// ```
/// ```
#[stable(feature = "slice_rotate", since = "1.26.0")]
pub fn rotate_left(&mut self, mid: usize) {
assert!(mid <= self.len());
Expand Down Expand Up @@ -2250,6 +2250,77 @@ impl<T> [T] {
from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
}
}

/// Checks if the elements of this slice are sorted.
///
/// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
/// slice yields exactly zero or one element, `true` is returned.
///
/// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
/// implies that this function returns `false` if any two consecutive items are not
/// comparable.
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
/// let empty: [i32; 0] = [];
///
/// assert!([1, 2, 2, 9].is_sorted());
/// assert!(![1, 3, 2, 4].is_sorted());
/// assert!([0].is_sorted());
/// assert!(empty.is_sorted());
/// assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
/// ```
#[inline]
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
pub fn is_sorted(&self) -> bool
where
T: PartialOrd,
{
self.is_sorted_by(|a, b| a.partial_cmp(b))
}

/// Checks if the elements of this slice are sorted using the given comparator function.
///
/// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
/// function to determine the ordering of two elements. Apart from that, it's equivalent to
/// [`is_sorted`]; see its documentation for more information.
///
/// [`is_sorted`]: #method.is_sorted
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
where
F: FnMut(&T, &T) -> Option<Ordering>
{
self.iter().is_sorted_by(|a, b| compare(*a, *b))
}

/// Checks if the elements of this slice are sorted using the given key extraction function.
///
/// Instead of comparing the slice's elements directly, this function compares the keys of the
/// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
/// documentation for more information.
///
/// [`is_sorted`]: #method.is_sorted
///
/// # Examples
///
/// ```
/// #![feature(is_sorted)]
///
/// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
/// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
/// ```
#[inline]
kleimkuhler marked this conversation as resolved.
Show resolved Hide resolved
#[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
pub fn is_sorted_by_key<F, K>(&self, mut f: F) -> bool
where
F: FnMut(&T) -> K,
K: PartialOrd
{
self.is_sorted_by(|a, b| f(a).partial_cmp(&f(b)))
}
}

#[lang = "slice_u8"]
Expand Down Expand Up @@ -2773,7 +2844,13 @@ macro_rules! len {

// The shared definition of the `Iter` and `IterMut` iterators
macro_rules! iterator {
(struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
(
struct $name:ident -> $ptr:ty,
$elem:ty,
$raw_mut:tt,
{$( $mut_:tt )*},
{$($extra:tt)*}
) => {
impl<'a, T> $name<'a, T> {
// Helper function for creating a slice from the iterator.
#[inline(always)]
Expand Down Expand Up @@ -2950,6 +3027,8 @@ macro_rules! iterator {
i
})
}

$($extra)*
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down Expand Up @@ -3087,7 +3166,17 @@ impl<'a, T> Iter<'a, T> {
}
}

iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, {
fn is_sorted_by<F>(self, mut compare: F) -> bool
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
{
self.as_slice().windows(2).all(|w| {
compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
})
}
}}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Clone for Iter<'_, T> {
Expand Down Expand Up @@ -3188,7 +3277,7 @@ impl<'a, T> IterMut<'a, T> {
}
}

iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}

/// An internal abstraction over the splitting iterators, so that
/// splitn, splitn_mut etc can be implemented once.
Expand Down
13 changes: 13 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2235,3 +2235,16 @@ fn test_monad_laws_associativity() {
assert_eq!((0..10).flat_map(f).flat_map(g).sum::<usize>(),
(0..10).flat_map(|x| f(x).flat_map(g)).sum::<usize>());
}

#[test]
fn test_is_sorted() {
assert!([1, 2, 2, 9].iter().is_sorted());
assert!(![1, 3, 2].iter().is_sorted());
assert!([0].iter().is_sorted());
assert!(std::iter::empty::<i32>().is_sorted());
assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LukasKalbertodt shouldn't is_sorted return true here ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a test case taken from the RFC for a heads up.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kleimkuhler I think this is correct. These are some other tests from the discussion:

[nan, nan, nan]
[1.0, nan, 2.0]
[2.0, nan, 1.0]
[2.0, nan, 1.0, 7.0]
[2.0, nan, 1.0, 0.0]
[-nan, -1.0, 0.0, 1.0, nan]
[nan, -nan, -1.0, 0.0, 1.0]
[1.0, nan, -nan, -1.0, 0.0]
[0.0, 1.0, nan, -nan, -1.0]
[-1.0, 0.0, 1.0, nan, -nan]

IIRC is_sorted does return false for all of these, but is_sorted_by(|a,b| a < b) returns true for some of these. It would be great to cover these for f32 and f64.

@ExpHP also suggested:

// using `Suffix::from`
["a", "aa", "aaa", "b", "bb", "bbb"]
[ "",  "a",  "aa",  "",  "b",  "bb"]

// using set / subset:
[set![3], set![2]]
[set![2], set![3]]
[set![2], set![3], set![2, 3]]
[set![2], set![2, 3], set![3]]
[set![2], set![2, 3], set![5]]
[set![2, 3], set![5], set![2]]

See this comment (rust-lang/rfcs#2351 (comment)) and the associated gist with the test source code (https://gist.github.com/ExpHP/c23b51f0a9f5f94f2375c93137299604).

assert!([-2, -1, 0, 3].iter().is_sorted());
assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
assert!(!["c", "bb", "aaa"].iter().is_sorted());
assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
}
kleimkuhler marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#![feature(flt2dec)]
#![feature(fmt_internals)]
#![feature(hashmap_internals)]
#![feature(is_sorted)]
#![feature(iter_copied)]
#![feature(iter_nth_back)]
#![feature(iter_once_with)]
Expand Down
15 changes: 15 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,3 +1317,18 @@ fn test_copy_within_panics_src_inverted() {
// 2 is greater than 1, so this range is invalid.
bytes.copy_within(2..1, 0);
}

#[test]
fn test_is_sorted() {
let empty: [i32; 0] = [];

assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
assert!([-2, -1, 0, 3].is_sorted());
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
assert!(!["c", "bb", "aaa"].is_sorted());
assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to add many optimizations in the future, so we should try to already add a comprehensive test suite, e.g., see https://github.com/gnzlbg/is_sorted/tree/master/tests for inspiration, but @LukasKalbertodt RFC and associated discussion also covered many interesting cases.

13 changes: 13 additions & 0 deletions src/test/ui/feature-gates/feature-gate-is_sorted.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fn main() {
// Assert `Iterator` methods are feature gated
assert!([1, 2, 2, 9].iter().is_sorted());
//~^ ERROR: use of unstable library feature 'is_sorted': new API
assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
//~^ ERROR: use of unstable library feature 'is_sorted': new API

// Assert `[T]` methods are feature gated
assert!([1, 2, 2, 9].is_sorted());
//~^ ERROR: use of unstable library feature 'is_sorted': new API
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
//~^ ERROR: use of unstable library feature 'is_sorted': new API
}
35 changes: 35 additions & 0 deletions src/test/ui/feature-gates/feature-gate-is_sorted.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
error[E0658]: use of unstable library feature 'is_sorted': new API (see issue #53485)
--> $DIR/feature-gate-is_sorted.rs:3:33
|
LL | assert!([1, 2, 2, 9].iter().is_sorted());
| ^^^^^^^^^
|
= help: add #![feature(is_sorted)] to the crate attributes to enable

error[E0658]: use of unstable library feature 'is_sorted': new API (see issue #53485)
--> $DIR/feature-gate-is_sorted.rs:5:39
|
LL | assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
| ^^^^^^^^^^^^^^^^
|
= help: add #![feature(is_sorted)] to the crate attributes to enable

error[E0658]: use of unstable library feature 'is_sorted': new API (see issue #53485)
--> $DIR/feature-gate-is_sorted.rs:9:26
|
LL | assert!([1, 2, 2, 9].is_sorted());
| ^^^^^^^^^
|
= help: add #![feature(is_sorted)] to the crate attributes to enable

error[E0658]: use of unstable library feature 'is_sorted': new API (see issue #53485)
--> $DIR/feature-gate-is_sorted.rs:11:32
|
LL | assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
| ^^^^^^^^^^^^^^^^
|
= help: add #![feature(is_sorted)] to the crate attributes to enable

error: aborting due to 4 previous errors

For more information about this error, try `rustc --explain E0658`.