Commit Graph

810 Commits

Author SHA1 Message Date
The 8472
69db91b8b2 Change advance(_back)_by to return usize instead of Result<(), usize>
A successful advance is now signalled by returning `0` and other values now represent the remaining number
of steps that couldn't be advanced as opposed to the amount of steps that have been advanced during a partial advance_by.

This simplifies adapters a bit, replacing some `match`/`if` with arithmetic. Whether this is beneficial overall depends
on whether `advance_by` is mostly used as a building-block for other iterator methods and adapters or whether
we also see uses by users where `Result` might be more useful.
2023-03-27 14:11:49 +02:00
onestacked
8a9d6bf4fd Mark DoubleEndedIterator as #[const_trait] using rustc_do_not_const_check, implement const Iterator and DoubleEndedIterator for Range. 2023-03-18 09:17:37 +01:00
Mara Bos
96d252160e Update format_args!() test to account for inlining. 2023-03-16 11:21:50 +01:00
est31
999405059c Match unmatched backticks in library/ 2023-03-03 03:03:29 +01:00
Ralf Jung
229aef1f7d add missing feature in core/tests 2023-02-28 10:07:57 +01:00
Linus Färnstrand
6cb34492a6 Move IpAddr and SocketAddr to core 2023-02-26 13:50:08 +01:00
soc
3aa9f76a3a
Remove #![feature(option_result_contains)] from library/core/tests/lib.rs 2023-02-15 19:30:02 +00:00
bors
2d91939bb7 Auto merge of #107634 - scottmcm:array-drain, r=thomcc
Improve the `array::map` codegen

The `map` method on arrays [is documented as sometimes performing poorly](https://doc.rust-lang.org/std/primitive.array.html#note-on-performance-and-stack-usage), and after [a question on URLO](https://users.rust-lang.org/t/try-trait-residual-o-trait-and-try-collect-into-array/88510?u=scottmcm) prompted me to take another look at the core [`try_collect_into_array`](7c46fb2111/library/core/src/array/mod.rs (L865-L912)) function, I had some ideas that ended up working better than I'd expected.

There's three main ideas in here, split over three commits:
1. Don't use `array::IntoIter` when we can avoid it, since that seems to not get SRoA'd, meaning that every step writes things like loop counters into the stack unnecessarily
2. Don't return arrays in `Result`s unnecessarily, as that doesn't seem to optimize away even with `unwrap_unchecked` (perhaps because it needs to get moved into a new LLVM type to account for the discriminant)
3. Don't distract LLVM with all the `Option` dances when we know for sure we have enough items (like in `map` and `zip`).  This one's a larger commit as to do it I ended up adding a new `pub(crate)` trait, but hopefully those changes are still straight-forward.

(No libs-api changes; everything should be completely implementation-detail-internal.)

It's still not completely fixed -- I think it needs pcwalton's `memcpy` optimizations still (#103830) to get further -- but this seems to go much better than before.  And the remaining `memcpy`s are just `transmute`-equivalent (`[T; N] -> ManuallyDrop<[T; N]>` and `[MaybeUninit<T>; N] -> [T; N]`), so hopefully those will be easier to remove with LLVM16 than the previous subobject copies 🤞

r? `@thomcc`

As a simple example, this test
```rust
pub fn long_integer_map(x: [u32; 64]) -> [u32; 64] {
    x.map(|x| 13 * x + 7)
}
```
On nightly <https://rust.godbolt.org/z/xK7548TGj> takes `sub rsp, 808`
```llvm
start:
  %array.i.i.i.i = alloca [64 x i32], align 4
  %_3.sroa.5.i.i.i = alloca [65 x i32], align 4
  %_5.i = alloca %"core::iter::adapters::map::Map<core::array::iter::IntoIter<u32, 64>, [closure@/app/example.rs:2:11: 2:14]>", align 8
```
(and yes, that's a 6**5**-element array `alloca` despite 6**4**-element input and output)

But with this PR it's only `sub rsp, 520`
```llvm
start:
  %array.i.i.i.i.i.i = alloca [64 x i32], align 4
  %array1.i.i.i = alloca %"core::mem::manually_drop::ManuallyDrop<[u32; 64]>", align 4
```

Similarly, the loop it emits on nightly is scalar-only and horrifying
```nasm
.LBB0_1:
        mov     esi, 64
        mov     edi, 0
        cmp     rdx, 64
        je      .LBB0_3
        lea     rsi, [rdx + 1]
        mov     qword ptr [rsp + 784], rsi
        mov     r8d, dword ptr [rsp + 4*rdx + 528]
        mov     edi, 1
        lea     edx, [r8 + 2*r8]
        lea     r8d, [r8 + 4*rdx]
        add     r8d, 7
.LBB0_3:
        test    edi, edi
        je      .LBB0_11
        mov     dword ptr [rsp + 4*rcx + 272], r8d
        cmp     rsi, 64
        jne     .LBB0_6
        xor     r8d, r8d
        mov     edx, 64
        test    r8d, r8d
        jne     .LBB0_8
        jmp     .LBB0_11
.LBB0_6:
        lea     rdx, [rsi + 1]
        mov     qword ptr [rsp + 784], rdx
        mov     edi, dword ptr [rsp + 4*rsi + 528]
        mov     r8d, 1
        lea     esi, [rdi + 2*rdi]
        lea     edi, [rdi + 4*rsi]
        add     edi, 7
        test    r8d, r8d
        je      .LBB0_11
.LBB0_8:
        mov     dword ptr [rsp + 4*rcx + 276], edi
        add     rcx, 2
        cmp     rcx, 64
        jne     .LBB0_1
```

whereas with this PR it's unrolled and vectorized
```nasm
	vpmulld	ymm1, ymm0, ymmword ptr [rsp + 64]
	vpaddd	ymm1, ymm1, ymm2
	vmovdqu	ymmword ptr [rsp + 328], ymm1
	vpmulld	ymm1, ymm0, ymmword ptr [rsp + 96]
	vpaddd	ymm1, ymm1, ymm2
	vmovdqu	ymmword ptr [rsp + 360], ymm1
```
(though sadly still stack-to-stack)
2023-02-13 10:18:48 +00:00
Matthias Krüger
454ae9fb8b
Rollup merge of #107954 - RalfJung:tree-borrows-fix, r=m-ou-se
avoid mixing accesses of ptrs derived from a mutable ref and parent ptrs

``@Vanille-N`` is working on a successor for Stacked Borrows. It will mostly accept strictly more code than Stacked Borrows did, with one exception: the following pattern no longer works.
```rust
let mut root = 6u8;
let mref = &mut root;
let ptr = mref as *mut u8;
*ptr = 0; // Write
assert_eq!(root, 0); // Parent Read
*ptr = 0; // Attempted Write
```
This worked in Stacked Borrows kind of by accident: when doing the "parent read", under SB we Disable `mref`, but the raw ptrs derived from it remain usable. The fact that we can still use the "children" of a reference that is no longer usable is quite nasty and leads to some undesirable effects (in particular it is the major blocker for resolving https://github.com/rust-lang/unsafe-code-guidelines/issues/257). So in Tree Borrows we no longer do that; instead, reading from `root` makes `mref` and all its children read-only.

Due to other improvements in Tree Borrows, the entire Miri test suite still passes with this new behavior, and even the entire libcore and liballoc test suite, except for these 2 cases this PR fixes. Both of these involve code where the programmer wrote `&mut` but then used pointers derived from that reference in ways that alias with the parent pointer, which arguably is violating uniqueness. They are fixed by properly using raw pointers throughout.
2023-02-12 22:29:49 +01:00
Ralf Jung
c3a2e7a809 avoid mixing accesses of ptrs derived from a mutable ref and parent ptrs 2023-02-12 15:16:27 +01:00
bors
adb4bfd25d Auto merge of #105671 - lukas-code:depreciate-char, r=scottmcm
Use associated items of `char` instead of freestanding items in `core::char`

The associated functions and constants on `char` have been stable since 1.52 and the freestanding items have soft-deprecated since 1.62 (https://github.com/rust-lang/rust/pull/95566). This PR ~~marks them as "deprecated in future", similar to the integer and floating point modules (`core::{i32, f32}` etc)~~ replaces all uses of `core::char::*` with `char::*` to prepare for future deprecation of `core::char::*`.
2023-02-12 11:09:06 +00:00
Scott McMurray
5bc328fdef Allow canonicalizing the array::map loop in trusted cases 2023-02-04 16:44:51 -08:00
Scott McMurray
5a7342c3dd Stop using into_iter in array::map 2023-02-04 16:41:35 -08:00
Nikolai Vazquez
734a91358b Remove unnecessary &format!
These were likely from before the `PartialEq<str>` impl for `&String`.
2023-01-21 22:06:42 -05:00
André Vennberg
0b35f448f8 Remove various double spaces in source comments. 2023-01-14 17:22:04 +01:00
Lukas Markeffsky
76e216f29b Use associated items of char instead of freestanding items in core::char 2023-01-14 11:58:41 +01:00
Daniel Henry-Mantilla
48b7e2a5b9
Stabilize ::{core,std}::pin::pin! 2023-01-11 14:09:14 -08:00
nils
c962b07ed3
Rollup merge of #106570 - Xaeroxe:div-duration-tests, r=JohnTitor
add tests for div_duration_* functions

Per https://github.com/rust-lang/rust/issues/63139#issuecomment-817070719

this adds unit tests for the functions that will hopefully effectively demonstrate that `div_duration` is ready to be stabilized.
2023-01-11 17:30:54 +01:00
Jacob Kiesel
9fd744b3e3 add tests for div_duration_* functions 2023-01-07 11:05:33 -07:00
Thom Chiovoloni
a4bf36e87b
Update rand in the stdlib tests, and remove the getrandom feature from it 2023-01-04 14:52:41 -08:00
David Tolnay
257e766c0c
Remove test of static Context
Context is no longer Sync so this doesn't work.

    error[E0277]: `*mut ()` cannot be shared between threads safely
      --> library/core/tests/task.rs:24:21
       |
    24 |     static CONTEXT: Context<'static> = Context::from_waker(&WAKER);
       |                     ^^^^^^^^^^^^^^^^ `*mut ()` cannot be shared between threads safely
       |
       = help: within `Context<'static>`, the trait `Sync` is not implemented for `*mut ()`
       = note: required because it appears within the type `PhantomData<*mut ()>`
       = note: required because it appears within the type `Context<'static>`
       = note: shared static variables must have a type that implements `Sync`
2023-01-02 10:33:23 -08:00
jonathanCogan
78691e3589 Update paths in comments. 2022-12-30 14:00:42 +01:00
jonathanCogan
db47071df2 Replace libstd, libcore, liballoc in line comments. 2022-12-30 14:00:42 +01:00
Pietro Albini
11191279b7 Update bootstrap cfg 2022-12-28 09:18:43 -05:00
Michael Goulet
4b668a1fee
Rollup merge of #103718 - matklad:infer-lazy, r=dtolnay
More inference-friendly API for lazy

The signature for new was

```
fn new<F>(f: F) -> Lazy<T, F>
```

Notably, with `F` unconstrained, `T` can be literally anything, and just `let _ = Lazy::new(|| 92)` would not typecheck.

This historiacally was a necessity -- `new` is a `const` function, it couldn't have any bounds. Today though, we can move `new` under the `F: FnOnce() -> T` bound, which gives the compiler enough data to infer the type of T from closure.
2022-12-27 12:33:33 -08:00
Michal Nazarewicz
28162ad970 char: µoptimise UTF-16 surrogates decoding
According to Godbolt¹, on x86_64 using binary and produces slightly
better code than using subtraction.  Readability of both is pretty
much equivalent so might just as well use the shorter option.

¹ https://rust.godbolt.org/z/9jM3ejbMx
2022-12-23 14:15:33 +01:00
Scott McMurray
9d68a1a74c Tune RepeatWith::try_fold and Take::for_each and Vec::extend_trusted 2022-11-24 19:14:19 -08:00
Manish Goregaokar
1dd515f273
Rollup merge of #83608 - Kimundi:index_many, r=Mark-Simulacrum
Add slice methods for indexing via an array of indices.

Disclaimer: It's been a while since I contributed to the main Rust repo, apologies in advance if this is large enough already that it should've been an RFC.

---

# Update:

- Based on feedback, removed the `&[T]` variant of this API, and removed the requirements for the indices to be sorted.

# Description

This adds the following slice methods to `core`:

```rust
impl<T> [T] {
    pub unsafe fn get_many_unchecked_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut T; N];
    pub fn get_many_mut<const N: usize>(&mut self, indices: [usize; N]) -> Option<[&mut T; N]>;
}
```

This allows creating multiple mutable references to disjunct positions in a slice, which previously required writing some awkward code with `split_at_mut()` or `iter_mut()`. For the bound-checked variant, the indices are checked against each other and against the bounds of the slice, which requires `N * (N + 1) / 2` comparison operations.

This has a proof-of-concept standalone implementation here: https://crates.io/crates/index_many

Care has been taken that the implementation passes miri borrow checks, and generates straight-forward assembly (though this was only checked on x86_64).

# Example

```rust
let v = &mut [1, 2, 3, 4];
let [a, b] = v.get_many_mut([0, 2]).unwrap();
std::mem::swap(a, b);
*v += 100;
assert_eq!(v, &[3, 2, 101, 4]);
```

# Codegen Examples

<details>
  <summary>Click to expand!</summary>

Disclaimer: Taken from local tests with the standalone implementation.

## Unchecked Indexing:

```rust
pub unsafe fn example_unchecked(slice: &mut [usize], indices: [usize; 3]) -> [&mut usize; 3] {
    slice.get_many_unchecked_mut(indices)
}
```

```nasm
example_unchecked:
 mov     rcx, qword, ptr, [r9]
 mov     r8, qword, ptr, [r9, +, 8]
 mov     r9, qword, ptr, [r9, +, 16]
 lea     rcx, [rdx, +, 8*rcx]
 lea     r8, [rdx, +, 8*r8]
 lea     rdx, [rdx, +, 8*r9]
 mov     qword, ptr, [rax], rcx
 mov     qword, ptr, [rax, +, 8], r8
 mov     qword, ptr, [rax, +, 16], rdx
 ret
```

## Checked Indexing (Option):

```rust
pub unsafe fn example_option(slice: &mut [usize], indices: [usize; 3]) -> Option<[&mut usize; 3]> {
    slice.get_many_mut(indices)
}
```

```nasm
 mov     r10, qword, ptr, [r9, +, 8]
 mov     rcx, qword, ptr, [r9, +, 16]
 cmp     rcx, r10
 je      .LBB0_7
 mov     r9, qword, ptr, [r9]
 cmp     rcx, r9
 je      .LBB0_7
 cmp     rcx, r8
 jae     .LBB0_7
 cmp     r10, r9
 je      .LBB0_7
 cmp     r9, r8
 jae     .LBB0_7
 cmp     r10, r8
 jae     .LBB0_7
 lea     r8, [rdx, +, 8*r9]
 lea     r9, [rdx, +, 8*r10]
 lea     rcx, [rdx, +, 8*rcx]
 mov     qword, ptr, [rax], r8
 mov     qword, ptr, [rax, +, 8], r9
 mov     qword, ptr, [rax, +, 16], rcx
 ret
.LBB0_7:
 mov     qword, ptr, [rax], 0
 ret
```

## Checked Indexing (Panic):

```rust
pub fn example_panic(slice: &mut [usize], indices: [usize; 3]) -> [&mut usize; 3] {
    let len = slice.len();
    match slice.get_many_mut(indices) {
        Some(s) => s,
        None => {
            let tmp = indices;
            index_many::sorted_bound_check_failed(&tmp, len)
        }
    }
}
```

```nasm
example_panic:
 sub     rsp, 56
 mov     rax, qword, ptr, [r9]
 mov     r10, qword, ptr, [r9, +, 8]
 mov     r9, qword, ptr, [r9, +, 16]
 cmp     r9, r10
 je      .LBB0_6
 cmp     r9, rax
 je      .LBB0_6
 cmp     r9, r8
 jae     .LBB0_6
 cmp     r10, rax
 je      .LBB0_6
 cmp     rax, r8
 jae     .LBB0_6
 cmp     r10, r8
 jae     .LBB0_6
 lea     rax, [rdx, +, 8*rax]
 lea     r8, [rdx, +, 8*r10]
 lea     rdx, [rdx, +, 8*r9]
 mov     qword, ptr, [rcx], rax
 mov     qword, ptr, [rcx, +, 8], r8
 mov     qword, ptr, [rcx, +, 16], rdx
 mov     rax, rcx
 add     rsp, 56
 ret
.LBB0_6:
 mov     qword, ptr, [rsp, +, 32], rax
 mov     qword, ptr, [rsp, +, 40], r10
 mov     qword, ptr, [rsp, +, 48], r9
 lea     rcx, [rsp, +, 32]
 mov     edx, 3
 call    index_many::bound_check_failed
 ud2
```
</details>

# Extensions

There are multiple optional extensions to this.

## Indexing With Ranges

This could easily be expanded to allow indexing with `[I; N]` where `I: SliceIndex<Self>`.  I wanted to keep the initial implementation simple, so I didn't include it yet.

## Panicking Variant

We could also add this method:

```rust
impl<T> [T] {
    fn index_many_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut T; N];
}
```

This would work similar to the regular index operator and panic with out-of-bound indices. The advantage would be that we could more easily ensure good codegen with a useful panic message, which is non-trivial with the `Option` variant.

This is implemented in the standalone implementation, and used as basis for the codegen examples here and there.
2022-11-22 01:26:05 -05:00
Marvin Löbel
3fe37b8c6e Add get_many_mut methods to slice 2022-11-20 11:19:11 -05:00
Ralf Jung
428ab59fb7 enable fuzzy_provenance_casts in libcore+tests 2022-11-20 16:04:16 +01:00
Ralf Jung
2bb28c174b avoid non-strict-provenance casts in libcore tests 2022-11-20 09:58:29 +01:00
Yuki Okushi
785237d392
Rollup merge of #104435 - scottmcm:iter-repeat-n, r=thomcc
`VecDeque::resize` should re-use the buffer in the passed-in element

Today it always copies it for *every* appended element, but one of those clones is avoidable.

This adds `iter::repeat_n` (https://github.com/rust-lang/rust/issues/104434) as the primitive needed to do this.  If this PR is acceptable, I'll also use this in `Vec` rather than its custom `ExtendElement` type & infrastructure that is harder to share between multiple different containers:

101e1822c3/library/alloc/src/vec/mod.rs (L2479-L2492)
2022-11-20 13:15:59 +09:00
Lukas Markeffsky
c9c017dfb5 update provenance test
* fix allocation alignment for 16bit platforms
* add edge case where `stride % align != 0` on pointers with provenance
2022-11-19 16:58:02 +01:00
Lukas Markeffsky
9e5d497b67 fix const align_offset implementation 2022-11-19 16:57:58 +01:00
Lukas Markeffsky
2ef9a8ae0f add coretests for is_aligned 2022-11-19 16:47:42 +01:00
Lukas Markeffsky
8cf6b16185 add coretests for const align_offset 2022-11-19 16:47:38 +01:00
Manish Goregaokar
6b09d60f82
Rollup merge of #103378 - nagisa:fix-infinite-offset, r=scottmcm
Fix mod_inv termination for the last iteration

On usize=u64 platforms, the 4th iteration would overflow the `mod_gate` back to 0. Similarly for usize=u32 platforms, the 3rd iteration would overflow much the same way.

I tested various approaches to resolving this, including approaches with `saturating_mul` and `widening_mul` to a double usize. Turns out LLVM likes `mul_with_overflow` the best. In fact now, that LLVM can see the iteration count is limited, it will happily unroll the loop into a nice linear sequence.

You will also notice that the code around the loop got simplified somewhat. Now that LLVM is handling the loop nicely, there isn’t any more reasons to manually unroll the first iteration out of the loop (though looking at the code today I’m not sure all that complexity was necessary in the first place).

Fixes #103361
2022-11-18 17:48:16 -05:00
bors
e702534763 Auto merge of #102935 - ajtribick:display-float-0.5-fixed-0, r=scottmcm
Fix inconsistent rounding of 0.5 when formatted to 0 decimal places

As described in #70336, when displaying values to zero decimal places the value of 0.5 is rounded to 1, which is inconsistent with the display of other half-integer values which round to even.

From testing the flt2dec implementation, it looks like this comes down to the condition in the fixed-width Dragon implementation where an empty buffer is treated as a case to apply rounding up. I believe the change below fixes it and updates only the relevant tests.

Nevertheless I am aware this is very much a core piece of functionality, so please take a very careful look to make sure I haven't missed anything. I hope this change does not break anything in the wider ecosystem as having a consistent rounding behaviour in floating point formatting is in my opinion a useful feature to have.

Resolves #70336
2022-11-16 07:20:30 +00:00
Scott McMurray
d62b903892 VecDeque::resize should re-use the buffer in the passed-in element
Today it always copies it for *every* appended element, but one of those clones is avoidable.
2022-11-15 00:53:26 -08:00
bors
338cfd3cce Auto merge of #103858 - Mark-Simulacrum:bump-bootstrap, r=pietroalbini
Bump bootstrap compiler to 1.66

This PR:

- Bumps version placeholders to release
- Bumps to latest beta
- cfg-steps code

r? `@pietroalbini`
2022-11-14 00:07:19 +00:00
Manish Goregaokar
150e0ec393
Rollup merge of #104060 - ink-feather-org:const_hash, r=fee1-dead
Make `Hash`, `Hasher` and `BuildHasher` `#[const_trait]` and make `Sip` const `Hasher`

This PR enables using Hashes in const context.

r? ``@fee1-dead``
2022-11-10 10:47:38 -05:00
Dylan DPC
1db7f690b1
Rollup merge of #103570 - lukas-code:stabilize-ilog, r=scottmcm
Stabilize integer logarithms

Stabilizes feature `int_log`.

I've also made the functions const stable, because they don't depend on any unstable const features. `rustc_allow_const_fn_unstable` is just there for `Option::expect`, which could be replaced with a `match` and `panic!`. cc ``@rust-lang/wg-const-eval``

closes https://github.com/rust-lang/rust/issues/70887 (tracking issue)

~~blocked on FCP finishing: https://github.com/rust-lang/rust/issues/70887#issuecomment-1289028216~~
FCP finished: https://github.com/rust-lang/rust/issues/70887#issuecomment-1302121266
2022-11-09 19:21:21 +05:30
onestacked
56e59bcb27 Test const Hash, fix nits 2022-11-08 17:39:40 +01:00
The 8472
43c353fff7 simplification: do not process the ArrayChunks remainder in fold() 2022-11-07 21:44:25 +01:00
Mark Rousskov
40290505fb cfg-step code 2022-11-06 17:21:21 -05:00
Michael Goulet
e24df2778f Format dyn Trait better in type_name intrinsic 2022-11-01 20:41:47 +00:00
Ralf Jung
d366471e58 interpret: fix align_of_val on packed types 2022-10-29 15:58:32 +02:00
Aleksey Kladov
3cddc8bff6 More inference-friendly API for lazy
The signature for new was

```
fn new<F>(f: F) -> Lazy<T, F>
```

Notably, with `F` unconstrained, `T` can be literally anything, and just
`let _ = Lazy::new(|| 92)` would not typecheck.

This historiacally was a necessity -- `new` is a `const` function, it
couldn't have any bounds. Today though, we can move `new` under the `F:
FnOnce() -> T` bound, which gives the compiler enough data to infer the
type of T from closure.
2022-10-29 09:56:20 +01:00
Lukas Markeffsky
9e36fd926c stabilize int_log 2022-10-26 11:58:33 +02:00
Dylan DPC
2326f42ce2 stabilise array methods 2022-10-25 18:07:21 +05:30
Dylan DPC
d2d44f619f
Rollup merge of #98204 - Kixiron:stable-unzip, r=thomcc
Stabilize `Option::unzip()`

Stabilizes `Option::unzip()`, closes #87800

```@rustbot``` modify labels: +T-libs-api
2022-10-25 14:43:13 +05:30
Yuki Okushi
c1f9d985d7
Rollup merge of #102271 - lopopolo:lopopolo/stabilize-duration-try-from-secs-float, r=dtolnay
Stabilize `duration_checked_float`

## Stabilization Report

This stabilization report is for a stabilization of `duration_checked_float`, tracking issue: https://github.com/rust-lang/rust/issues/83400.

### Implementation History

- https://github.com/rust-lang/rust/pull/82179
- https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051
- Changed error type to `FromFloatSecsError` in https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051 changes the rounding mode to round-to-nearest instead of truncate.

## API Summary

This stabilization report proposes the following API to be stabilized in `core`, along with their re-exports in `std`:

```rust
// core::time

impl Duration {
    pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, TryFromFloatSecsError>;
    pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TryFromFloatSecsError { ... }

impl core::fmt::Display for TryFromFloatSecsError { ... }
impl core::error::Error for TryFromFloatSecsError { ... }
```

These functions are made const unstable under `duration_consts_float`, tracking issue #72440.

There is an open question in the tracking issue around what the error type should be called which I was hoping to resolve in the context of an FCP.

In this stabilization PR, I have altered the name of the error type to `TryFromFloatSecsError`. In my opinion, the error type shares the name of the method (adjusted to accommodate both types of floats), which is consistent with other error types in `core`, `alloc` and `std` like `TryReserveError` and `TryFromIntError`.

## Experience Report

Code such as this is ready to be converted to a checked API to ensure it is panic free:

```rust
impl Time {
    pub fn checked_add_f64(&self, seconds: f64) -> Result<Self, TimeError> {
        // Fail safely during `f64` conversion to duration
        if seconds.is_nan() || seconds.is_infinite() {
            return Err(TzOutOfRangeError::new().into());
        }

        if seconds.is_sign_positive() {
            self.checked_add(Duration::from_secs_f64(seconds))
        } else {
            self.checked_sub(Duration::from_secs_f64(-seconds))
        }
    }
}
```

See: https://github.com/artichoke/artichoke/issues/2194.

`@rustbot` label +T-libs-api -T-libs

cc `@mbartlett21`
2022-10-24 19:32:26 +09:00
Simonas Kazlauskas
a3c3f722b7 Fix mod_inv termination for the last iteration
On usize=u64 platforms, the 4th iteration would overflow the `mod_gate`
back to 0. Similarly for usize=u32 platforms, the 3rd iteration would
overflow much the same way.

I tested various approaches to resolving this, including approaches with
`saturating_mul` and `widening_mul` to a double usize. Turns out LLVM
likes `mul_with_overflow` the best. In fact now, that LLVM can see the
iteration count is limited, it will happily unroll the loop into a nice
linear sequence.

You will also notice that the code around the loop got simplified
somewhat. Now that LLVM is handling the loop nicely, there isn’t any
more reasons to manually unroll the first iteration out of the loop
(though looking at the code today I’m not sure all that complexity was
necessary in the first place).

Fixes #103361
2022-10-22 03:46:48 +03:00
Andrew Tribick
aa9837ba29 Add tests for rounding of ties during float formatting 2022-10-20 22:09:24 +02:00
Thom Chiovoloni
afd08175de
Adjust transmute{,_copy} to be clearer about which of T and U is input vs output 2022-10-19 22:36:14 -07:00
Alex Saveau
55d71c61b8
Remove all uses of array_assume_init
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17 13:03:54 -07:00
Ryan Lopopolo
95040a70d7
Stabilize duration_checked_float
Tracking issue:

- https://github.com/rust-lang/rust/issues/83400
2022-10-15 12:02:13 -07:00
bors
8147e6e427 Auto merge of #103069 - matthiaskrgr:rollup-xxsx6sk, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #102092 (refactor: use grep -E/-F instead of fgrep/egrep)
 - #102781 (Improved documentation for `std::io::Error`)
 - #103017 (Avoid dropping TLS Key on sgx)
 - #103039 (checktools: fix comments)
 - #103045 (Remove leading newlines from integer primitive doc examples)
 - #103047 (Update browser-ui-test version to fix some flaky tests)
 - #103054 (Clean up rust-logo rustdoc GUI test)
 - #103059 (Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`)
 - #103067 (More alphabetical sorting)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-14 22:56:53 +00:00
bors
bf15a9e526 Auto merge of #101030 - woppopo:const_location, r=scottmcm
Constify `Location` methods

Tracking issue: #102911

Example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4789884c2f16ec4fb0e0405d86b794f5
2022-10-14 20:15:51 +00:00
beetrees
c9948f5c5f
Fix Duration::{try_,}from_secs_f{32,64}(-0.0) 2022-10-14 16:07:09 +01:00
Rageking8
7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
Dylan DPC
d8091f8991
Rollup merge of #102578 - lukas-code:ilog-panic, r=m-ou-se
Panic for invalid arguments of `{integer primitive}::ilog{,2,10}` in all modes

Decision made in https://github.com/rust-lang/rust/issues/100422#issuecomment-1245864700

resolves https://github.com/rust-lang/rust/issues/100422

tracking issue: https://github.com/rust-lang/rust/issues/70887

r? `@m-ou-se`
2022-10-12 11:11:25 +05:30
Andrew Tribick
848744403a Fix inconsistent rounding of 0.5 when formatted to 0 decimal places 2022-10-11 23:09:23 +02:00
woppopo
a53e3acca9 Change tracking issue from #76156 to #102911 2022-10-11 06:40:37 +00:00
Maybe Waffle
7434b9f0d1 fixup lint name 2022-10-09 13:07:21 +00:00
Maybe Waffle
75ae20a42f allow for_loop_over_fallibles in a core test 2022-10-09 13:07:20 +00:00
woppopo
f0b8167a4e Fix test (location_const_file) 2022-10-08 11:48:53 +00:00
Ralf Jung
fd59d44f58 make const_err a hard error 2022-10-07 18:08:49 +02:00
Matthias Krüger
a5488826a9
Rollup merge of #101308 - nerdypepper:feature/is-ascii-octdigit, r=joshtriplett
introduce `{char, u8}::is_ascii_octdigit`

This feature adds two new APIs: `char::is_ascii_octdigit` and `u8::is_ascii_octdigit`, under the feature gate `is_ascii_octdigit`. These methods are shorthands for `char::is_digit(self, 8)` and `u8::is_digit(self, 8)`:

```rust
// core::char

impl char {
    pub fn is_ascii_octdigit(self) -> bool;
}

// core::num

impl u8 {
    pub fn is_ascii_octdigit(self) -> bool;
}
```

---

Couple of things I need help understanding:

- `const`ness: have I used the right attribute in this case?
- is there a way to run the tests for `core::char` alone, instead of `./x.py test library/core`?
2022-10-03 20:58:56 +02:00
Lukas Markeffsky
6acc29f88b add tests for panicking integer logarithms 2022-10-02 14:25:36 +02:00
beetrees
e409ce2159
Fix integer overflow in format!("{:.0?}", Duration::MAX) 2022-09-29 23:06:22 +01:00
woppopo
7b993885d0 Sort mod 2022-09-27 19:53:58 +00:00
woppopo
ca55a88161 Fix indent 2022-09-27 19:40:53 +00:00
woppopo
767a7771c7 Add newlines 2022-09-27 19:23:52 +00:00
woppopo
834cab7244 Add test cases for const Location 2022-09-27 19:09:32 +00:00
Urgau
9ad2f00f6a Stabilize bench_black_box 2022-09-27 17:38:51 +02:00
Akshay
591c1f25b2 introduce {char, u8}::is_ascii_octdigit 2022-09-27 11:55:13 +05:30
y86-dev
9a78faba71 Made from_waker, waker, from_raw const 2022-09-14 14:53:16 +02:00
bors
7200da0217 Auto merge of #93873 - Stovent:big-ints, r=m-ou-se
Reimplement `carrying_add` and `borrowing_sub` for signed integers.

As per the discussion in #85532, this PR reimplements `carrying_add` and `borrowing_sub` for signed integers.

It also adds unit tests for both unsigned and signed integers, emphasing on the behaviours of the methods.
2022-09-09 00:59:08 +00:00
Guillaume Gomez
0e82dc969f
Rollup merge of #99583 - shepmaster:provider-plus-plus, r=yaahc
Add additional methods to the Demand type

This adds on to the original tracking issue #96024

r? `````@yaahc`````
2022-09-02 11:34:46 +02:00
Dylan DPC
395ce34a95
Rollup merge of #100819 - WaffleLapkin:use_ptr_byte_methods, r=scottmcm
Make use of `[wrapping_]byte_{add,sub}`

These new methods trivially replace old `.cast().wrapping_offset().cast()` & similar code.
Note that [`arith_offset`](https://doc.rust-lang.org/std/intrinsics/fn.arith_offset.html) and `wrapping_offset` are the same thing.

r? ``@scottmcm``

_split off from #100746_
2022-08-29 16:49:43 +05:30
Yuki Okushi
ba31a9b505
Rollup merge of #100604 - dtolnay:okorerr, r=m-ou-se
Remove unstable Result::into_ok_or_err

Pending FCP: https://github.com/rust-lang/rust/issues/82223#issuecomment-1214920203

```@rustbot``` label +waiting-on-fcp
2022-08-26 09:51:44 +09:00
Matthias Krüger
6deca5f067
Rollup merge of #100220 - scottmcm:fix-by-ref-sized, r=joshtriplett
Properly forward `ByRefSized::fold` to the inner iterator

cc ``@timvermeulen,`` who noticed this mistake in https://github.com/rust-lang/rust/pull/100214#issuecomment-1207317625
2022-08-24 18:20:08 +02:00
Maybe Waffle
53565b23ac Make use of [wrapping_]byte_{add,sub}
...replacing `.cast().wrapping_offset().cast()` & similar code.
2022-08-23 19:32:37 +04:00
Jake Goulding
38de102cff Support eager and lazy methods for providing references and values
There are times where computing a value may be cheap, or where
computing a reference may be expensive, so this fills out the
possibilities.
2022-08-23 09:58:50 -04:00
Matthias Krüger
d49906519b
Rollup merge of #99544 - dylni:expose-utf8lossy, r=Mark-Simulacrum
Expose `Utf8Lossy` as `Utf8Chunks`

This PR changes the feature for `Utf8Lossy` from `str_internals` to `utf8_lossy` and improves the API. This is done to eventually expose the API as stable.

Proposal: rust-lang/libs-team#54
Tracking Issue: #99543
2022-08-20 19:32:07 +02:00
dylni
e8ee0b7b2b Expose Utf8Lossy as Utf8Chunks 2022-08-20 12:49:20 -04:00
bors
6c943bad02 Auto merge of #99541 - timvermeulen:flatten_cleanup, r=the8472
Refactor iteration logic in the `Flatten` and `FlatMap` iterators

The `Flatten` and `FlatMap` iterators both delegate to `FlattenCompat`:
```rust
struct FlattenCompat<I, U> {
    iter: Fuse<I>,
    frontiter: Option<U>,
    backiter: Option<U>,
}
```
Every individual iterator method that `FlattenCompat` implements needs to carefully manage this state, checking whether the `frontiter` and `backiter` are present, and storing the current iterator appropriately if iteration is aborted. This has led to methods such as `next`, `advance_by`, and `try_fold` all having similar code for managing the iterator's state.

I have extracted this common logic of iterating the inner iterators with the option to exit early into a `iter_try_fold` method:
```rust
impl<I, U> FlattenCompat<I, U>
where
    I: Iterator<Item: IntoIterator<IntoIter = U>>,
{
    fn iter_try_fold<Acc, Fold, R>(&mut self, acc: Acc, fold: Fold) -> R
    where
        Fold: FnMut(Acc, &mut U) -> R,
        R: Try<Output = Acc>,
    { ... }
}
```
It passes each of the inner iterators to the given function as long as it keep succeeding. It takes care of managing `FlattenCompat`'s state, so that the actual `Iterator` methods don't need to. The resulting code that makes use of this abstraction is much more straightforward:
```rust
fn next(&mut self) -> Option<U::Item> {
    #[inline]
    fn next<U: Iterator>((): (), iter: &mut U) -> ControlFlow<U::Item> {
        match iter.next() {
            None => ControlFlow::CONTINUE,
            Some(x) => ControlFlow::Break(x),
        }
    }

    self.iter_try_fold((), next).break_value()
}
```
Note that despite being implemented in terms of `iter_try_fold`, `next` is still able to benefit from `U`'s `next` method. It therefore does not take the performance hit that implementing `next` directly in terms of `Self::try_fold` causes (in some benchmarks).

This PR also adds `iter_try_rfold` which captures the shared logic of `try_rfold` and `advance_back_by`, as well as `iter_fold` and `iter_rfold` for folding without early exits (used by `fold`, `rfold`, `count`, and `last`).

Benchmark results:
```
                                             before                after
bench_flat_map_sum                       423,255 ns/iter      414,338 ns/iter
bench_flat_map_ref_sum                 1,942,139 ns/iter    2,216,643 ns/iter
bench_flat_map_chain_sum               1,616,840 ns/iter    1,246,445 ns/iter
bench_flat_map_chain_ref_sum           4,348,110 ns/iter    3,574,775 ns/iter
bench_flat_map_chain_option_sum          780,037 ns/iter      780,679 ns/iter
bench_flat_map_chain_option_ref_sum    2,056,458 ns/iter      834,932 ns/iter
```

I added the last two benchmarks specifically to demonstrate an extreme case where `FlatMap::next` can benefit from custom internal iteration of the outer iterator, so take it with a grain of salt. We should probably do a perf run to see if the changes to `next` are worth it in practice.
2022-08-19 02:34:30 +00:00
David Tolnay
83f081fc01
Remove unstable Result::into_ok_or_err 2022-08-17 17:20:42 -07:00
Scott McMurray
7680c8b690 Properly forward ByRefSized::fold to the inner iterator 2022-08-14 22:55:30 -07:00
austinabell
00bc9e8ac4
fix(iter::skip): Optimize next and nth implementations of Skip 2022-08-14 13:25:13 -04:00
Dylan DPC
482a6eaf10
Rollup merge of #100026 - WaffleLapkin:array-chunks, r=scottmcm
Add `Iterator::array_chunks` (take N+1)

A revival of https://github.com/rust-lang/rust/pull/92393.

r? `@Mark-Simulacrum`
cc `@rossmacarthur` `@scottmcm` `@the8472`

I've tried to address most of the review comments on the previous attempt. The only thing I didn't address is `try_fold` implementation, I've left the "custom" one for now, not sure what exactly should it use.
2022-08-14 17:09:14 +05:30
Dylan DPC
51eed00ca9
Rollup merge of #100030 - WaffleLapkin:nice_pointer_sis, r=scottmcm
cleanup code w/ pointers in std a little

Use pointer methods (`byte_add`, `null_mut`, etc) to make code in std a little nicer.
2022-08-12 20:39:10 +05:30
Matthias Krüger
275d4e779a
Rollup merge of #100112 - RalfJung:assert_send_and_sync, r=m-ou-se
Fix test: chunks_mut_are_send_and_sync

Follow-up to https://github.com/rust-lang/rust/pull/100023 to make the test actually effective
2022-08-11 22:53:03 +02:00
bors
908fc5b26d Auto merge of #99174 - scottmcm:reoptimize-layout-array, r=joshtriplett
Reoptimize layout array

This way it's one check instead of two, so hopefully (cc #99117) it'll be simpler for rustc perf too 🤞

Quick demonstration:
```rust
pub fn demo(n: usize) -> Option<Layout> {
    Layout::array::<i32>(n).ok()
}
```

Nightly: <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=e97bf33508aa03f38968101cdeb5322d>
```nasm
	mov	rax, rdi
	mov	ecx, 4
	mul	rcx
	seto	cl
	movabs	rdx, 9223372036854775805
	xor	esi, esi
	cmp	rax, rdx
	setb	sil
	shl	rsi, 2
	xor	edx, edx
	test	cl, cl
	cmove	rdx, rsi
	ret
```

This PR (note no `mul`, in addition to being much shorter):
```nasm
	xor	edx, edx
	lea	rax, [4*rcx]
	shr	rcx, 61
	sete	dl
	shl	rdx, 2
	ret
```

This is built atop `@CAD97` 's #99136; the new changes are cb8aba66ef6a0e17f08a0574e4820653e31b45a0.

I added a bunch more tests for `Layout::from_size_align` and `Layout::array` too.
2022-08-10 23:50:18 +00:00
Eric Holk
c18f22058b Rename integer log* methods to ilog*
This reflects the concensus from the libs team as reported at
https://github.com/rust-lang/rust/issues/70887#issuecomment-1209513261

Co-authored-by: Yosh Wuyts <github@yosh.is>
2022-08-09 10:20:49 -07:00
Maybe Waffle
127b6c4c18 cleanup code w/ pointers in std a little 2022-08-05 16:47:49 +04:00
Tim Vermeulen
3f7004920c Move fold logic to iter_fold method and reuse it in count and last 2022-08-05 03:43:39 +02:00
Ralf Jung
a61c841385 actually call assert_send_and_sync 2022-08-03 12:44:21 -04:00
Maybe Waffle
4db628a801 Remove incorrect impl TrustedLen for ArrayChunks
As explained in the review of the previous attempt to add `ArrayChunks`,
adapters that shrink the length can't implement `TrustedLen`.
2022-08-01 19:16:24 +04:00
Ben Kimock
22dfbdd707 Add back Send and Sync impls on ChunksMut iterators
These were accidentally removed in #94247 because the representation was
changed from &mut [T] to *mut T, which has !Send + !Sync.
2022-08-01 10:32:45 -04:00
Ross MacArthur
f5485181ca Use array::IntoIter for the ArrayChunks remainder 2022-08-01 16:39:30 +04:00
Ross MacArthur
ca3d1010bb Add Iterator::array_chunks() 2022-08-01 16:39:27 +04:00
Guillaume Gomez
ef81fca760
Rollup merge of #94247 - saethlin:chunksmut-aliasing, r=the8472
Fix slice::ChunksMut aliasing

Fixes https://github.com/rust-lang/rust/issues/94231, details in that issue.
cc `@RalfJung`

This isn't done just yet, all the safety comments are placeholders. But otherwise, it seems to work.

I don't really like this approach though. There's a lot of unsafe code where there wasn't before, but as far as I can tell the only other way to uphold the aliasing requirement imposed by `__iterator_get_unchecked` is to use raw slices, which I think require the same amount of unsafe code. All that would do is tie the `len` and `ptr` fields together.

Oh I just looked and I'm pretty sure that `ChunksExactMut`, `RChunksMut`, and `RChunksExactMut` also need to be patched. Even more reason to put up a draft.
2022-07-27 17:55:01 +02:00
bors
41419e7036 Auto merge of #99491 - workingjubilee:sync-psimd, r=workingjubilee
Sync in portable-simd subtree

r? `@ghost`
2022-07-22 09:48:00 +00:00
Jubilee Young
f8aa494c69 Introduce core::simd trait imports in tests 2022-07-20 18:08:20 -07:00
bors
8bd12e8cca Auto merge of #98912 - nrc:provider-it, r=yaahc
core::any: replace some generic types with impl Trait

This gives a cleaner API since the caller only specifies the concrete type they usually want to.

r? `@yaahc`
2022-07-19 11:28:20 +00:00
Dylan DPC
e301cd39ad
Rollup merge of #99434 - timvermeulen:skip_next_non_fused, r=scottmcm
Fix `Skip::next` for non-fused inner iterators

`iter.skip(n).next()` will currently call `nth` and `next` in succession on `iter`, without checking whether `nth` exhausts the iterator. Using `?` to propagate a `None` value returned by `nth` avoids this.
2022-07-19 11:38:58 +05:30
Tim Vermeulen
e52837c362 Add note to test about Unfuse 2022-07-18 21:53:35 +02:00
Tim Vermeulen
50c612faef Fix Skip::next for non-fused inner iterators 2022-07-18 21:10:47 +02:00
Dylan DPC
5ccdf1f6f7
Rollup merge of #98839 - 5225225:assert_transmute_copy_size, r=thomcc
Add assertion that `transmute_copy`'s U is not larger than T

This is called out as a safety requirement in the docs, but because knowing this can be done at compile time and constant folded (just like the `align_of` branch is removed), we can just panic here.

I've looked at the asm (using `cargo-asm`) of a function that both is correct and incorrect, and the panic is completely removed, or is unconditional, without needing build-std.

I don't expect this to cause much breakage in the wild. I scanned through https://miri.saethlin.dev/ub for issues that would look like this (error: Undefined Behavior: memory access failed: alloc1768 has size 1, so pointer to 8 bytes starting at offset 0 is out-of-bounds), but couldn't find any.

That doesn't rule out it happening in crates tested that fail earlier for some other reason, though, but it indicates that doing this is rare, if it happens at all. A crater run for this would need to be build and test, since this is a runtime thing.

Also added a few more transmute_copy tests.
2022-07-18 21:14:42 +05:30
Yuki Okushi
50527690e2
Rollup merge of #99306 - JohnTitor:stabilize-future-poll-fn, r=joshtriplett
Stabilize `future_poll_fn`

FCP is done: https://github.com/rust-lang/rust/issues/72302#issuecomment-1179620512
Closes #72302

r? `@joshtriplett` as you started FCP

Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2022-07-17 13:08:52 +09:00
bors
db41351753 Auto merge of #98866 - nagisa:nagisa/align-offset-wroom, r=Mark-Simulacrum
Add a special case for align_offset /w stride != 1

This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:

    leaq 15(%rdi), %rax
    andq $-16, %rax

This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:

    pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
        slice.offset(slice.align_offset(16) as isize)
    }

    // =>

    movl %edi, %eax
    andl $3, %eax
    leaq 15(%rdi), %rcx
    andq $-16, %rcx
    subq %rdi, %rcx
    shrq $2, %rcx
    negq %rax
    sbbq %rax, %rax
    orq  %rcx, %rax
    leaq (%rdi,%rax,4), %rax

Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.

This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.

Fixes #98809.
Sadly, this does not help with #72356.
2022-07-16 23:28:28 +00:00
Simonas Kazlauskas
62a182cf7f Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:

    leaq 15(%rdi), %rax
    andq $-16, %rax

This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:

    pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
        slice.offset(slice.align_offset(16) as isize)
    }

    // =>

    movl %edi, %eax
    andl $3, %eax
    leaq 15(%rdi), %rcx
    andq $-16, %rcx
    subq %rdi, %rcx
    shrq $2, %rcx
    negq %rax
    sbbq %rax, %rax
    orq  %rcx, %rax
    leaq (%rdi,%rax,4), %rax

Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.

This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.

Fixes #98809.
Sadly, this does not help with #72356.
2022-07-17 01:27:37 +03:00
Yuki Okushi
084ad59622
Stabilize future_poll_fn
Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2022-07-16 10:04:14 +09:00
bors
24699bcbad Auto merge of #95956 - yaahc:stable-in-unstable, r=cjgillot
Support unstable moves via stable in unstable items

part of https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/moving.20items.20to.20core.20unstably and a blocker of https://github.com/rust-lang/rust/pull/90328.

The libs-api team needs the ability to move an already stable item to a new location unstably, in this case for Error in core. Otherwise these changes are insta-stable making them much harder to merge.

This PR attempts to solve the problem by checking the stability of path segments as well as the last item in the path itself, which is currently the only thing checked.
2022-07-14 13:42:09 +00:00
Dylan DPC
103b8602b7
Rollup merge of #98315 - joshtriplett:stabilize-core-ffi-c, r=Mark-Simulacrum
Stabilize `core::ffi:c_*` and rexport in `std::ffi`

This only stabilizes the base types, not the non-zero variants, since
those have their own separate tracking issue and have not gone through
FCP to stabilize.
2022-07-14 14:14:20 +05:30
Josh Triplett
d431338b25 Stabilize core::ffi:c_* and rexport in std::ffi
This only stabilizes the base types, not the non-zero variants, since
those have their own separate tracking issue and have not gone through
FCP to stabilize.
2022-07-13 19:28:20 -07:00
Scott McMurray
a32305a80f Re-optimize Layout::array
This way it's one check instead of two, so hopefully it'll be better

Nightly:
```
layout_array_i32:
	movq	%rdi, %rax
	movl	$4, %ecx
	mulq	%rcx
	jo	.LBB1_2
	movabsq	$9223372036854775805, %rcx
	cmpq	%rcx, %rax
	jae	.LBB1_2
	movl	$4, %edx
	retq
.LBB1_2:
	…
```

This PR:
```
	movq	%rcx, %rax
	shrq	$61, %rax
	jne	.LBB2_1
	shlq	$2, %rcx
	movl	$4, %edx
	movq	%rcx, %rax
	retq
.LBB2_1:
	…
```
2022-07-13 17:07:41 -07:00
Konrad Borowski
0753fd117b Partially stabilize const_slice_from_raw_parts
This doesn't stabilize methods working on mutable pointers.
2022-07-09 23:20:02 +02:00
Jane Losare-Lusby
d68cb1f9a3 revert changes to unicode stability 2022-07-08 21:18:15 +00:00
Guillaume Gomez
4755173cf6
Rollup merge of #96935 - thomcc:atomicptr-strict-prov, r=dtolnay
Allow arithmetic and certain bitwise ops on AtomicPtr

This is mainly to support migrating from `AtomicUsize`, for the strict provenance experiment.

This is a pretty dubious set of APIs, but it should be sufficient to allow code that's using `AtomicUsize` to manipulate a tagged pointer atomically. It's under a new feature gate, `#![feature(strict_provenance_atomic_ptr)]`, but I'm not sure if it needs its own tracking issue. I'm happy to make one, but it's not clear that it's needed.

I'm unsure if it needs changes in the various non-LLVM backends. Because we just cast things to integers anyway (and were already doing so), I doubt it.

API change proposal: https://github.com/rust-lang/libs-team/issues/60

Fixes #95492
2022-07-06 20:43:23 +02:00
Nick Cameron
0c72be3e1a core::any: replace some unstable generic types with impl Trait
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-07-05 15:06:31 +01:00
Dylan DPC
8fa1ed8f12
Rollup merge of #97712 - RalfJung:untyped, r=scottmcm
ptr::copy and ptr::swap are doing untyped copies

The consensus in https://github.com/rust-lang/rust/issues/63159 seemed to be that these operations should be "untyped", i.e., they should treat the data as raw bytes, should work when these bytes violate the validity invariant of `T`, and should exactly preserve the initialization state of the bytes that are being copied. This is already somewhat implied by the description of "copying/swapping size*N bytes" (rather than "N instances of `T`").

The implementations mostly already work that way (well, for LLVM's intrinsics the documentation is not precise enough to say what exactly happens to poison, but if this ever gets clarified to something that would *not* perfectly preserve poison, then I strongly assume there will be some way to make a copy that *does* perfectly preserve poison). However, I had to adjust `swap_nonoverlapping`; after ``@scottmcm's`` [recent changes](https://github.com/rust-lang/rust/pull/94212), that one (sometimes) made a typed copy. (Note that `mem::swap`, which works on mutable references, is unchanged. It is documented as "swapping the values at two mutable locations", which to me strongly indicates that it is indeed typed. It is also safe and can rely on `&mut T` pointing to a valid `T` as part of its safety invariant.)

On top of adding a test (that will be run by Miri), this PR then also adjusts the documentation to indeed stably promise the untyped semantics. I assume this means the PR has to go through t-libs (and maybe t-lang?) FCP.

Fixes https://github.com/rust-lang/rust/issues/63159
2022-07-05 16:04:31 +05:30
5225225
5f5ca88958 Add size assert in transmute_copy 2022-07-03 10:46:20 +01:00
Ben Kimock
7919e4208b Fix slice::ChunksMut aliasing 2022-07-03 00:15:15 -04:00
Pietro Albini
6b2d3d5f3c
update cfg(bootstrap)s 2022-07-01 15:48:23 +02:00
Thom Chiovoloni
e65ecee90e
Rename AtomicPtr::fetch_{add,sub}{,_bytes} 2022-07-01 06:21:19 -07:00
Thom Chiovoloni
2f872afdb5
Allow arithmetic and certain bitwise ops on AtomicPtr
This is mainly to support migrating from AtomicUsize, for the strict
provenance experiment.

Fixes #95492
2022-07-01 06:21:18 -07:00
Ralf Jung
8c977cfda8 libcore tests: avoid int2ptr casts 2022-06-27 13:30:44 -04:00
Ross MacArthur
bbdff1fff4
Add Iterator::next_chunk 2022-06-21 08:57:02 +02:00
Chase Wilson
59be3e856f
Stabilized Option::unzip() 2022-06-17 11:54:55 -05:00
Maybe Waffle
7c360dc117 Move/rename lazy::{OnceCell, Lazy} to cell::{OnceCell, LazyCell} 2022-06-16 19:53:59 +04:00
bors
e9aff9c42c Auto merge of #91970 - nrc:provide-any, r=scottmcm
Add the Provider api to core::any

This is an implementation of [RFC 3192](https://github.com/rust-lang/rfcs/pull/3192) ~~(which is yet to be merged, thus why this is a draft PR)~~. It adds an API for type-driven requests and provision of data from trait objects. A primary use case is for the `Error` trait, though that is not implemented in this PR. The only major difference to the RFC is that the functionality is added to the `any` module, rather than being in a sibling `provide_any` module (as discussed in the RFC thread).

~~Still todo: improve documentation on items, including adding examples.~~

cc `@yaahc`
2022-06-10 01:10:59 +00:00
Yuki Okushi
2b58e6314a
Stabilize const_intrinsic_copy 2022-06-08 20:17:28 +09:00
Ben Kimock
5dd5244423 Use repr(C) when depending on struct layout in ptr tests 2022-06-07 19:24:09 -04:00
Nick Cameron
843f90cbb7 Add some more tests
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:14 +01:00
Nick Cameron
57d027d23a Modify the signature of the request_* methods so that trait_upcasting is not required
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Nick Cameron
bb5db85f74 Add the Provider api to core::any
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2022-06-06 12:10:13 +01:00
Ralf Jung
b96d1e45f1 change ptr::swap methods to do untyped copies 2022-06-05 10:09:41 -04:00
Ralf Jung
4990021082 test const_copy to make sure bytewise pointer copies are working 2022-06-03 09:20:42 -04:00
Stovent
1266099742 Implement carrying_add and borrowing_sub on signed numbers 2022-05-30 18:32:27 -04:00
est31
cdb8e64bc7 Use Box::new() instead of box syntax in core tests 2022-05-29 01:44:11 +02:00
bors
9fed13030c Auto merge of #94954 - SimonSapin:null-thin3, r=yaahc
Extend ptr::null and null_mut to all thin (including extern) types

Fixes https://github.com/rust-lang/rust/issues/93959

This change was accepted in https://rust-lang.github.io/rfcs/2580-ptr-meta.html

Note that this changes the signature of **stable** functions. The change should be backward-compatible, but it is **insta-stable** since it cannot (easily, at all?) be made available only through a `#![feature(…)]` opt-in.

The RFC also proposed the same change for `NonNull::dangling`, which makes sense it terms of its signature but not in terms of its implementation. `dangling` uses `align_of()` as an address. But what `align_of()` should be for extern types or whether it should be allowed at all remains an open question.

This commit depends on https://github.com/rust-lang/rust/pull/93977, which is not yet part of the bootstrap compiler. So `#[cfg]` is used to only apply the change in stage 1+. As far a I know bounds cannot be made conditional with `#[cfg]`, so the entire functions are duplicated. This is unfortunate but temporary.

Since this duplication makes it less obvious in the diff, the new definitions differ in:

* More permissive bounds (`Thin` instead of implied `Sized`)
* Different implementation
* Having `rustc_allow_const_fn_unstable(const_fn_trait_bound)`
* Having `rustc_allow_const_fn_unstable(ptr_metadata)`
2022-05-25 13:58:51 +00:00
Caio
664e8a9ce5 [RFC 2011] Library code 2022-05-22 07:18:32 -03:00
bors
bb5e6c984d Auto merge of #97265 - JohnTitor:rollup-kgthnjt, r=JohnTitor
Rollup of 6 pull requests

Successful merges:

 - #97144 (Fix rusty grammar in `std::error::Reporter` docs)
 - #97225 (Fix `Display` for `cell::{Ref,RefMut}`)
 - #97228 (Omit stdarch workspace from rust-src)
 - #97236 (Recover when resolution did not resolve lifetimes.)
 - #97245 (Fix typo in futex RwLock::write_contended.)
 - #97259 (Fix typo in Mir phase docs)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-22 04:27:10 +00:00
Josh Stone
83abb7c18f Fix Display for cell::{Ref,RefMut}
These guards changed to pointers in #97027, but their `Display` was
formatting that field directly, which made it show the raw pointer
value. Now we go through `Deref` to display the real value again.
2022-05-20 11:16:30 -07:00
Caio
d917112606 Stabilize core::array::from_fn 2022-05-20 11:04:13 -03:00
Mark Rousskov
32fdc6b207 Stage-step cfgs 2022-05-18 12:29:35 -04:00
bors
9fbbe75fd7 Auto merge of #95602 - scottmcm:faster-array-intoiter-fold, r=the8472
Fix `array::IntoIter::fold` to use the optimized `Range::fold`

It was using `Iterator::by_ref` in the implementation, which ended up pessimizing it enough that, for example, it didn't vectorize when we tried it in the <https://rust-lang.zulipchat.com/#narrow/stream/257879-project-portable-simd/topic/Reducing.20sum.20into.20wider.20types> conversation.

Demonstration that the codegen test doesn't pass on the current nightly: <https://rust.godbolt.org/z/Taxev5eMn>
2022-05-14 03:12:53 +00:00
Simon Sapin
7ccc09b210 Extend ptr::null and null_mut to all thin (including extern) types
Fixes https://github.com/rust-lang/rust/issues/93959

This change was accepted in https://rust-lang.github.io/rfcs/2580-ptr-meta.html

Note that this changes the signature of **stable** functions.
The change should be backward-compatible, but it is **insta-stable**
since it cannot (easily, at all?) be made available only
through a `#![feature(…)]` opt-in.

The RFC also proposed the same change for `NonNull::dangling`,
which makes sense it terms of its signature but not in terms of its implementation.
`dangling` uses `align_of()` as an address. But what `align_of()` should be for
extern types or whether it should be allowed at all remains an open question.

This commit depends on https://github.com/rust-lang/rust/pull/93977, which is not yet
part of the bootstrap compiler. So `#[cfg]` is used to only apply the change in
stage 1+. As far a I know bounds cannot be made conditional with `#[cfg]`, so the
entire functions are duplicated. This is unfortunate but temporary.

Since this duplication makes it less obvious in the diff,
the new definitions differ in:

* More permissive bounds (`Thin` instead of implied `Sized`)
* Different implementation
* Having `rustc_allow_const_fn_unstable(ptr_metadata)`
2022-05-13 18:03:06 +02:00
bors
8c4fc9d9a4 Auto merge of #94598 - scottmcm:prefix-free-hasher-methods, r=Amanieu
Add a dedicated length-prefixing method to `Hasher`

This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.

Fixes #94026

r? rust-lang/libs

---

The core of this change is the following two new methods on `Hasher`:

```rust
pub trait Hasher {
    /// Writes a length prefix into this hasher, as part of being prefix-free.
    ///
    /// If you're implementing [`Hash`] for a custom collection, call this before
    /// writing its contents to this `Hasher`.  That way
    /// `(collection![1, 2, 3], collection![4, 5])` and
    /// `(collection![1, 2], collection![3, 4, 5])` will provide different
    /// sequences of values to the `Hasher`
    ///
    /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
    /// hashing a slice (or array or vector) via its `Hash::hash` method,
    /// you should **not** call this yourself.
    ///
    /// This method is only for providing domain separation.  If you want to
    /// hash a `usize` that represents part of the *data*, then it's important
    /// that you pass it to [`Hasher::write_usize`] instead of to this method.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(hasher_prefixfree_extras)]
    /// # // Stubs to make the `impl` below pass the compiler
    /// # struct MyCollection<T>(Option<T>);
    /// # impl<T> MyCollection<T> {
    /// #     fn len(&self) -> usize { todo!() }
    /// # }
    /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
    /// #     type Item = T;
    /// #     type IntoIter = std::iter::Empty<T>;
    /// #     fn into_iter(self) -> Self::IntoIter { todo!() }
    /// # }
    ///
    /// use std:#️⃣:{Hash, Hasher};
    /// impl<T: Hash> Hash for MyCollection<T> {
    ///     fn hash<H: Hasher>(&self, state: &mut H) {
    ///         state.write_length_prefix(self.len());
    ///         for elt in self {
    ///             elt.hash(state);
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Note to Implementers
    ///
    /// If you've decided that your `Hasher` is willing to be susceptible to
    /// Hash-DoS attacks, then you might consider skipping hashing some or all
    /// of the `len` provided in the name of increased performance.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_length_prefix(&mut self, len: usize) {
        self.write_usize(len);
    }

    /// Writes a single `str` into this hasher.
    ///
    /// If you're implementing [`Hash`], you generally do not need to call this,
    /// as the `impl Hash for str` does, so you can just use that.
    ///
    /// This includes the domain separator for prefix-freedom, so you should
    /// **not** call `Self::write_length_prefix` before calling this.
    ///
    /// # Note to Implementers
    ///
    /// The default implementation of this method includes a call to
    /// [`Self::write_length_prefix`], so if your implementation of `Hasher`
    /// doesn't care about prefix-freedom and you've thus overridden
    /// that method to do nothing, there's no need to override this one.
    ///
    /// This method is available to be overridden separately from the others
    /// as `str` being UTF-8 means that it never contains `0xFF` bytes, which
    /// can be used to provide prefix-freedom cheaper than hashing a length.
    ///
    /// For example, if your `Hasher` works byte-by-byte (perhaps by accumulating
    /// them into a buffer), then you can hash the bytes of the `str` followed
    /// by a single `0xFF` byte.
    ///
    /// If your `Hasher` works in chunks, you can also do this by being careful
    /// about how you pad partial chunks.  If the chunks are padded with `0x00`
    /// bytes then just hashing an extra `0xFF` byte doesn't necessarily
    /// provide prefix-freedom, as `"ab"` and `"ab\u{0}"` would likely hash
    /// the same sequence of chunks.  But if you pad with `0xFF` bytes instead,
    /// ensuring at least one padding byte, then it can often provide
    /// prefix-freedom cheaper than hashing the length would.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_str(&mut self, s: &str) {
        self.write_length_prefix(s.len());
        self.write(s.as_bytes());
    }
}
```

With updates to the `Hash` implementations for slices and containers to call `write_length_prefix` instead of `write_usize`.

`write_str` defaults to using `write_length_prefix` since, as was pointed out in the issue, the `write_u8(0xFF)` approach is insufficient for hashers that work in chunks, as those would hash `"a\u{0}"` and `"a"` to the same thing.  But since `SipHash` works byte-wise (there's an internal buffer to accumulate bytes until a full chunk is available) it overrides `write_str` to continue to use the add-non-UTF-8-byte approach.

---

Compatibility:

Because the default implementation of `write_length_prefix` calls `write_usize`, the changed hash implementation for slices will do the same thing the old one did on existing `Hasher`s.
2022-05-06 09:43:57 +00:00
Scott McMurray
98054377ee Add a dedicated length-prefixing method to Hasher
This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.
2022-05-06 00:03:38 -07:00
Matthias Krüger
47801413d9
Rollup merge of #95359 - jhpratt:int_roundings, r=joshtriplett
Update `int_roundings` methods from feedback

This updates `#![feature(int_roundings)]` (#88581) from feedback. All methods now take `NonZeroX`. The documentation makes clear that they panic in debug mode and wrap in release mode.

r? `@joshtriplett`

`@rustbot` label +T-libs +T-libs-api +S-waiting-on-review
2022-05-05 15:43:00 +02:00
Jacob Pratt
dde590d180
Update int_roundings methods from feedback 2022-05-04 23:20:29 -04:00
Josh Triplett
0fc5c524f5 Stabilize bool::then_some 2022-05-04 13:22:08 +02:00
Dylan DPC
93db30aa7f
Rollup merge of #96149 - est31:remove_unused_macro_matchers, r=petrochenkov
Remove unused macro rules

Removes rules of internal macros that weren't triggered.
2022-04-26 01:21:20 +02:00
bors
d5ae66c12c Auto merge of #92287 - JulianKnodt:slice_remainder, r=yaahc
Add slice::remainder

This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.

Addresses #91733
2022-04-18 23:34:24 +00:00
est31
3c1e1661e7 Remove unused macro rules 2022-04-18 23:28:06 +02:00
est31
9e7a319f01 Replace u8to64_le macro with u64::from_le_bytes
The macro was a reimplementation of the function.
2022-04-17 22:55:33 +02:00
kadmin
494901ced6 Add slice::remainder
This adds a remainder function to the Slice iterator, so that a caller can access unused
elements if iteration stops.
2022-04-17 17:19:45 +00:00
bors
4e1927db3c Auto merge of #95399 - gilescope:plan_b, r=scottmcm
Faster parsing for lower numbers for radix up to 16 (cont.)

( Continuation of https://github.com/rust-lang/rust/pull/83371 )

With LingMan's change I think this is potentially ready.
2022-04-12 05:54:50 +00:00
Giles Cope
3ee7bb19c6
better def of is signed in tests. 2022-04-11 07:37:53 +01:00
liangyongrui
03b2588837 fix Layout struct member naming style 2022-04-11 13:35:18 +08:00
Giles Cope
515906a669
Use Add, Sub, Mul traits instead of unsafe 2022-04-10 18:13:48 +01:00
Dylan DPC
e4b4bf1535
Rollup merge of #95361 - scottmcm:valid-align, r=Mark-Simulacrum
Make non-power-of-two alignments a validity error in `Layout`

Inspired by the zulip conversation about how `Layout` should better enforce `size <= isize::MAX as usize`, this uses an N-variant enum on N-bit platforms to require at the validity level that the existing invariant of "must be a power of two" is upheld.

This was MIRI can catch it, and means there's a more-specific type for `Layout` to store than just `NonZeroUsize`.

It's left as `pub(crate)` here; a future PR could consider giving it a tracking issue for non-internal usage.
2022-04-09 18:26:25 +02:00
Scott McMurray
fe0c08a4f2 Make non-power-of-two alignments a validity error in Layout
Inspired by the zulip conversation about how `Layout` should better enforce `size < isize::MAX as usize`, this uses an N-variant enum on N-bit platforms to require at the validity level that the existing invariant of "must be a power of two" is upheld.

This was MIRI can catch it, and means there's a more-specific type for `Layout` to store than just `NonZeroUsize`.
2022-04-08 20:17:38 -07:00
Dylan DPC
d5232c6b93
Rollup merge of #95579 - Cyborus04:slice_flatten, r=scottmcm
Add `<[[T; N]]>::flatten{_mut}`

Adds `flatten` to convert `&[[T; N]]` to `&[T]` (and `flatten_mut` for `&mut [[T; N]]` to `&mut [T]`)
2022-04-08 11:48:21 +02:00
Cyborus04
06788fd7a4 add <[[T; N]]>::flatten, <[[T; N]]>::flatten_mut, and Vec::<[T; N]>::into_flattened 2022-04-08 00:54:39 -04:00
Giles Cope
82e9d9ebac
from_u32(0) can just be default() 2022-04-04 15:53:53 +01:00
Scott McMurray
83595f9242 Fix array::IntoIter::fold to use the optimized Range::fold
It was using `Iterator::by_ref` in the implementation, which ended up pessimizing it enough that, for example, it didn't vectorize when we tried it in the <https://rust-lang.zulipchat.com/#narrow/stream/257879-project-portable-simd/topic/Reducing.20sum.20into.20wider.20types> conversation.

Demonstration that the codegen test doesn't pass on the current nightly: <https://rust.godbolt.org/z/Taxev5eMn>
2022-04-02 14:29:41 -07:00
Dylan DPC
d6f6084b24
Rollup merge of #95556 - declanvk:nonnull-provenance, r=dtolnay
Implement provenance preserving methods on NonNull

### Description
 Add the `addr`, `with_addr`, `map_addr` methods to the `NonNull` type, and map the address type to `NonZeroUsize`.

 ### Motivation
 The `NonNull` type is useful for implementing pointer types which have  the 0-niche. It is currently possible to implement these provenance  preserving functions by calling `NonNull::as_ptr` and `new_unchecked`. The adding these methods makes it more ergonomic.

 ### Testing
 Added a unit test of a non-null tagged pointer type. This is based on some real code I have elsewhere, that currently routes the pointer through a `NonZeroUsize` and back out to produce a usable pointer. I wanted to produce an ideal version of the same tagged pointer struct that preserved pointer provenance.

### Related

Extension of APIs proposed in #95228 . I can also split this out into a separate tracking issue if that is better (though I may need some pointers on how to do that).
2022-04-02 03:34:24 +02:00
Dylan DPC
d7a24003d8
Rollup merge of #95354 - dtolnay:rustc_const_stable, r=lcnr
Handle rustc_const_stable attribute in library feature collector

The library feature collector in [compiler/rustc_passes/src/lib_features.rs](551b4fa395/compiler/rustc_passes/src/lib_features.rs) has only been looking at `#[stable(…)]`, `#[unstable(…)]`, and `#[rustc_const_unstable(…)]` attributes, while ignoring `#[rustc_const_stable(…)]`. The consequences of this were:

- When any const feature got stabilized (changing one or more `rustc_const_unstable` to `rustc_const_stable`), users who had previously enabled that unstable feature using `#![feature(…)]` would get told "unknown feature", rather than rustc's nicer "the feature … has been stable since … and no longer requires an attribute to enable".

    This can be seen in the way that https://github.com/rust-lang/rust/pull/93957#issuecomment-1079794660 failed after rebase:

    ```console
    error[E0635]: unknown feature `const_ptr_offset`
      --> $DIR/offset_from_ub.rs:1:35
       |
    LL | #![feature(const_ptr_offset_from, const_ptr_offset)]
       |                                   ^^^^^^^^^^^^^^^^
    ```

- We weren't enforcing that a particular feature is either stable everywhere or unstable everywhere, and that a feature that has been stabilized has the same stabilization version everywhere, both of which we enforce for the other stability attributes.

This PR updates the library feature collector to handle `rustc_const_stable`, and fixes places in the standard library and test suite where `rustc_const_stable` was being used in a way that does not meet the rules for a stability attribute.
2022-04-02 03:34:21 +02:00
Matthias Krüger
c37aeb0299
Rollup merge of #95528 - RalfJung:miri-is-too-slow, r=scottmcm
skip slow int_log tests in Miri

Iterating over i16::MAX many things takes a long time in Miri, let's not do that.
I added https://github.com/rust-lang/miri/pull/2044 on the Miri side to still give us some test coverage.
2022-04-01 12:07:03 +02:00
Declan Kelly
2a827635ba Implement provenance preserving method on NonNull
**Description**
 Add the `addr`, `with_addr, `map_addr` methods to the `NonNull` type,
 and map the address type to `NonZeroUsize`.

 **Motiviation**
 The `NonNull` type is useful for implementing pointer types which have
 the 0-niche. It is currently possible to implement these provenance
 preserving functions by calling `NonNull::as_ptr` and `new_unchecked`.
 The addition of these methods simply make it more ergonomic to use.

 **Testing**
 Added a unit test of a nonnull tagged pointer type. This is based on
 some real code I have elsewhere, that currently routes the pointer
 through a `NonZeroUsize` and back out to produce a usable pointer.
2022-04-01 00:23:09 -07:00
David Tolnay
4246916619
Adjust feature names that disagree on const stabilization version 2022-03-31 12:34:48 -07:00
Ralf Jung
487bd8184f skip slow int_log tests in Miri 2022-03-31 11:48:51 -04:00
Ralf Jung
907ba11490 ptr_metadata test: avoid ptr-to-int transmutes 2022-03-31 09:32:30 -04:00
David Tolnay
2ac9efbe95
Debug print char 0 as '\0' rather than '\u{0}' 2022-03-27 04:49:10 -07:00
Jendrik
5f88c23c39 add #[must_use] to functions of slice and its iterators. 2022-03-26 10:24:25 +01:00
bjorn3
4af755baf5 Limit test_variadic_fnptr to unix 2022-03-22 22:27:13 +01:00
bjorn3
56939ffe7d Don't declare test_variadic_fnptr with two conflicting signatures
It is UB for LLVM and results in a compile error for Cranelift
2022-03-20 21:09:35 +01:00
Matthias Krüger
4ead6d9dc7
Rollup merge of #95017 - zachs18:cmp_ordering_derive_eq, r=Dylan-DPC
Derive Eq for std::cmp::Ordering, instead of using manual impl.

This allows consts of type Ordering to be used in patterns, and with feature(adt_const_params) allows using `Ordering` as a const generic parameter.

Currently, `std::cmp::Ordering` implements `Eq` using a manually written `impl Eq for Ordering {}`, instead of `derive(Eq)`. This means that it does not implement `StructuralEq`.

This commit removes the manually written impl, and adds `derive(Eq)` to `Ordering`, so that it will implement `StructuralEq`.
2022-03-18 21:50:48 +01:00
Matthias Krüger
c183d4a510
Rollup merge of #94115 - scottmcm:iter-process-by-ref, r=yaahc
Let `try_collect` take advantage of `try_fold` overrides

No public API changes.

With this change, `try_collect` (#94047) is no longer going through the `impl Iterator for &mut impl Iterator`, and thus will be able to use `try_fold` overrides instead of being forced through `next` for every element.

Here's the test added, to see that it fails before this PR (once a new enough nightly is out): https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=462f2896f2fed2c238ee63ca1a7e7c56

This might as well go to the same person as my last `try_process` PR  (#93572), so
r? ``@yaahc``
2022-03-18 21:50:44 +01:00
Zachary S
b13b495b91 Add test for StructuralEq for std::cmp::Ordering.
Added test in library/core/tests/cmp.rs that ensures that `const`s of type `Ordering`s can be used in patterns.
2022-03-16 14:01:48 -05:00
bors
21b0325c68 Auto merge of #94738 - Urgau:rustbuild-check-cfg-values, r=Mark-Simulacrum
Enable conditional checking of values in the Rust codebase

This pull-request enable conditional checking of (well known) values in the Rust codebase.

Well known values were added in https://github.com/rust-lang/rust/pull/94362. All the `target_*` values are taken from all the built-in targets which is why some extra values were needed do be added as they are not (yet ?) defined in any built-in targets.

r? `@Mark-Simulacrum`
2022-03-13 18:34:00 +00:00
T-O-R-U-S
72a25d05bf Use implicit capture syntax in format_args
This updates the standard library's documentation to use the new syntax. The
documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).
2022-03-10 10:23:40 -05:00
Scott McMurray
7ef74bc8b9 Let try_collect take advantage of try_fold overrides
Without this change it's going through `&mut impl Iterator`, which handles `?Sized` and thus currently can't forward generics.

Here's the test added, to see that it fails before this PR (once a new enough nightly is out): https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=462f2896f2fed2c238ee63ca1a7e7c56
2022-03-10 00:16:06 -08:00
Matthias Krüger
d5c05fcc8a
Rollup merge of #93057 - frengor:iter_collect_into, r=m-ou-se
Add Iterator::collect_into

This PR adds `Iterator::collect_into` as proposed by ``@cormacrelf`` in #48597 (see https://github.com/rust-lang/rust/pull/48597#issuecomment-842083688).
Followup of #92982.

This adds the following method to the Iterator trait:

```rust
fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
```
2022-03-09 23:14:11 +01:00
Loïc BRANSTETT
e3ea59ada5 Remove unexpected #[cfg(target_pointer_width = "8")] in tests 2022-03-09 00:30:17 +01:00
Ralf Jung
e9149b6773 Miri can run this test now 2022-03-03 14:54:18 -05:00
Ralf Jung
d233570fab fix a warning when building core tests with cfg(miri) 2022-03-03 14:54:18 -05:00
Ralf Jung
6739299d18 Miri/CTFE: properly treat overflow in (signed) division/rem as UB 2022-03-01 20:39:51 -05:00
Matthias Krüger
770ee32b34
Rollup merge of #89793 - ibraheemdev:from_ptr_range, r=m-ou-se
Add `slice::{from_ptr_range, from_mut_ptr_range} `

Adds `slice::{from_ptr_range, from_mut_ptr_range}` as counterparts to `slice::{as_ptr_range, as_mut_ptr_range}`.
2022-02-28 12:57:44 +01:00
Ibraheem Ahmed
aac0281d30 add slice::{from_ptr_range, from_mut_ptr_range} 2022-02-27 16:53:26 -05:00
Mark Rousskov
22c3a71de1 Switch bootstrap cfgs 2022-02-25 08:00:52 -05:00
fren_gor
04b3162764
Add collect_into 2022-02-20 01:57:32 +01:00
Matthias Krüger
f19adc7acc
Rollup merge of #93658 - cchiw:issue-77443-fix, r=joshtriplett
Stabilize `#[cfg(panic = "...")]`

[Stabilization PR](https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr) for #77443
2022-02-19 06:45:29 +01:00
Arthur Lafrance
47d5196a00 Add a try_collect() helper method to Iterator
Tweaked `try_collect()` to accept more `Try` types

Updated feature attribute for tracking issue
2022-02-16 14:26:39 -08:00
Daniel Henry-Mantilla
42d69e2793 Write {ui,} tests for pin_macro and pin! 2022-02-14 16:56:37 +01:00
SaltyKitkat
3c142b0ffe
stabilize const_ptr_offset 2022-02-13 15:26:14 +08:00
Charisee
dbeab9c532 added space 2022-02-10 22:30:51 +00:00
Charisee
a889079b29 add cfg_panic bootstrap 2022-02-10 22:10:08 +00:00
Charisee
d018a8b624 remove mention of cfg_panic from library tests 2022-02-10 22:09:11 +00:00
Charisee
5e6be7df94 replace feature expression (cfg_panic) in lib and remove expression from tests
Rebase commit
2022-02-10 22:06:47 +00:00
Amanieu d'Antras
49d4823112 Stabilize cfg_target_has_atomic
Closes #32976
2022-02-09 18:45:44 +00:00
tamaron
83242897fb add tests 2022-02-02 23:07:02 +09:00
Matthias Krüger
a643e59800
Rollup merge of #91828 - oxalica:feat/waker-getters, r=dtolnay
Implement `RawWaker` and `Waker` getters for underlying pointers

implement #87021

New APIs:
- `RawWaker::data(&self) -> *const ()`
- `RawWaker::vtable(&self) -> &'static RawWakerVTable`
- ~`Waker::as_raw_waker(&self) -> &RawWaker`~ `Waker::as_raw(&self) -> &RawWaker`

This third one is an auxiliary function to make the two APIs above more useful. Since we can only get `&Waker` in `Future::poll`, without this, we need to `transmute` it into `&RawWaker` (relying on `repr(transparent)`) in order to access its data/vtable pointers.

~Not sure if it should be named `as_raw` or `as_raw_waker`. Seems we always use `as_<something-raw>` instead of just `as_raw`. But `as_raw_waker` seems not quite consistent with `Waker::from_raw`.~ As suggested in https://github.com/rust-lang/rust/pull/91828#discussion_r770729837, use `as_raw`.
2022-02-01 16:08:02 +01:00
bors
547f2ba06b Auto merge of #86988 - thomcc:chunky-splitz-says-no-checking, r=the8472
Carefully remove bounds checks from some chunk iterator functions

So, I was writing code that requires the equivalent of `rchunks(N).rev()` (which isn't the same as forward `chunks(N)` — in particular, if the buffer length is not a multiple of `N`, I must handle the "remainder" first).

I happened to look at the codegen output of the function (I was actually interested in whether or not a nested loop was being unrolled — it was), and noticed that in the outer `rchunks(n).rev()` loop, LLVM seemed to be unable to remove the bounds checks from the iteration: https://rust.godbolt.org/z/Tnz4MYY8f (this panic was from the split_at in `RChunks::next_back`).

After doing some experimentation, it seems all of the `next_back` in the non-exact chunk iterators have the issue: (`Chunks::next_back`, `RChunks::next_back`, `ChunksMut::next_back`, and `RChunksMut::next_back`)...

Even worse, the forward `rchunks` iterators sometimes have the issue as well (... but only sometimes). For example https://rust.godbolt.org/z/oGhbqv53r has bounds checks, but if I uncomment the loop body, it manages to remove the check (which is bizarre, since I'd expect the opposite...). I suspect it's highly dependent on the surrounding code, so I decided to remove the bounds checks from them anyway. Overall, this change includes:
- All `next_back` functions on the non-`Exact` iterators (e.g. `R?Chunks(Mut)?`).
- All `next` functions on the non-exact rchunks iterators (e.g. `RChunks(Mut)?`).

I wasn't able to catch any of the other chunk iterators failing to remove the bounds checks (I checked iterations over `r?chunks(_exact)?(_mut)?` with constant chunk sizes under `-O3`, `-Os`, and `-Oz`), which makes sense, since these were the cases where it was harder to prove the bounds check correct to remove...

In fact, it took quite a bit of thinking to convince myself that using unchecked_ here was valid — so I'm not really surprised that LLVM had trouble (although compilers are slightly better at this sort of reasoning than humans). A consequence of that is the fact that the `// SAFETY` comment for these are... kinda long...

---

I didn't do this for, or even think about it for, any of the other iteration methods; just `next` and `next_back` (where it mattered). If this PR is accepted, I'll file a follow up for someone (possibly me) to look at the others later (in particular, `nth`/`nth_back` looked like they had similar logic), but I wanted to do this now, as IMO `next`/`next_back` are the most important here, since they're what gets used by the iteration protocol.

---

Note: While I don't expect this to impact performance directly, the panic is a side effect, which would otherwise not exist in these loops. That is, this could prevent the compiler from being able to move/remove/otherwise rework a loop over these iterators (as an example, it could not delete the code for a loop whose body computes a value which doesn't get used).

Also, some like to be able to have confidence this code has no panicking branches in the optimized code, and "no bounds checks" is kinda part of the selling point of Rust's iterators anyway.
2022-02-01 10:11:59 +00:00
Thom Chiovoloni
9c62455e2f
Improve test coverage of {Chunks,RChunks,RChunksMut}::{next,next_back} 2022-01-31 17:35:19 -08:00
bors
86f5e177bc Auto merge of #93498 - matthiaskrgr:rollup-k5shwrc, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #90277 (Improve terminology around "after typeck")
 - #92918 (Allow eliding GATs in expression position)
 - #93039 (Don't suggest inaccessible fields)
 - #93155 (Switch pretty printer to block-based indentation)
 - #93214 (Respect doc(hidden) when suggesting available fields)
 - #93347 (Make `char::DecodeUtf16::size_hist` more precise)
 - #93392 (Clarify documentation on char::MAX)
 - #93444 (Fix some CSS warnings and errors from VS Code)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-01-31 11:24:03 +00:00
Matthias Krüger
b0cdf7e995
Rollup merge of #93480 - est31:remove_unstable_deprecated, r=Mark-Simulacrum
Remove deprecated and unstable slice_partition_at_index functions

They have been deprecated since commit 01ac5a97c9
which was part of the 1.49.0 release, so from the point of nightly,
11 releases ago.
2022-01-31 07:00:45 +01:00
Matthias Krüger
76857fb3fb
Rollup merge of #93347 - WaffleLapkin:better_char_decode_utf16_size_hint, r=dtolnay
Make `char::DecodeUtf16::size_hist` more precise

New implementation takes into account contents of `self.buf` and rounds lower bound up instead of down.

Fixes #88762
Revival of #88763
2022-01-31 06:58:31 +01:00
Eric Huss
0610d4fa66
Rollup merge of #92887 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bootstrap compiler update

r? ``@Mark-Simulacrum``
2022-01-30 08:37:46 -08:00
est31
105a7461b9 Remove deprecated and unstable slice_partition_at_index functions
They have been deprecated since commit 01ac5a97c9
which was part of the 1.49.0 release, so from the point of nightly,
11 releases ago.
2022-01-30 16:19:03 +01:00
Maybe Waffle
17cd2cd592 Fix an edge case in chat::DecodeUtf16::size_hint
There are cases, when data in the buf might or might not be an error.
2022-01-30 15:32:21 +03:00
Matthias Krüger
37e9cb34e5
Rollup merge of #93236 - woppopo:const_nonnull_new, r=oli-obk
Make `NonNull::new` `const`

Tracking issue: #93235
2022-01-29 14:46:31 +01:00
Matthias Krüger
9e86a434a7
Rollup merge of #92274 - woppopo:const_deallocate, r=oli-obk
Add `intrinsics::const_deallocate`

Tracking issue: #79597
Related: #91884

This allows deallocation of a memory allocated by `intrinsics::const_allocate`. At the moment, this can be only used to reduce memory usage, but in the future this may be useful to detect memory leaks (If an allocated memory remains after evaluation, raise an error...?).
2022-01-29 14:46:30 +01:00
Pietro Albini
5b3462c556
update cfg(bootstrap)s 2022-01-28 15:01:07 +01:00
woppopo
cdd0873db6 Add a test case for using NonNull::new in const context 2022-01-28 18:41:35 +09:00
Maybe Waffle
2c97d1012e Fix wrong assumption in DecodeUtf16::size_hint
`self.buf` can contain a surrogate, but only a leading one.
2022-01-28 12:40:59 +03:00
woppopo
7a7144f413 test_const_allocate_at_runtime 2022-01-28 17:27:33 +09:00
Maybe Waffle
9c8cd1ff37 Add a test for char::DecodeUtf16::size_hint 2022-01-27 00:50:34 +03:00
woppopo
29932db09b const_deallocate: Don't deallocate memory allocated in an another const. Does nothing at runtime.
`const_allocate`:  Returns a null pointer at runtime.
2022-01-26 13:06:09 +09:00
Matthias Krüger
55a1f8b955
Rollup merge of #91122 - dtolnay:not, r=m-ou-se
impl Not for !

The lack of this impl caused trouble for me in some degenerate cases of macro-generated code of the form `if !$cond {...}`, even without `feature(never_type)` on a stable compiler. Namely if `$cond` contains a `return` or `break` or similar diverging expression, which would otherwise be perfectly legal in boolean position, the code previously failed to compile with:

```console
error[E0600]: cannot apply unary operator `!` to type `!`
   --> library/core/tests/ops.rs:239:8
    |
239 |     if !return () {}
    |        ^^^^^^^^^^ cannot apply unary operator `!`
```
2022-01-23 01:09:41 +01:00
Matthias Krüger
f511360fd2
Rollup merge of #92747 - swenson:bignum-bit-length-optimization, r=scottmcm
Simplification of BigNum::bit_length

As indicated in the comment, the BigNum::bit_length function could be
optimized by using CLZ, which is often a single instruction instead a
loop.

I think the code is also simpler now without the loop.

I added some additional tests for Big8x3 and Big32x40 to ensure that
there were no regressions.
2022-01-15 11:28:22 +01:00
Matthias Krüger
558da934c1
Rollup merge of #92768 - ojeda:stabilize-maybe_uninit_extra, r=Mark-Simulacrum
Partially stabilize `maybe_uninit_extra`

This covers:

```rust
impl<T> MaybeUninit<T> {
    pub unsafe fn assume_init_read(&self) -> T { ... }
    pub unsafe fn assume_init_drop(&mut self) { ... }
}
```

It does not cover the const-ness of `write` under `const_maybe_uninit_write` nor the const-ness of `assume_init_read` (this commit adds `const_maybe_uninit_assume_init_read` for that).

FCP: https://github.com/rust-lang/rust/issues/63567#issuecomment-958590287.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-01-14 07:47:33 +01:00
Miguel Ojeda
8680a44c0f Partially stabilize maybe_uninit_extra
This covers:

    impl<T> MaybeUninit<T> {
        pub unsafe fn assume_init_read(&self) -> T { ... }
        pub unsafe fn assume_init_drop(&mut self) { ... }
    }

It does not cover the const-ness of `write` under
`const_maybe_uninit_write` nor the const-ness of
`assume_init_read` (this commit adds
`const_maybe_uninit_assume_init_read` for that).

FCP: https://github.com/rust-lang/rust/issues/63567#issuecomment-958590287.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-01-11 17:01:13 +01:00
Christopher Swenson
424f38f211 Simplification of BigNum::bit_length
As indicated in the comment, the BigNum::bit_length function could be
optimized by using CLZ, which is often a single instruction instead a
loop.

I think the code is also simpler now without the loop.

I added some additional tests for Big8x3 and Big32x40 to ensure that
there were no regressions.
2022-01-10 14:18:28 -08:00
Lucas Kent
08829853d3 eplace usages of vec![].into_iter with [].into_iter 2022-01-09 14:09:25 +11:00
bors
fca4b155a7 Auto merge of #92226 - woppopo:const_black_box, r=joshtriplett
Constify `core::intrinsics::black_box` and `core::hint::black_box`.

`core::intrinsics::black_box` is already constified, but it wasn't marked as const (see: https://github.com/rust-lang/rust/blob/master/compiler/rustc_const_eval/src/interpret/intrinsics.rs#L471).

Tracking issue: None
2021-12-24 10:02:54 +00:00
Matthias Krüger
94b9b5f35f
Rollup merge of #92121 - RalfJung:miri-core-test, r=kennytm
disable test with self-referential generator on Miri

Running the libcore test suite in Miri currently fails due to the known incompatibility of self-referential generators with Miri's aliasing checks (https://github.com/rust-lang/unsafe-code-guidelines/issues/148). So let's disable that test in Miri for now.
2021-12-23 17:48:30 +01:00
woppopo
72f15ea22a Constify core::intrinsics::black_box 2021-12-23 20:07:41 +09:00
Matthias Krüger
60625a6ef0
Rollup merge of #88858 - spektom:to_lower_upper_rev, r=dtolnay
Allow reverse iteration of lowercase'd/uppercase'd chars

The PR implements `DoubleEndedIterator` trait for `ToLowercase` and `ToUppercase`.

This enables reverse iteration of lowercase/uppercase variants of character sequences.
One of use cases:  determining whether a char sequence is a suffix of another one.

Example:

```rust
fn endswith_ignore_case(s1: &str, s2: &str) -> bool {
    for eob in s1
        .chars()
        .flat_map(|c| c.to_lowercase())
        .rev()
        .zip_longest(s2.chars().flat_map(|c| c.to_lowercase()).rev())
    {
        match eob {
            EitherOrBoth::Both(c1, c2) => {
                if c1 != c2 {
                    return false;
                }
            }
            EitherOrBoth::Left(_) => return true,
            EitherOrBoth::Right(_) => return false,
        }
    }
    true
}
```
2021-12-23 00:28:51 +01:00
Ralf Jung
5994990088 disable test with self-referential generator on Miri 2021-12-20 12:33:55 +01:00
Matthias Krüger
6d2689526b
Rollup merge of #91141 - jhpratt:int_roundings, r=joshtriplett
Revert "Temporarily rename int_roundings functions to avoid conflicts"

This reverts commit 3ece63b64e.

This should be okay because #90329 has been merged.

r? `@joshtriplett`
2021-12-19 10:45:50 +01:00
bors
d3f300477b Auto merge of #92062 - matthiaskrgr:rollup-en3p4sb, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #91439 (Mark defaulted `PartialEq`/`PartialOrd` methods as const)
 - #91516 (Improve suggestion to change struct field to &mut)
 - #91896 (Remove `in_band_lifetimes` for `rustc_passes`)
 - #91909 (⬆️ rust-analyzer)
 - #91922 (Remove `in_band_lifetimes` from `rustc_mir_dataflow`)
 - #92025 (Revert "socket ancillary data implementation for dragonflybsd.")
 - #92030 (Update stdlib to the 2021 edition)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-12-18 10:20:24 +00:00
Matthias Krüger
359c88e426
Rollup merge of #91439 - ecstatic-morse:const-cmp-trait-default-methods, r=oli-obk
Mark defaulted `PartialEq`/`PartialOrd` methods as const

WIthout it, `const` impls of these traits are unpleasant to write. I think this kind of change is allowed now. although it looks like it might require some Miri tweaks. Let's find out.

r? ```@fee1-dead```
2021-12-18 10:26:35 +01:00
Matthias Krüger
fcc59794a7
Rollup merge of #91928 - fee1-dead:constification1, r=oli-obk
Constify (most) `Option` methods

r? ``@oli-obk``
2021-12-18 08:16:29 +01:00
bors
7abab1efb2 Auto merge of #91838 - scottmcm:array-slice-eq-via-arrays-not-slices, r=dtolnay
Do array-slice equality via array equality, rather than always via slices

~~Draft because it needs a rebase after #91766 eventually gets through bors.~~

This enables the optimizations from #85828 to be used for array-to-slice comparisons too, not just array-to-array.

For example, <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=5f9ba69b3d5825a782f897c830d3a6aa>
```rust
pub fn demo(x: &[u8], y: [u8; 4]) -> bool {
    *x == y
}
```
Currently writes the array to stack for no reason:
```nasm
	sub	rsp, 4
	mov	dword ptr [rsp], edx
	cmp	rsi, 4
	jne	.LBB0_1
	mov	eax, dword ptr [rdi]
	cmp	eax, dword ptr [rsp]
	sete	al
	add	rsp, 4
	ret

.LBB0_1:
	xor	eax, eax
	add	rsp, 4
	ret
```
Whereas with the change in this PR it just compares it directly:
```nasm
	cmp	rsi, 4
	jne	.LBB1_1
	cmp	dword ptr [rdi], edx
	sete	al
	ret

.LBB1_1:
	xor	eax, eax
	ret
```
2021-12-17 19:17:29 +00:00
Deadbeef
6b5f63c3fc
Constify (most) Option methods 2021-12-17 20:46:47 +08:00
Dylan MacKenzie
2049287030 Disable test on bootstrap compiler 2021-12-16 22:11:17 -08:00
Dylan MacKenzie
1606335a93 Test const impl of cmp traits 2021-12-16 21:35:25 -08:00
oxalica
bae0da8361
Implement data and vtable getters for RawWaker 2021-12-17 04:30:13 +08:00
Matthias Krüger
13fb051074
Rollup merge of #91918 - fee1-dead:constification0-the-great-constification-begins, r=oli-obk
Constify `bool::then{,_some}`

Note on `~const Drop`: it has no effect when called from runtime functions, when called from const contexts, the trait system ensures that the type can be dropped in const contexts.
2021-12-15 10:57:03 +01:00
Scott McMurray
a0b96902e4 Do array-slice equality via arrays, rather than always via slices
This'll still go via slices eventually for large arrays, but this way slice comparisons to short arrays can use the same memcmp-avoidance tricks.

Added some tests for all the combinations to make sure I didn't accidentally infinitely-recurse something.
2021-12-14 13:15:15 -08:00
Deadbeef
4f4b2c7271
Constify bool::then{,_some} 2021-12-15 00:11:23 +08:00
Frank Steffahn
a957cefda6 Fix a bunch of typos 2021-12-14 16:40:43 +01:00
bors
f7fd79ac1d Auto merge of #91841 - matthiaskrgr:rollup-zlhsg5a, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #91086 (Implement `TryFrom<&'_ mut [T]>` for `[T; N]`)
 - #91091 (Stabilize `ControlFlow::{is_break, is_continue}`)
 - #91749 (BTree: improve public descriptions and comments)
 - #91819 (rustbot: Add autolabeling for `T-compiler`)
 - #91824 (Make `(*mut T)::write_bytes` `const`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-12-13 00:56:18 +00:00
Matthias Krüger
9e662d0c03
Rollup merge of #91824 - woppopo:const_ptr_write_bytes, r=oli-obk
Make `(*mut T)::write_bytes` `const`

Tracking issue: #86302
2021-12-13 00:20:10 +01:00