Commit graph

284 commits

Author SHA1 Message Date
Mara
ee796c6523
Rollup merge of #82289 - SkiFire13:fix-issue-82282, r=m-ou-se
Fix underflow in specialized ZipImpl::size_hint

Fixes #82282
2021-03-05 10:57:19 +01:00
Mara
e6a6df5daa
Rollup merge of #80723 - rylev:noop-lint-pass, r=estebank
Implement NOOP_METHOD_CALL lint

Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`).

This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs:
* [ ] No UFCS support
* [ ] The warning message is pretty plain
* [ ] Doesn't work for `ToOwned`

The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type.

Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-05 10:57:14 +01:00
Giacomo Stevanato
8b9ac4d415 Add test for underflow in specialized Zip's size_hint 2021-03-03 21:16:08 +01:00
Ryan Levick
1999a3147f Fix borrow and deref 2021-03-03 11:23:29 +01:00
Ryan Levick
d3b49c2ed2 Only allow new lint when not bootstrapping - since beta doesn't know about the lint 2021-03-03 11:22:50 +01:00
Ryan Levick
ee65416f0d Fix core tests 2021-03-03 11:22:49 +01:00
Ralf Jung
dc685f6815 enable atomic_min/max tests in Miri 2021-03-02 19:58:55 +01:00
Folyd
3eb5bee242 Fix binary_search_by() overflow issue in ZST case 2021-02-27 22:11:44 +08:00
Dylan DPC
4b9c213d6f
Rollup merge of #81167 - usbalbin:const_write, r=oli-obk
Make ptr::write const

~~The code in this PR as of right now is not much more than an experiment.~~

~~This should, if I am not mistaken, in theory compile and pass the tests once the bootstraping compiler is updated. Thus the PR is blocked on that which should happen some time after the February the 9th. Also we might want to wait for #79989 to avoid regressing performance due to using `mem::forget` over `intrinsics::forget`~~.
2021-02-25 14:33:51 +01:00
Albin Hedman
89c761058a
Constify ptr::write and the write[_unaligned] methods on *mut T
Constify intrinsics::forget
2021-02-23 18:00:01 +01:00
Dylan DPC
51511c75b5
Rollup merge of #82391 - RalfJung:miri-atomic-minmax, r=dtolnay
disable atomic_max/min tests in Miri

Disable some tests that currently [fail in Miri](https://travis-ci.com/github/RalfJung/miri-test-libstd/builds/217788631).
2021-02-23 16:10:30 +01:00
Ralf Jung
dd9ab160a1 disable atomic_max/min tests in Miri 2021-02-22 10:06:51 +01:00
Joshua Nelson
3733275854 Update the bootstrap compiler
Note this does not change `core::derive` since it was merged after the
beta bump.
2021-02-20 17:19:30 -05:00
Dylan DPC
f8b61d852c
Rollup merge of #82093 - bjorn3:more_atomic_tests, r=kennytm
Add tests for Atomic*::fetch_{min,max}

This ensures that all atomic operations except for fences are tested. This has been useful to test my work on using atomic instructions for atomic operations in cg_clif instead of a global lock.
2021-02-19 02:49:07 +01:00
LeSeulArtichaut
ec20993c4d Stabilize unsafe_op_in_unsafe_fn lint 2021-02-18 17:12:15 +01:00
bors
d1462d8558 Auto merge of #81172 - SimonSapin:ptr-metadata, r=oli-obk
Implement RFC 2580: Pointer metadata & VTable

RFC: https://github.com/rust-lang/rfcs/pull/2580

~~Before merging this PR:~~

* [x] Wait for the end of the RFC’s [FCP to merge](https://github.com/rust-lang/rfcs/pull/2580#issuecomment-759145278).
* [x] Open a tracking issue: https://github.com/rust-lang/rust/issues/81513
* [x] Update `#[unstable]` attributes in the PR with the tracking issue number

----

This PR extends the language with a new lang item for the `Pointee` trait which is special-cased in trait resolution to implement it for all types. Even in generic contexts, parameters can be assumed to implement it without a corresponding bound.

For this I mostly imitated what the compiler was already doing for the `DiscriminantKind` trait. I’m very unfamiliar with compiler internals, so careful review is appreciated.

This PR also extends the standard library with new unstable APIs in `core::ptr` and `std::ptr`:

```rust
pub trait Pointee {
    /// One of `()`, `usize`, or `DynMetadata<dyn SomeTrait>`
    type Metadata: Copy + Send + Sync + Ord + Hash + Unpin;
}

pub trait Thin = Pointee<Metadata = ()>;

pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {}

pub const fn from_raw_parts<T: ?Sized>(*const (), <T as Pointee>::Metadata) -> *const T {}
pub const fn from_raw_parts_mut<T: ?Sized>(*mut (),<T as Pointee>::Metadata) -> *mut T {}

impl<T: ?Sized> NonNull<T> {
    pub const fn from_raw_parts(NonNull<()>, <T as Pointee>::Metadata) -> NonNull<T> {}

    /// Convenience for `(ptr.cast(), metadata(ptr))`
    pub const fn to_raw_parts(self) -> (NonNull<()>, <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *const T {
    pub const fn to_raw_parts(self) -> (*const (), <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *mut T {
    pub const fn to_raw_parts(self) -> (*mut (), <T as Pointee>::Metadata) {}
}

/// `<dyn SomeTrait as Pointee>::Metadata == DynMetadata<dyn SomeTrait>`
pub struct DynMetadata<Dyn: ?Sized> {
    // Private pointer to vtable
}

impl<Dyn: ?Sized> DynMetadata<Dyn> {
    pub fn size_of(self) -> usize {}
    pub fn align_of(self) -> usize {}
    pub fn layout(self) -> crate::alloc::Layout {}
}

unsafe impl<Dyn: ?Sized> Send for DynMetadata<Dyn> {}
unsafe impl<Dyn: ?Sized> Sync for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Debug for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Unpin for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Copy for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Clone for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Eq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialEq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Ord for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialOrd for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Hash for DynMetadata<Dyn> {}
```

API differences from the RFC, in areas noted as unresolved questions in the RFC:

* Module-level functions instead of associated `from_raw_parts` functions on `*const T` and `*mut T`, following the precedent of `null`, `slice_from_raw_parts`, etc.
* Added `to_raw_parts`
2021-02-18 04:22:16 +00:00
Thom Chiovoloni
2711b011e6 Rename Result::ok_or_err to Result::into_ok_or_err 2021-02-17 08:54:52 -08:00
Thom Chiovoloni
f688bee4ec Add a Result::ok_or_err method to extract a T from Result<T, T> 2021-02-17 08:51:58 -08:00
bjorn3
4fa9e08e3d Enable the tests on Arm Linux too 2021-02-17 10:01:39 +01:00
bjorn3
dfdadad228 Ignore Atomic*::fetch_{min,max} tests on ARM 2021-02-16 09:45:27 +01:00
Simon Sapin
5ade3fe32c Add a ThinBox library as a libcore test for pointer metadata APIs 2021-02-15 14:27:51 +01:00
Simon Sapin
642486c2b2 Fix libcore unit tests in stage 0 2021-02-15 14:27:48 +01:00
Simon Sapin
937d580a25 Add ptr::from_raw_parts, ptr::from_raw_parts_mut, and NonNull::from_raw_parts
The use of module-level functions instead of associated functions
on `<*const T>` or `<*mut T>` follows the precedent of
`ptr::slice_from_raw_parts` and `ptr::slice_from_raw_parts_mut`.
2021-02-15 14:27:31 +01:00
Simon Sapin
9ab83b9338 Add size_of, align_of, and layout methods to DynMetadata 2021-02-15 14:27:17 +01:00
Simon Sapin
b1e15fa8a2 Parameterize DynMetadata over its dyn SomeTrait type 2021-02-15 14:27:16 +01:00
Simon Sapin
696b239f72 Add ptr::Pointee trait (for all types) and ptr::metadata function
RFC: https://github.com/rust-lang/rfcs/pull/2580
2021-02-15 14:27:12 +01:00
bjorn3
d1a541e342 Add tests for Atomic*::fetch_{min,max} 2021-02-14 11:31:33 +01:00
VillSnow
afdc8c7918 stabilize partition_point 2021-02-12 21:57:17 +09:00
Scott McMurray
1b7309edd6 Expand the docs for ops::ControlFlow a bit
Since I was writing some examples for an RFC anyway.
2021-02-06 22:36:05 -08:00
Mara Bos
cc882fc3be
Rollup merge of #80011 - Stupremee:stabilize-peekable-next-if, r=dtolnay
Stabilize `peekable_next_if`

This PR stabilizes the `peekable_next_if` feature

Resolves #72480
2021-02-06 00:14:06 +01:00
Mara Bos
89882388d9 Revert stabilizing integer::BITS. 2021-02-03 22:23:58 +01:00
Ashley Mannix
8940a2652e stabilize int_bits_const 2021-01-31 21:50:47 +10:00
Jonas Schievink
1e99f26894
Rollup merge of #80470 - SimonSapin:array-intoiter-type, r=m-ou-se
Stabilize by-value `[T; N]` iterator `core::array::IntoIter`

Tracking issue: https://github.com/rust-lang/rust/issues/65798

This is unblocked now that `min_const_generics` has been stabilized in https://github.com/rust-lang/rust/pull/79135.

This PR does *not* include the corresponding `IntoIterator` impl, which is https://github.com/rust-lang/rust/pull/65819. Instead, an iterator can be constructed through the `new` method.

`new` would become unnecessary when `IntoIterator` is implemented and might be deprecated then, although it will stay stable.
2021-01-31 01:47:25 +01:00
Folyd
7d078cfb94 Simplify binary search logic to full branch code to let CPU guessing branch more precisely 2021-01-30 14:11:47 +08:00
Folyd
18e44a1be4 Improve slice.binary_search_by()'s best-case performance to O(1) 2021-01-30 14:11:47 +08:00
Yuki Okushi
94e093ab97
Rollup merge of #81306 - SkiFire13:fuse-flatten, r=cuviper
Fuse inner iterator in FlattenCompat and improve related tests

Fixes #81248
2021-01-29 09:17:36 +09:00
Yuki Okushi
b2f6c2aa9b
Rollup merge of #81412 - hyd-dev:array-assume-init-wrong-assertion, r=m-ou-se
Fix assertion in `MaybeUninit::array_assume_init()` for zero-length arrays

That assertion has a false positive ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=63922b8c897b04112adcdf346deb1d0e)):
```rust
#![feature(maybe_uninit_array_assume_init)]

use std::mem::MaybeUninit;

enum Uninhabited {}

fn main() {
    unsafe {
        // thread 'main' panicked at 'attempted to instantiate uninhabited type `Uninhabited`'
        MaybeUninit::<Uninhabited>::array_assume_init([]);
    }
}
```
*Previously reported in https://github.com/rust-lang/rust/pull/80600#discussion_r564496692.*

This PR makes it ignore zero-length arrays.

cc #80908
2021-01-27 04:43:37 +09:00
Yuki Okushi
fe6b3a9792
Rollup merge of #80876 - ojeda:option-result-unwrap_unchecked, r=m-ou-se
Add `unwrap_unchecked()` methods for `Option` and `Result`

In particular:
  - `unwrap_unchecked()` for `Option`.
  - `unwrap_unchecked()` and `unwrap_err_unchecked()` for `Result`.

These complement other `*_unchecked()` methods in `core` etc.

Currently there are a couple of places it may be used inside rustc (`LinkedList`, `BTree`). It is also easy to find other repositories with similar functionality.

Fixes #48278.
2021-01-27 04:43:14 +09:00
hyd-dev
f52066726d
Fix assertion in MaybeUninit::array_assume_init() for zero-length arrays 2021-01-27 00:16:58 +08:00
Giacomo Stevanato
f241c10223 Improve flatten-fuse tests 2021-01-23 21:33:38 +01:00
Daniel Conley
0c78500426 library/core/tests/iter documentation and cleanup 2021-01-22 17:57:08 -05:00
Daniel Conley
bc830a274b library/core/tests/iter rearrange & add back missed doc comments 2021-01-22 17:57:07 -05:00
Daniel Conley
1e3a2def67 library/core/test/iter add newlines between tests 2021-01-22 16:58:21 -05:00
Daniel Conley
3ce97000e1 library/core/test/iter.rs split attempt 2 2021-01-21 19:36:32 -05:00
Mara Bos
9272d53c5a Stop fold at first None when iterator yield 2021-01-19 12:17:58 +00:00
Lzu Tao
20d8478864 Fix intersperse_fold 2021-01-19 00:43:59 +00:00
bors
7d3818152d Auto merge of #81058 - Smittyvb:wasm-num-tests, r=Mark-Simulacrum
Re-enable all num tests on WASM

This was partially done by #47365, but a few tests were missed in that PR.
2021-01-17 11:51:47 +00:00
Mara Bos
d8843d9d82
Rollup merge of #80670 - the8472:fix-zip-trusted-random-access-composition, r=m-ou-se
TrustedRandomAaccess specialization composes incorrectly for nested iter::Zips

I found this while working on improvements for TRA.

After partially consuming a Zip adapter and then wrapping it into another Zip where the adapters use their `TrustedRandomAccess` specializations leads to the outer adapter returning elements which should have already been consumed.

If the optimizer gets tripped up by the addition this might affect performance for chained `zip()` iterators even when the inner one is not partially advanced but it would require more extensive fixes to `TrustedRandomAccess` to communicate those offsets earlier.

Included test fails on nightly, [playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=24fa1edf8a104ff31f5a24830593b01f)
2021-01-16 17:29:51 +00:00
Smitty
e10555c658 Re-enable all num tests on WASM
This was partially done by #47365, but a few tests
were missed in that PR.
2021-01-15 16:58:44 -05:00
Mara Bos
446ed77124
Rollup merge of #80567 - lukaslueg:intersperse_with, r=m-ou-se
Add Iterator::intersperse_with

This is a follow-up to #79479, tracking in #79524, as discussed https://github.com/rust-lang/rust/pull/79479#issuecomment-752671731.

~~Note that I had to manually implement `Clone` and `Debug` because `derive` insists on placing a `Clone`-bound on the struct-definition, which is too narrow. There is a long-standing issue # for this somewhere around here :-)~~

Also, note that I refactored the guts of `Intersperse` into private functions and re-used them in `IntersperseWith`, so I also went light on duplicating all the tests.

If this is suitable to be merged, the tracking issue should be updated, since it only mentions `intersperse`.

Happy New Year!

r? ``@m-ou-se``
2021-01-14 18:00:06 +00:00
Philippe Laflamme
64d695b753
Adds tests to ensure some base op traits exist.
These tests invoke the various op traits using all accepted types they
are implemented for as well as for references to those types.

This fixes #49660 and ensures the following implementations exist:

* `Add`, `Sub`, `Mul`, `Div`, `Rem`
  * `T op T`, `T op &T`, `&T op T` and `&T op &T`
  * for all integer and floating point types
* `AddAssign`, `SubAssign`, `MulAssign`, `DivAssign`, `RemAssign`
  * `&mut T op T` and `&mut T op &T`
  * for all integer and floating point types
* `Neg`
  * `op T` and `op &T`
  * for all signed integer and floating point types
* `Not`
  * `op T` and `op &T`
  * for `bool`
* `BitAnd`, `BitOr`, `BitXor`
  * `T op T`, `T op &T`, `&T op T` and `&T op &T`
  * for all integer types and bool
* `BitAndAssign`, `BitOrAssign`, `BitXorAssign`
  * `&mut T op T` and `&mut T op &T`
  * for all integer types and bool
* `Shl`, `Shr`
  * `L op R`, `L op &R`, `&L op R` and `&L op &R`
  * for all pairs of integer types
* `ShlAssign`, `ShrAssign`
  * `&mut L op R`, `&mut L op &R`
  * for all pairs of integer types
2021-01-13 23:14:00 -05:00
Philippe Laflamme
8ddad18283
Avoid ident concatenation in macro.
AFAIK it isn't currently possible to do this. It is also more in line with other tests in the surrounding modules.
2021-01-13 23:13:55 -05:00
Philippe Laflamme
872dc60ed2
Fix missing mod declaration for Wrapping tests. 2021-01-13 23:13:49 -05:00
Miguel Ojeda
679f6f3473 Add unwrap_unchecked() methods for Option and Result
In particular:
  - `unwrap_unchecked()` for `Option`.
  - `unwrap_unchecked()` and `unwrap_err_unchecked()` for `Result`.

These complement other `*_unchecked()` methods in `core` etc.

Currently there are a couple of places it may be used inside rustc
(`LinkedList`, `BTree`). It is also easy to find other repositories
with similar functionality.

Fixes #48278.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-01-10 15:14:38 +01:00
The8472
af2983a912 TrustedRandomAaccess spec composes incorrectly for nested iter::Zips
After partially consuming a Zip adapter and then wrapping it into
another Zip where the adapters use their TrustedRandomAccess specializations
leads to the outer adapter returning elements which should have already been
consumed.
2021-01-04 01:12:21 +01:00
CoffeeBlend
72a3dee16f
Format code 2021-01-01 22:56:54 +01:00
CoffeeBlend
0ff1e6c697
Add test for MaybeUninit::array_assume_init 2021-01-01 22:12:49 +01:00
Lukas Lueg
7ed824ebd1 Add Iterator::intersperse_with 2020-12-31 23:09:13 +01:00
bors
b33e234155 Auto merge of #79895 - Kerollmops:slice-group-by, r=m-ou-se
The return of the GroupBy and GroupByMut iterators on slice

According to https://github.com/rust-lang/rfcs/pull/2477#issuecomment-742034372, I am opening this PR again, this time I implemented it in safe Rust only, it is therefore much easier to read and is completely safe.

This PR proposes to add two new methods to the slice, the `group_by` and `group_by_mut`. These two methods provide a way to iterate over non-overlapping sub-slices of a base slice that are separated by the predicate given by the user (e.g. `Partial::eq`, `|a, b| a.abs() < b.abs()`).

```rust
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];

let mut iter = slice.group_by(|a, b| a == b);
assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
```

[An RFC](https://github.com/rust-lang/rfcs/pull/2477) was open 2 years ago but wasn't necessary.
2020-12-31 12:00:43 +00:00
bors
9775ffef2a Auto merge of #80530 - m-ou-se:rollup-zit69ko, r=m-ou-se
Rollup of 9 pull requests

Successful merges:

 - #78934 (refactor: removing library/alloc/src/vec/mod.rs ignore-tidy-filelength)
 - #79479 (Add `Iterator::intersperse`)
 - #80128 (Edit rustc_ast::ast::FieldPat docs)
 - #80424 (Don't give an error when creating a file for the first time)
 - #80458 (Some Promotion Refactoring)
 - #80488 (Do not create dangling &T in Weak<T>::drop)
 - #80491 (Miri: make size/align_of_val work for dangling raw ptrs)
 - #80495 (Rename kw::Invalid -> kw::Empty)
 - #80513 (Add regression test for #80062)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2020-12-30 21:25:15 +00:00
Jonas Schievink
7786a6b334 Add Iterator::intersperse 2020-12-30 12:07:19 -08:00
bors
e226704685 Auto merge of #80511 - Mark-Simulacrum:bump-stage0, r=pietroalbini
Bump bootstrap compiler to 1.50 beta

r? `@pietroalbini`
2020-12-30 18:32:31 +00:00
Mark Rousskov
fe031180d0 Bump bootstrap compiler to 1.50 beta 2020-12-30 09:27:19 -05:00
bors
bbcaed03bf Auto merge of #79684 - usbalbin:const_copy, r=oli-obk
Make copy[_nonoverlapping] const

Constifies
* `intrinsics::copy` and `intrinsics::copy_nonoverlapping`
* `ptr::read` and `ptr::read_unaligned`
  * `*const T::read` and `*const T::read_unaligned`
  * `*mut T::read` and `*mut T::read_unaligned`
* `MaybeUninit::assume_init_read`
2020-12-30 12:43:02 +00:00
Simon Sapin
61c49d4042 Stabilize by-value [T; N] iterator core::array::IntoIter
Tracking issue: https://github.com/rust-lang/rust/issues/65798

This is unblocked now that `min_const_generics` has been stabilized
in https://github.com/rust-lang/rust/pull/79135.

This PR does *not* include the corresponding `IntoIterator` impl,
which is https://github.com/rust-lang/rust/pull/65819.
Instead, an iterator can be constructed through the `new` method.

`new` would become unnecessary when `IntoIterator` is implemented
and might be deprecated then, although it will stay stable.
2020-12-29 09:16:46 +01:00
bors
2fab321435 Auto merge of #79134 - ohadravid:nzint-div, r=dtolnay
Add `impl Div<NonZeroU{0}> for u{0}` which cannot panic

Dividing an unsigned int by a `NonZeroUxx` requires a user to write (for example, in [this SO question](https://stackoverflow.com/questions/64855738/how-to-inform-the-optimizer-that-nonzerou32get-will-never-return-zero)):

```
pub fn safe_div(x: u32, y: std::num::NonZeroU32) -> u32 {
    x / y.get()
}
```

which generates a panicking-checked-div [assembly](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:rust,selection:(endColumn:2,endLineNumber:6,positionColumn:2,positionLineNumber:6,selectionStartColumn:2,selectionStartLineNumber:6,startColumn:2,startLineNumber:6),source:%27pub+fn+div(x:+u32,+y:+u32)+-%3E+u32+%7B%0A++++x+/+y%0A%7D%0Apub+fn+safe_div(x:+u32,+y:+std::num::NonZeroU32)+-%3E+u32+%7B%0A++++x+/+y.get()+//+an+unchecked+division+expected%0A%7D%27),l:%275%27,n:%270%27,o:%27Rust+source+%231%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:r1470,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%270%27,libraryCode:%271%27,trim:%271%27),fontScale:14,j:1,lang:rust,libs:!(),options:%27-O%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:%275%27,n:%270%27,o:%27rustc+1.47.0+(Editor+%231,+Compiler+%231)+Rust%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4).
Avoiding the `panic` currently requires `unsafe` code.

This PR adds an `impl Div<NonZeroU{0}> for u{0}` (and `impl Rem<NonZeroU{0}> for u{0}`) which calls the `unchecked_div` (and `unchecked_rem`) intrinsic without any additional checks,
making the following code compile:

```
pub fn safe_div(x: u32, y: std::num::NonZeroU32) -> u32 {
    x / y
}

pub fn safe_rem(x: u32, y: std::num::NonZeroU32) -> u32 {
    x % y
}
```

The doc is set to match the regular div impl [docs](https://doc.rust-lang.org/beta/src/core/ops/arith.rs.html#460).

I've marked these as stable because (as I understand it) trait impls are automatically stable. I'm happy to change it to unstable if needed.

Following `@dtolnay` template from a similar issue:
this adds the following **stable** impls, which rely on dividing unsigned integers by nonzero integers being well defined and previously would have involved unsafe code to encode that knowledge:
```
impl Div<NonZeroU8> for u8 {
    type Output = u8;
}

impl Rem<NonZeroU8> for u8 {
    type Output = u8;
}
```
and equivalent for u16, u32, u64, u128, usize, but **not** for i8, i16, i32, i64, i128, isize (since -1/MIN is undefined).

r? `@dtolnay`
2020-12-27 13:11:06 +00:00
Albin Hedman
5e27765ddf Add tests 2020-12-26 03:45:51 +01:00
Linus Färnstrand
828d4ace4d Migrate standard library away from compare_and_swap 2020-12-22 12:19:46 +01:00
DrMeepster
28e0d2f234
Fix unused import error on wasm 2020-12-18 14:53:55 -08:00
DrMeepster
01f36c51c2 fix memory leak in test 2020-12-17 09:18:06 -08:00
Ohad Ravid
1e9e30dc40 Added impl Rem<NonZeroU{0}> for u{0} which cannot panic 2020-12-17 18:42:19 +02:00
Ohad Ravid
3f671bc944 Added impl Div<NonZeroU{0}> for u{0} which cannot panic 2020-12-17 18:41:47 +02:00
DrMeepster
4652a13f44 write_slice(_cloned) 2020-12-15 12:21:33 -08:00
Justus K
58307bc273
stabilize peekable_next_if 2020-12-13 14:59:50 +01:00
Clément Renault
a891f6edfe
Introduce the GroupBy and GroupByMut Iterators 2020-12-10 10:16:29 +01:00
Albin Hedman
d0a1e40eae Remove unused feature gate 2020-12-06 22:29:13 +01:00
Albin Hedman
4255a5afd5 Moved failing test to src/test/ui/
Still have not figured out how to make it work
2020-12-06 19:01:03 +01:00
Albin Hedman
94762417e8 Still unable to get the tests working 2020-12-05 19:41:02 +01:00
Albin Hedman
7bd754cf8c Fix tests (hopefully) 2020-12-05 18:39:10 +01:00
Albin Hedman
f311db100b Added tests for assume_init 2020-12-02 19:14:10 +01:00
Christiaan Dirkx
be554c4101 Make ui test that are run-pass and do not test the compiler itself library tests 2020-11-30 02:47:32 +01:00
bstrie
90a2e5e3fe Update tests to remove old numeric constants
Part of #68490.

Care has been taken to leave the old consts where appropriate, for testing backcompat regressions, module shadowing, etc. The intrinsics docs were accidentally referring to some methods on f64 as std::f64, which I changed due to being contrary with how we normally disambiguate the shadow module from the primitive. In one other place I changed std::u8 to std::ops since it was just testing path handling in macros.

For places which have legitimate uses of the old consts, deprecated attributes have been optimistically inserted. Although currently unnecessary, they exist to emphasize to any future deprecation effort the necessity of these specific symbols and prevent them from being accidentally removed.
2020-11-29 00:55:55 -05:00
Aaron Hill
6f91c32da6
Fix new 'unnecessary trailing semicolon' warnings 2020-11-26 17:08:36 -05:00
Lukas Lueg
3b015622be Add Peekable::peek_mut 2020-11-23 23:52:19 +01:00
bors
74285eb3a8 Auto merge of #78088 - fusion-engineering-forks:panic-fmt-lint, r=estebank
Add lint for panic!("{}")

This adds a lint that warns about `panic!("{}")`.

`panic!(msg)` invocations with a single argument use their argument as panic payload literally, without using it as a format string. The same holds for `assert!(expr, msg)`.

This lints checks if `msg` is a string literal (after expansion), and warns in case it contained braces. It suggests to insert `"{}", ` to use the message literally, or to add arguments to use it as a format string.

![image](https://user-images.githubusercontent.com/783247/96643867-79eb1080-1328-11eb-8d4e-a5586837c70a.png)

This lint is also a good starting point for adding warnings about `panic!(not_a_string)` later, once [`panic_any()`](https://github.com/rust-lang/rust/pull/74622) becomes a stable alternative.
2020-11-20 03:40:20 +00:00
Dylan DPC
c2a277c11d
Rollup merge of #79123 - CDirkx:128-bits, r=Mark-Simulacrum
Add u128 and i128 integer tests

Add the missing integer tests for u128 and i128 for completeness with the other integer types.
2020-11-19 23:58:35 +01:00
Mara Bos
126d88bd12
Rollup merge of #79114 - andjo403:nonzero_leading_trailing_zeros, r=m-ou-se
add trailing_zeros and leading_zeros to non zero types

as a way towards being able to use the optimized intrinsics ctlz_nonzero and cttz_nonzero from stable.

have not crated any tracking issue if this is not a solution that is wanted
2020-11-18 15:46:31 +01:00
Andreas Jonson
9bbc4c16d3 add trailing_zeros and leading_zeros to non zero types 2020-11-17 19:54:29 +01:00
Mara Bos
de0aa6169f
Rollup merge of #76339 - CDirkx:structural-match-range, r=Mark-Simulacrum
Test structural matching for all range types

As of #70166 all range types (`core::ops::Range` etc.) can be structurally matched upon, and by extension used in const generics. In reference to the fact that this is a publicly observable property of these types, and thus falls under the Rust stability guarantees of the standard library, a regression test was added in #70283.

This regression test was implemented by me by testing for the ability to use the range types within const generics, but that is not the actual property the std guarantees now (const generics is still unstable). This PR addresses that situation by adding extra tests for the range types that directly test whether they can be structurally matched upon.

Note: also adds the otherwise unrelated test `test_range_to_inclusive` for completeness with the other range unit tests
2020-11-16 17:26:13 +01:00
Christiaan Dirkx
6554086526 Add u128 and i128 integer tests 2020-11-14 20:27:08 +01:00
Jonas Schievink
62f0a78056
Rollup merge of #78216 - workingjubilee:duration-zero, r=m-ou-se
Duration::zero() -> Duration::ZERO

In review for #72790, whether or not a constant or a function should be favored for `#![feature(duration_zero)]` was seen as an open question. In https://github.com/rust-lang/rust/issues/73544#issuecomment-691701670 an invitation was opened to either stabilize the methods or propose a switch to the constant value, supplemented with reasoning. Followup comments suggested community preference leans towards the const ZERO, which would be reason enough.

ZERO also "makes sense" beside existing associated consts for Duration. It is ever so slightly awkward to have a series of constants specifying 1 of various units but leave 0 as a method, especially when they are side-by-side in code. It seems unintuitive for the one non-dynamic value (that isn't from Default) to be not-a-const, which could hurt discoverability of the associated constants overall. Elsewhere in `std`, methods for obtaining a constant value were even deprecated, as seen with [std::u32::min_value](https://doc.rust-lang.org/std/primitive.u32.html#method.min_value).

Most importantly, ZERO costs less to use. A match supports a const pattern, but const fn can only be used if evaluated through a const context such as an inline `const { const_fn() }` or a `const NAME: T = const_fn()` declaration elsewhere. Likewise, while https://github.com/rust-lang/rust/issues/73544#issuecomment-691949373 notes `Duration::zero()` can optimize to a constant value, "can" is not "will". Only const contexts have a strong promise of such. Even without that in mind, the comment in question still leans in favor of the constant for simplicity. As it costs less for a developer to use, may cost less to optimize, and seems to have more of a community consensus for it, the associated const seems best.

r? ```@LukasKalbertodt```
2020-11-11 20:58:52 +01:00
Dylan DPC
d69ee57f97
Rollup merge of #77640 - ethanboxx:int_error_matching_attempt_2, r=KodrAus
Refactor IntErrorKind to avoid "underflow" terminology

This PR is a continuation of #76455

# Changes

- `Overflow` renamed to `PosOverflow` and `Underflow` renamed to `NegOverflow` after discussion in #76455
- Changed some of the parsing code to return `InvalidDigit` rather than `Empty` for strings "+" and "-". https://users.rust-lang.org/t/misleading-error-in-str-parse-for-int-types/49178
- Carry the problem `char` with the `InvalidDigit` variant.
- Necessary changes were made to the compiler as it depends on `int_error_matching`.
- Redid tests to match on specific errors.

r? ```@KodrAus```
2020-11-09 01:13:25 +01:00
Mara Bos
2967e58be3
Rollup merge of #78728 - a1phyr:const_cell_into_inner, r=dtolnay
Constantify `UnsafeCell::into_inner` and related

Tracking issue: #78729

This PR constantifies:
- `UnsafeCell::into_inner`
- `Cell::into_inner`
- `RefCell::into_inner`
- `Atomic*::into_inner`

r? `````@dtolnay`````
2020-11-08 13:36:14 +01:00
Mara Bos
bdeace9f4e
Rollup merge of #76227 - CDirkx:const-poll, r=KodrAus
Stabilize `Poll::is_ready` and `is_pending` as const

Insta-stabilize the methods `is_ready` and `is_pending` of `std::task::Poll` as const, in the same way as [PR#76198](https://github.com/rust-lang/rust/pull/76198).

Possible because of the recent stabilization of const control flow.

Part of #76225.
2020-11-08 13:35:58 +01:00
Christiaan Dirkx
6728240f36 Test structural matching for all range types
Adds structural match tests for all range types.

Note: also adds the otherwise unrelated test `test_range_to_inclusive` for completeness
2020-11-07 01:31:44 +01:00
Mara Bos
86e6afafe1
Rollup merge of #78738 - sasurau4:test/move-range-test-to-library-core, r=jyn514
Move range in ui test to ops test in library/core

Helps with #76268

r? ````@matklad````
2020-11-05 10:29:56 +01:00
chansuke
f9b139f9c4 Add mod nan for test 2020-11-05 12:57:18 +09:00
chansuke
97d5a1be3f Fix format 2020-11-05 08:40:04 +09:00
chansuke
5855fb7b79 Move f64::NAN ui tests into library 2020-11-05 08:32:07 +09:00
Daiki Ihara
232b9ba129 Move range in ui test to ops test in library/core 2020-11-05 00:00:44 +09:00
Benoît du Garreau
9a12d727df Constantify UnsafeCell::into_inner and related
Also includes:
- Cell::into_inner
- RefCell::into_inner
- Atomic*::into_inner
2020-11-04 11:41:57 +01:00
Jubilee Young
af4d1786e7 Fixup tests: Duration::MIN -> ::ZERO 2020-10-27 13:57:51 -07:00
Ethan Brierley
ad2d93da1f Apply suggested changes 2020-10-26 18:14:12 +00:00
Jubilee Young
ef027a1eed Duration::zero() -> Duration::ZERO
Duration::ZERO composes better with match and various other things,
at the cost of an occasional parens, and results in less work for the
optimizer, so let's use that instead.
2020-10-21 20:44:03 -07:00
Jubilee Young
d72d5f48c2 Dogfood Duration API in std::time tests
This expands time's test suite to use more and in more places the
range of methods and constants added to Duration in recent
proposals for the sake of testing more API surface area and
improving legibility.
2020-10-21 20:03:56 -07:00
Josh Stone
9202fbdbdb Check for exhaustion in SliceIndex for RangeInclusive 2020-10-20 17:18:08 -07:00
Mara Bos
9e3b949b8c Fix braces in panic message in test. 2020-10-19 10:07:30 +02:00
Yuki Okushi
70f8e1a56f
Rollup merge of #77892 - est31:remove_redundant_absolute_paths, r=lcnr
Replace absolute paths with relative ones

Modern compilers allow reaching external crates
like std or core via relative paths in modules
outside of lib.rs and main.rs.
2020-10-14 06:02:36 +09:00
est31
a0fc455d30 Replace absolute paths with relative ones
Modern compilers allow reaching external crates
like std or core via relative paths in modules
outside of lib.rs and main.rs.
2020-10-13 14:16:45 +02:00
James Gill
01ac5a97c9 Stabilize slice_select_nth_unstable
This stabilizes the functionality in slice_partition_at_index,
but under the names `select_nth_unstable*`.  The functions
`partition_at_index*` are left as deprecated, to be removed in
a later release.

Closes #55300
2020-10-12 00:07:41 -04:00
Ethan Brierley
f233abb909 Add comment to helper function 2020-10-07 08:02:36 +01:00
Ethan Brierley
1e7e2e40e4 remove OnlySign in favour of InvalidDigit 2020-10-06 22:42:33 +01:00
Ethan Brierley
83d294f06a Bring char along with InvalidDigit 2020-10-06 19:05:25 +01:00
Ethan Brierley
c027844795 Fill in things needed to stabilize int_error_matching 2020-10-06 14:06:25 +01:00
bors
5849a7eca9 Auto merge of #77594 - timvermeulen:chain_advance_by, r=scottmcm
Implement advance_by, advance_back_by for iter::Chain

Part of #77404.

This PR does two things:
- implement `Chain::advance[_back]_by` in terms of `advance[_back]_by` on `self.a` and `advance[_back]_by` on `self.b`
- change `Chain::nth[_back]` to use `advance[_back]_by` on `self.a` and `nth[_back]` on `self.b`

This ensures that `Chain::nth` can take advantage of an efficient `nth` implementation on the second iterator, in case it doesn't implement `advance_by`.

cc `@scottmcm` in case you want to review this
2020-10-06 10:17:48 +00:00
Tim Vermeulen
1d27a508d1 Test with non-fused iterators 2020-10-06 00:48:34 +02:00
Tim Vermeulen
bcacfe1dbf Add tests 2020-10-05 22:55:48 +02:00
Jonas Schievink
389f7cf7d6
Rollup merge of #76745 - workingjubilee:move-wrapping-tests, r=matklad
Move Wrapping<T> ui tests into library

Part of #76268
r? @matklad
2020-10-03 00:31:08 +02:00
Jubilee Young
4e973966b9 Remove unnecessary mod-cfg 2020-10-02 11:40:57 -07:00
Dylan DPC
8bd4ed9f95
Rollup merge of #76909 - timvermeulen:advance_by, r=Amanieu
Add Iterator::advance_by and DoubleEndedIterator::advance_back_by

This PR adds the iterator method

```rust
fn advance_by(&mut self, n: usize) -> Result<(), usize>
```

that advances the iterator by `n` elements, returning `Ok(())` if this succeeds or `Err(len)` if the length of the iterator was less than `n`.

Currently `Iterator::nth` is the method to override for efficiently advancing an iterator by multiple elements at once. `advance_by` is superior for this purpose because
- it's simpler to implement: instead of advancing the iterator and producing the next element you only need to advance the iterator
- it composes better: iterators like `Chain` and `FlatMap` can implement `advance_by` in terms of `advance_by` on their inner iterators, but they cannot implement `nth` in terms of `nth` on their inner iterators (see #60395)
- the default implementation of `nth` can trivially be implemented in terms of `advance_by` and `next`, which this PR also does

This PR also adds `DoubleEndedIterator::advance_back_by` for all the same reasons.

I'll make a tracking issue if it's decided this is worth merging. Also let me know if anything can be improved, this went through several iterations so there might very well still be room for improvement (especially in the doc comments). I've written overrides of these methods for most iterators that already override `nth`/`nth_back`, but those still need tests so I'll add them in a later PR.

cc @cuviper @scottmcm @Amanieu
2020-10-01 02:13:29 +02:00
Ralf Jung
734c57d45c
Rollup merge of #76454 - poliorcetics:ui-to-unit-test-1, r=matklad
UI to unit test for those using Cell/RefCell/UnsafeCell

Helps with #76268.

I'm working on all files using `Cell` and moving them to unit tests when possible.

r? @matklad
2020-09-28 18:39:39 +02:00
Jonas Schievink
5926c43743
Rollup merge of #77167 - fusion-engineering-forks:fix-fixme-min-max-sign-test, r=nagisa
Fix FIXME in core::num test: Check sign of zero in min/max tests.

r? nagisa

@rustbot modify labels: +C-cleanup
2020-09-27 01:53:20 +02:00
Alexis Bourget
a61b9638bb review: fix nits and move panic safety tests to the correct place 2020-09-25 23:10:24 +02:00
Jonas Schievink
1b8c939a8d
Rollup merge of #76973 - lzutao:unstably-const-assume, r=oli-obk
Unstably allow assume intrinsic in const contexts

Not sure much about this usage because there are concerns
about [blocking  optimization][1] and [slowing down LLVM][2] when using `assme` intrinsic
in inline functions.
But since Oli suggested in https://github.com/rust-lang/rust/issues/76960#issuecomment-695772221,
here we are.

[1]: https://github.com/rust-lang/rust/pull/54995#issuecomment-429302709
[2]: https://github.com/rust-lang/rust/issues/49572#issuecomment-589615423
2020-09-25 19:42:29 +02:00
Mara Bos
74952b9f21 Fix FIXME in core::num test: Check sign of zero in min/max tests. 2020-09-24 22:29:32 +02:00
Lzu Tao
382d7243a7 move test to intergrated test in library/core 2020-09-24 14:46:57 +00:00
Bastian Kauschke
179f63dafc add array from_ref 2020-09-22 21:35:43 +02:00
ecstatic-morse
537ede465f
Rollup merge of #76655 - CDirkx:const-pin, r=ecstatic-morse
Make some methods of `Pin` unstable const

Make the following methods unstable const under the `const_pin` feature:
- `new`
- `new_unchecked`
- `into_inner`
- `into_inner_unchecked`
- `get_ref`
- `into_ref`
- `get_mut`
- `get_unchecked_mut`

Of these, `into_inner` and `into_inner_unchecked` require the unstable `const_precise_live_drops`.

Also adds tests for these methods in a const context.

Tracking issue: #76654

r? @ecstatic-morse
2020-09-21 20:40:49 -07:00
Alexis Bourget
5be843fc54 Move format-ref-cell test 2020-09-21 21:50:27 +02:00
Alexis Bourget
275eed7eb1 Move vec-slice-drop test 2020-09-21 21:50:27 +02:00
Alexis Bourget
8904921c1d Move array cycle test 2020-09-21 21:50:26 +02:00
Alexis Bourget
ac39debeba Move panic safety traits tests 2020-09-21 21:50:26 +02:00
Alexis Bourget
85b2d9bf6f fmt 2020-09-21 21:50:26 +02:00
Alexis Bourget
fc152cd67e move 'test zip ...' tests 2020-09-21 21:50:26 +02:00
Alexis Bourget
af44a2a857 move 'cell does not clone' test 2020-09-21 21:50:25 +02:00
Alexis Bourget
f69c5aa428 Move more tests using Cell to unit tests 2020-09-21 21:50:19 +02:00
Alexis Bourget
8aae1eee94 Move cell exterior test into library unit tests 2020-09-21 21:28:33 +02:00
Christiaan Dirkx
4f859fbcfc Move const tests for Option to library\core
Part of #76268
2020-09-20 22:42:14 +02:00
Tim Vermeulen
ecacc7534b Add advance_by and advance_back_by 2020-09-20 16:14:43 +02:00
bors
b873fa6d42 Auto merge of #76136 - CDirkx:const-result, r=dtolnay
Stabilize some Result methods as const

Stabilize the following methods of Result as const:
 - `is_ok`
 - `is_err`
 - `as_ref`

A test is also included, analogous to the test for `const_option`.

These methods are currently const under the unstable feature `const_result` (tracking issue: #67520).
I believe these methods to be eligible for stabilization because of the stabilization of #49146 (Allow if and match in constants) and the trivial implementations, see also: [PR#75463](https://github.com/rust-lang/rust/pull/75463) and [PR#76135](https://github.com/rust-lang/rust/pull/76135).

Note: these methods are the only methods currently under the `const_result` feature, thus this PR results in the removal of the feature.

Related: #76225
2020-09-20 13:07:11 +00:00
Mara Bos
1e2dba1e7c Use T::BITS instead of size_of::<T> * 8. 2020-09-19 06:54:42 +02:00
Christiaan Dirkx
e3c6e46168 Make some methods of Pin<&mut T> unstable const
Make the following methods unstable const under the `const_pin` feature:
- `into_ref`
- `get_mut`
- `get_unchecked_mut`
2020-09-18 19:23:50 +02:00
Tyler Mandry
23a677787e
Rollup merge of #75026 - JulianKnodt:array_windows, r=Amanieu
Add array_windows fn

This mimicks the functionality added by array_chunks, and implements a const-generic form of
`windows`. It makes egregious use of `unsafe`, but by necessity because the array must be
re-interpreted as a slice of arrays, and unlike array_chunks this cannot be done by casting the
original array once, since each time the index is advanced it needs to move one element, not
`N`.

I'm planning on adding more tests, but this should be good enough as a premise for the functionality.
Notably: should there be more functions overwritten for the iterator implementation/in general?

~~I've marked the issue as #74985 as there is no corresponding exact issue for `array_windows`, but it's based of off `array_chunks`.~~

Edit: See Issue #75027 created by @lcnr for tracking issue

~~Do not merge until I add more tests, please.~~

r? @lcnr
2020-09-16 12:24:03 -07:00
kadmin
f240abc1dc Add array window fn
Updated issue to #75027

Update to rm oob access

And hopefully fix docs as well

Fixed naming conflict in test

Fix test which used 1-indexing

Nth starts from 0, woops

Fix a bunch of off by 1 errors

See https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=757b311987e3fae1ca47122969acda5a

Add even more off by 1 errors

And also write `next` and `next_back` in terms of `nth` and `nth_back`.

Run fmt

Fix forgetting to change fn name in test

add nth_back test & document unsafe

Remove as_ref().unwrap()
Documented occurrences of unsafe, noting what invariants are maintained
2020-09-16 14:52:20 +00:00
Ralf Jung
c1a74a3c28
Rollup merge of #76366 - ayushmishra2005:arith_tests_in_library, r=jyn514
Add Arith Tests in Library

Added Arith Tests library as a part of #76268

r? @matklad
2020-09-16 08:24:52 +02:00
Ralf Jung
22dd07d555
Rollup merge of #76335 - CDirkx:const-duration, r=ecstatic-morse
Make all methods of `Duration` unstably const

Make the following methods of `Duration` unstable const under `duration_const_2`:
 - `from_secs_f64`
 - `from_secs_f32`
 - `mul_f64`
 - `mul_f32`
 - `div_f64`
 - `div_f32`

This results in all methods of `Duration` being (unstable) const.

Moved the tests to `library` as part of #76268.

Possible because of #72449, which made the relevant `f32` and `f64` methods const.

Tracking issue: #72440

r? @ecstatic-morse
2020-09-16 08:24:50 +02:00
Dylan DPC
69ac07608e
Rollup merge of #76198 - CDirkx:const-ordering, r=dtolnay
Make some Ordering methods const

Resubmission of [PR#75463](https://github.com/rust-lang/rust/pull/75463) as per [PR#76172](https://github.com/rust-lang/rust/pull/76172).

Constify the following methods of `core::cmp::Ordering`:
 - `reverse`
 - `then`

Insta-stabilizes these methods as const under the `const_ordering` feature, as their implementation is a trivial match and the recent stabilization of #49146 (Allow `if` and `match` in constants).
Note: the `const_ordering` feature has never actually been used as these methods have not been `#[rustc_const_unstable]`.

Tracking issue:  #76113
2020-09-16 01:30:42 +02:00
Jubilee Young
797cb9526a Fix to libstd test 2020-09-15 08:47:20 -07:00
Jubilee Young
247b73939a Move Wrapping<T> ui tests into library 2020-09-15 07:15:59 -07:00
Christiaan Dirkx
8f27e3cb1b Make some methods of Pin unstable const
Make the following methods unstable const under the `const_pin` feature:
- `new`
- `new_unchecked`
- `into_inner`
- `into_inner_unchecked`
- `get_ref`
- `into_ref`

Also adds tests for these methods in a const context.

Tracking issue: #76654
2020-09-13 01:55:34 +02:00