Commit Graph

175 Commits

Author SHA1 Message Date
bors
ed084b0b83 Auto merge of #69659 - CAD97:step-rework-take-3, r=Amanieu
Rework the std::iter::Step trait

Previous attempts: #43127 #62886 #68807
Tracking issue: #42168

This PR reworks the `Step` trait to be phrased in terms of the *successor* and *predecessor* operations. With this, `Step` hopefully has a consistent identity that can have a path towards stabilization. The proposed trait:

```rust
/// Objects that have a notion of *successor* and *predecessor* operations.
///
/// The *successor* operation moves towards values that compare greater.
/// The *predecessor* operation moves towards values that compare lesser.
///
/// # Safety
///
/// This trait is `unsafe` because its implementation must be correct for
/// the safety of `unsafe trait TrustedLen` implementations, and the results
/// of using this trait can otherwise be trusted by `unsafe` code to be correct
/// and fulful the listed obligations.
pub unsafe trait Step: Clone + PartialOrd + Sized {
    /// Returns the number of *successor* steps required to get from `start` to `end`.
    ///
    /// Returns `None` if the number of steps would overflow `usize`
    /// (or is infinite, or if `end` would never be reached).
    ///
    /// # Invariants
    ///
    /// For any `a`, `b`, and `n`:
    ///
    /// * `steps_between(&a, &b) == Some(n)` if and only if `Step::forward(&a, n) == Some(b)`
    /// * `steps_between(&a, &b) == Some(n)` if and only if `Step::backward(&a, n) == Some(a)`
    /// * `steps_between(&a, &b) == Some(n)` only if `a <= b`
    ///   * Corollary: `steps_between(&a, &b) == Some(0)` if and only if `a == b`
    ///   * Note that `a <= b` does _not_ imply `steps_between(&a, &b) != None`;
    ///     this is the case wheen it would require more than `usize::MAX` steps to get to `b`
    /// * `steps_between(&a, &b) == None` if `a > b`
    fn steps_between(start: &Self, end: &Self) -> Option<usize>;

    /// Returns the value that would be obtained by taking the *successor*
    /// of `self` `count` times.
    ///
    /// If this would overflow the range of values supported by `Self`, returns `None`.
    ///
    /// # Invariants
    ///
    /// For any `a`, `n`, and `m`:
    ///
    /// * `Step::forward_checked(a, n).and_then(|x| Step::forward_checked(x, m)) == Step::forward_checked(a, m).and_then(|x| Step::forward_checked(x, n))`
    ///
    /// For any `a`, `n`, and `m` where `n + m` does not overflow:
    ///
    /// * `Step::forward_checked(a, n).and_then(|x| Step::forward_checked(x, m)) == Step::forward_checked(a, n + m)`
    ///
    /// For any `a` and `n`:
    ///
    /// * `Step::forward_checked(a, n) == (0..n).try_fold(a, |x, _| Step::forward_checked(&x, 1))`
    ///   * Corollary: `Step::forward_checked(&a, 0) == Some(a)`
    fn forward_checked(start: Self, count: usize) -> Option<Self>;

    /// Returns the value that would be obtained by taking the *successor*
    /// of `self` `count` times.
    ///
    /// If this would overflow the range of values supported by `Self`,
    /// this function is allowed to panic, wrap, or saturate.
    /// The suggested behavior is to panic when debug assertions are enabled,
    /// and to wrap or saturate otherwise.
    ///
    /// Unsafe code should not rely on the correctness of behavior after overflow.
    ///
    /// # Invariants
    ///
    /// For any `a`, `n`, and `m`, where no overflow occurs:
    ///
    /// * `Step::forward(Step::forward(a, n), m) == Step::forward(a, n + m)`
    ///
    /// For any `a` and `n`, where no overflow occurs:
    ///
    /// * `Step::forward_checked(a, n) == Some(Step::forward(a, n))`
    /// * `Step::forward(a, n) == (0..n).fold(a, |x, _| Step::forward(x, 1))`
    ///   * Corollary: `Step::forward(a, 0) == a`
    /// * `Step::forward(a, n) >= a`
    /// * `Step::backward(Step::forward(a, n), n) == a`
    fn forward(start: Self, count: usize) -> Self {
        Step::forward_checked(start, count).expect("overflow in `Step::forward`")
    }

    /// Returns the value that would be obtained by taking the *successor*
    /// of `self` `count` times.
    ///
    /// # Safety
    ///
    /// It is undefined behavior for this operation to overflow the
    /// range of values supported by `Self`. If you cannot guarantee that this
    /// will not overflow, use `forward` or `forward_checked` instead.
    ///
    /// # Invariants
    ///
    /// For any `a`:
    ///
    /// * if there exists `b` such that `b > a`, it is safe to call `Step::forward_unchecked(a, 1)`
    /// * if there exists `b`, `n` such that `steps_between(&a, &b) == Some(n)`,
    ///   it is safe to call `Step::forward_unchecked(a, m)` for any `m <= n`.
    ///
    /// For any `a` and `n`, where no overflow occurs:
    ///
    /// * `Step::forward_unchecked(a, n)` is equivalent to `Step::forward(a, n)`
    #[unstable(feature = "unchecked_math", reason = "niche optimization path", issue = "none")]
    unsafe fn forward_unchecked(start: Self, count: usize) -> Self {
        Step::forward(start, count)
    }

    /// Returns the value that would be obtained by taking the *successor*
    /// of `self` `count` times.
    ///
    /// If this would overflow the range of values supported by `Self`, returns `None`.
    ///
    /// # Invariants
    ///
    /// For any `a`, `n`, and `m`:
    ///
    /// * `Step::backward_checked(a, n).and_then(|x| Step::backward_checked(x, m)) == n.checked_add(m).and_then(|x| Step::backward_checked(a, x))`
    /// * `Step::backward_checked(a, n).and_then(|x| Step::backward_checked(x, m)) == try { Step::backward_checked(a, n.checked_add(m)?) }`
    ///
    /// For any `a` and `n`:
    ///
    /// * `Step::backward_checked(a, n) == (0..n).try_fold(a, |x, _| Step::backward_checked(&x, 1))`
    ///   * Corollary: `Step::backward_checked(&a, 0) == Some(a)`
    fn backward_checked(start: Self, count: usize) -> Option<Self>;

    /// Returns the value that would be obtained by taking the *predecessor*
    /// of `self` `count` times.
    ///
    /// If this would overflow the range of values supported by `Self`,
    /// this function is allowed to panic, wrap, or saturate.
    /// The suggested behavior is to panic when debug assertions are enabled,
    /// and to wrap or saturate otherwise.
    ///
    /// Unsafe code should not rely on the correctness of behavior after overflow.
    ///
    /// # Invariants
    ///
    /// For any `a`, `n`, and `m`, where no overflow occurs:
    ///
    /// * `Step::backward(Step::backward(a, n), m) == Step::backward(a, n + m)`
    ///
    /// For any `a` and `n`, where no overflow occurs:
    ///
    /// * `Step::backward_checked(a, n) == Some(Step::backward(a, n))`
    /// * `Step::backward(a, n) == (0..n).fold(a, |x, _| Step::backward(x, 1))`
    ///   * Corollary: `Step::backward(a, 0) == a`
    /// * `Step::backward(a, n) <= a`
    /// * `Step::forward(Step::backward(a, n), n) == a`
    fn backward(start: Self, count: usize) -> Self {
        Step::backward_checked(start, count).expect("overflow in `Step::backward`")
    }

    /// Returns the value that would be obtained by taking the *predecessor*
    /// of `self` `count` times.
    ///
    /// # Safety
    ///
    /// It is undefined behavior for this operation to overflow the
    /// range of values supported by `Self`. If you cannot guarantee that this
    /// will not overflow, use `backward` or `backward_checked` instead.
    ///
    /// # Invariants
    ///
    /// For any `a`:
    ///
    /// * if there exists `b` such that `b < a`, it is safe to call `Step::backward_unchecked(a, 1)`
    /// * if there exists `b`, `n` such that `steps_between(&b, &a) == Some(n)`,
    ///   it is safe to call `Step::backward_unchecked(a, m)` for any `m <= n`.
    ///
    /// For any `a` and `n`, where no overflow occurs:
    ///
    /// * `Step::backward_unchecked(a, n)` is equivalent to `Step::backward(a, n)`
    #[unstable(feature = "unchecked_math", reason = "niche optimization path", issue = "none")]
    unsafe fn backward_unchecked(start: Self, count: usize) -> Self {
        Step::backward(start, count)
    }
}
```

Note that all of these are associated functions and not callable via method syntax; the calling syntax is always `Step::forward(start, n)`. This version of the trait additionally changes the stepping functions to talk their arguments by value.

As opposed to previous attempts which provided a "step by one" method directly, this version of the trait only exposes "step by n". There are a few reasons for this:

- `Range*`, the primary consumer of `Step`, assumes that the "step by n" operation is cheap. If a single step function is provided, it will be a lot more enticing to implement "step by n" as n repeated calls to "step by one". While this is not strictly incorrect, this behavior would be surprising for anyone used to using `Range<{primitive integer}>`.
- With a trivial default impl, this can be easily added backwards-compatibly later.
- The debug-wrapping "step by n" needs to exist for `RangeFrom` to be consistent between "step by n" and "step by one" operation. (Note: the behavior is not changed by this PR, but making the behavior consistent is made tenable by this PR.)

Three "kinds" of step are provided: `_checked`, which returns an `Option` indicating attempted overflow; (unsuffixed), which provides "safe overflow" behavior (is allowed to panic, wrap, or saturate, depending on what is most convenient for a given type); and `_unchecked`, which is a version which assumes overflow does not happen.

Review is appreciated to check that:

- The invariants as described on the `Step` functions are enough to specify the "common sense" consistency for successor/predecessor.
- Implementation of `Step` functions is correct in the face of overflow and the edges of representable integers.
- Added tests of `Step` functions are asserting the correct behavior (and not just the implemented behavior).
2020-05-15 11:24:50 +00:00
Josh Stone
eeb687f20e Don't fuse Chain in its second iterator
Only the "first" iterator is actually set `None` when exhausted,
depending on whether you iterate forward or backward. This restores
behavior similar to the former `ChainState`, where it would transition
from `Both` to `Front`/`Back` and only continue from that side.

However, if you mix directions, then this may still set both sides to
`None`, totally fusing the iterator.
2020-04-21 14:56:59 -07:00
CAD97
2fcfd233f7 Redesign the Step trait 2020-04-08 02:24:16 -04:00
Mazdak Farrokhzad
ae122721dc
Rollup merge of #69645 - DutchGhost:const-forget-tests, r=Dylan-DPC
const forget tests

Adds tests for https://github.com/rust-lang/rust/pull/69617
2020-03-11 10:36:24 +01:00
Tim Diekmann
545ef9d83a Add Layout::dangling() to return a well-aligned NonNull<u8> 2020-03-07 02:40:54 +01:00
Dodo
011fa9107f const forget tests 2020-03-02 21:05:14 +01:00
bors
126ad2b813 Auto merge of #68708 - Mark-Simulacrum:stage0-step, r=pietroalbini
Step stage0 to bootstrap from 1.42

This also includes a commit which fixes the rustfmt downloading logic to redownload when the rustfmt channel changes, and bumps rustfmt to a more recent version.
2020-02-04 14:16:18 +00:00
Yuki Okushi
7e2d7e0bbc Stabilize core::iter::once_with() 2020-02-04 00:47:04 +09:00
Mark Rousskov
31dcdc9e13 Drop cfg(bootstrap) code 2020-01-31 12:31:09 -05:00
Waffle
1aff08010d Add Iterator::map_while method and corresponding MapWhile adapter 2020-01-28 21:30:34 +03:00
bors
82018665a5 Auto merge of #68234 - CAD97:slice-from-raw-parts, r=KodrAus
Stabilize ptr::slice_from_raw_parts[_mut]

Closes #36925, the tracking issue.
Initial impl: #60667

r? @rust-lang/libs

In addition to stabilizing, I've adjusted the example of `ptr::slice_from_raw_parts` to use `slice_from_raw_parts` instead of `slice_from_raw_parts_mut`, which was unnecessary for the example as written.
2020-01-28 05:31:34 +00:00
Ashley Mannix
2c07a621ef stabilize the debug_map_key_value feature 2020-01-28 11:15:22 +10:00
bors
1d5f6d41e1 Auto merge of #68165 - thomcc:lt_ones, r=sfackler
Add leading_ones and trailing_ones methods to the primitive integer types

I was surprised these were missing (given that `leading_zeros` and `trailing_zeros` exist), and they seem trivial and hopefully not controversial.

Note that there's some precedent in that `count_ones` and `count_zeros` are both supported even though only one of these has an intrinsic.

I'm not sure if these need a `rustc_const_unstable` flag (the tests don't seem to mind that it's missing). I just made them const, since there's not really any reason for these to be non-const when the `_zeros` variants are const.

Note: My understanding is trivial stuff like (hopefully) this can land without an RFC, but I'm not fully sure about the process though. Questions like "when does the tracking issue get filed?", are a total mystery to me. So, any guidance is appreciated, and sorry in advance if I should have gone through some more involved process for this.
2020-01-27 08:42:56 +00:00
Mazdak Farrokhzad
3ccb0f9b8f slice_patterns: remove internal uses of gate 2020-01-18 19:33:47 +01:00
CAD97
f76177ce43 Stabilize ptr::slice_from_raw_parts[_mut] 2020-01-14 20:15:39 -05:00
Richard Dodd
9864ec499f Implement finish_non_exhaustive for DebugStruct. 2020-01-14 16:57:59 +00:00
Thom Chiovoloni
2330e325cc Tests for leading_trailing_ones 2020-01-12 14:50:00 -08:00
Mazdak Farrokhzad
50d76d6471
Rollup merge of #68114 - ecstatic-morse:fix-feature-gating, r=Centril
Don't require `allow_internal_unstable` unless `staged_api` is enabled.

#63770 changed `qualify_min_const_fn` to require `allow_internal_unstable` for *all* crates that used an unstable feature, regardless of whether `staged_api` was enabled or the `fn` that used that feature was stably const. In practice, this meant that every crate in the ecosystem that wanted to use nightly features added `#![feature(const_fn)]`, which skips `qualify_min_const_fn` entirely.

After this PR, crates that do not have `#![feature(staged_api)]` will only need to enable the feature they are interested in. For example, `#![feature(const_if_match)]` will be enough to enable `if` and `match` in constants. Crates with `staged_api` (e.g., `libstd`) require `#[allow_internal_unstable]` to be added to a function if it uses nightly features unless that function is also marked `#[rustc_const_unstable]`. This prevents proliferation of `#[allow_internal_unstable]` into functions that are not callable in a `const` context on stable.

r? @oli-obk (author of #63770)
cc @Centril
2020-01-11 12:36:14 +01:00
Dylan MacKenzie
09b5c854de Remove unnecessary const_fn feature gates
This flag opts out of the min-const-fn checks entirely, which is usually
not what we want. The few cases where the flag is still necessary have
been annotated.
2020-01-10 18:51:12 -08:00
Yuki Okushi
2dbcf0841a
Rollup merge of #66045 - mzabaluev:unwrap-infallible, r=dtolnay
Add method Result::into_ok

Implementation of https://github.com/rust-lang/rfcs/pull/2799

Tracking issue #61695
2020-01-11 04:50:45 +09:00
MOZGIII
5446cc99bb Add Iterator::try_find 2020-01-02 00:59:26 +03:00
Mikhail Zabaluev
9a99a2159b libcore: test Result::unwrap_infallible 2019-12-22 08:35:10 +02:00
Dodo
382d370c4f Make ptr::slice_from_raw_parts a const fn available under a feature flag 2019-12-20 21:42:03 +01:00
Lukas Kalbertodt
5334a307d5
Add unit tests for array::IntoIter
Many tests are based on tests by Josh Stone <cuviper@gmail.com>
2019-10-24 15:46:44 +02:00
Tim Vermeulen
6e5ada43bf Add cmp::{min_by, min_by_key, max_by, max_by_key} 2019-09-14 21:52:08 +02:00
Mazdak Farrokhzad
0ac09aef84
Rollup merge of #62205 - timvermeulen:iter_order_by, r=KodrAus
Add Iterator comparison methods that take a comparison function

This PR adds `Iterator::{cmp_by, partial_cmp_by, eq_by, ne_by, lt_by, le_by, gt_by, ge_by}`. We already have `Iterator::{cmp, partial_cmp, ...}` which are less general (but not any simpler) than the ones I'm proposing here.

I'm submitting this PR now because #61505 has been merged, so this change should not have a noticeable effect on the `Iterator` docs page size.

The diff is quite messy, here's what I changed:
- The logic of `cmp` / `partial_cmp` / `eq` is moved to `cmp_by` / `partial_cmp_by` / `eq_by` respectively, changing `x.cmp(&y)` to `cmp(&x, &y)` in the `cmp` method where `cmp` is the given comparison function (and similar for `partial_cmp_by` and `eq_by`).
- `ne_by` / `lt_by` / `le_by` / `gt_by` / `ge_by` are each implemented in terms of one of the three methods above.
- The existing comparison methods are each forwarded to their `_by` counterpart, passing one of `Ord::cmp` / `PartialOrd::partial_cmp` / `PartialEq::eq` as the comparison function.

The corresponding `_by_key` methods aren't included because they're not as fundamental as the `_by` methods and can easily be implemented in terms of them. Is that reasonable, or would adding the `_by_key` methods be desirable for the sake of completeness?

I didn't add any tests – I couldn't think of any that weren't already covered by our existing tests. Let me know if there's a particular test that would be useful to add.
2019-09-08 12:11:55 +02:00
varkor
b73e32c795 Add bool::then and bool::then_with 2019-09-07 15:49:27 +01:00
Tim Vermeulen
58ba1f51ef Add Iterator comparison methods that take a comparison function 2019-09-06 15:30:17 +02:00
Vadim Petrochenkov
434152157f Remove lint annotations in specific crates that are already enforced by rustbuild
Remove some random unnecessary lint `allow`s
2019-07-28 18:46:24 +03:00
Mazdak Farrokhzad
a57c4f6297
Rollup merge of #61884 - crlf0710:stablize_euc, r=dtolnay,Centril
Stablize Euclidean Modulo (feature euclidean_division)

Closes #49048
2019-07-25 23:20:53 +02:00
Josh Stone
265e3a6230 Unit test Iterator::partition_in_place and is_partitioned 2019-07-09 12:39:25 -07:00
Ashley Mannix
e98ea52762 add key and value methods to DebugMap 2019-07-08 09:56:02 +10:00
CrLF0710
72ac8ce9aa Stablize Euclidean Modulo (feature euclidean_division) 2019-07-07 12:16:13 +08:00
Mazdak Farrokhzad
a1ff450a68
Rollup merge of #61398 - kennytm:stabilize-copy-within, r=SimonSapin
Stabilize copy_within

Closes #54236.
2019-06-13 01:49:26 +02:00
Mazdak Farrokhzad
654854fdb5
Rollup merge of #61376 - czipperz:bound-cloned, r=sfackler
Add Bound::cloned()

Suggested by #61356
2019-06-06 22:39:09 +02:00
Chris Gregory
c478efbe6a Enable feature bound_cloned for tests 2019-06-01 22:39:13 -07:00
Mazdak Farrokhzad
7d3a0dd2fb
Rollup merge of #61364 - lzutao:stabilize-reverse_bits, r=Centril
Stabilize reverse_bits feature

FCP done in https://github.com/rust-lang/rust/issues/48763#issuecomment-497349379

Closes #48763

r? @Centril
2019-06-01 06:50:03 +02:00
kennytm
be6fc6aca2
Stabilize copy_within 2019-05-31 20:02:07 +08:00
Lzu Tao
1c26bbf628 Stabilize reverse_bits feature 2019-05-31 04:43:53 +00:00
Lzu Tao
0c35c699d4 Stabilize iter_nth_back feature 2019-05-30 18:00:17 +00:00
Richard Wiedenhöft
07e8d84479 Add const_unchecked_layout test to libcore/tests 2019-05-14 09:41:50 +02:00
Mazdak Farrokhzad
c8ef512480
Rollup merge of #60201 - RalfJung:core-tests, r=alexcrichton
coretest: Downgrade deny to warn

The `deny` causes a build failure in https://github.com/RalfJung/miri-test-libstd. Since we use `-D warnings` for rustc builds, `warn` should be enough to lead to compile errors here, without impeding external builds.
2019-05-13 21:36:51 +02:00
Mazdak Farrokhzad
b71f8d4e1b Stabilize Iterator::copied in 1.36.0. 2019-04-27 16:45:30 +02:00
Christopher Serr
cf9d6672b7 Remove feature gates from std and tests 2019-04-26 12:33:42 +02:00
Tobias Rapp
c7d47c8cf4 Add tests for saturating_abs() and saturating_neg functions 2019-04-25 17:04:17 +02:00
Ralf Jung
4cb6d1c523 deny -> warn 2019-04-23 17:51:10 +02:00
Philipp Hansch
c9ae68812f
Deny rust_2018_idioms in libcore tests 2019-04-20 18:44:29 +02:00
Taiki Endo
360432f1e8 libcore => 2018 2019-04-18 14:47:35 +09:00
Mazdak Farrokhzad
2f37c5a358
Rollup merge of #55448 - Mokosha:SortAtIndex, r=bluss
Add 'partition_at_index/_by/_by_key' for slices.

This is an analog to C++'s std::nth_element (a.k.a. quickselect).

Corresponds to tracking bug #55300.
2019-04-03 04:36:09 +02:00
Jean-Marie Comets
70fa616a23 Stabilize refcell_replace_swap feature, closes #43570 2019-03-31 10:54:14 +02:00