Commit graph

5691 commits

Author SHA1 Message Date
nyanpasu64
6b90c0f1b4 Fix copy-paste error in String::as_mut_vec() docs 2021-10-25 23:22:57 -07:00
Matthias Krüger
14931b94a2
Rollup merge of #90196 - yanok:master, r=scottmcm
Fix and extent ControlFlow `traverse_inorder` example

Fix and extent ControlFlow `traverse_inorder` example

1. The existing example compiles on its own, but any usage fails to be monomorphised and so doesn't compile. Fix that by using Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.

Fixes #90063
2021-10-25 22:59:47 +02:00
bors
84c2a8505d Auto merge of #90265 - GuillaumeGomez:rollup-gx3ficp, r=GuillaumeGomez
Rollup of 5 pull requests

Successful merges:

 - #90017 (Add a couple tests for normalize under binder issues)
 - #90079 (enable `i8mm` target feature on aarch64 and arm)
 - #90233 (Tooltip overflow)
 - #90257 (Changed slice.swap documentation for better readability)
 - #90261 (Move back to linux builder on try builds)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-10-25 14:40:45 +00:00
Tommaso Fontana
9b28ab40ac
Fixed missing double quote in the patch (slice.swap) 2021-10-25 14:13:54 +02:00
Tommaso Fontana
32a3edb153
Changed slice.swap documentation for better readability
using "b" and "d" can be easily confused
2021-10-25 13:51:34 +02:00
bors
235d9853d8 Auto merge of #90042 - pietroalbini:1.56-master, r=Mark-Simulacrum
Bump bootstrap compiler to 1.57

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

r? `@Mark-Simulacrum`
2021-10-25 11:31:47 +00:00
Ilya Yanok
f3795e27c1 Fix and extend ControlFlow traverse_inorder example
1. The existing example compiles on its own, but any usage fails
   to be monomorphised and so doesn't compile. Fix that by using
   a mutable reference as an input argument.
2. Added an example usage of `traverse_inorder` showing how we
   can terminate the traversal early.

Fixes #90063
2021-10-24 20:12:22 +02:00
Matthias Krüger
c16ee19dd4
Rollup merge of #90162 - WaffleLapkin:const_array_slice_from_ref_mut, r=oli-obk
Mark `{array, slice}::{from_ref, from_mut}` as const fn

This PR marks the following APIs as `const`:
```rust
// core::array
pub const fn from_ref<T>(s: &T) -> &[T; 1];
pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1];

// core::slice
pub const fn from_ref<T>(s: &T) -> &[T];
pub const fn from_mut<T>(s: &mut T) -> &mut [T];
```

Note that `from_ref` methods require `const_raw_ptr_deref` feature (which seems totally fine, since it's being stabilized, see #89551), `from_mut` methods require `const_mut_refs` (which seems fine too since this PR marks `from_mut` functions as const unstable).

r? ````@oli-obk````
2021-10-24 15:48:44 +02:00
Matthias Krüger
87822b27ee
Rollup merge of #89558 - lcnr:query-stable-lint, r=estebank
Add rustc lint, warning when iterating over hashmaps

r? rust-lang/wg-incr-comp
2021-10-24 15:48:42 +02:00
Pietro Albini
b63ab8005a update cfg(bootstrap) 2021-10-23 21:55:57 -04:00
Maybe Waffle
5f390cfb72 Add tests for const_slice_from_ref and const_array_from_ref 2021-10-23 22:51:22 +03:00
Maybe Waffle
27d6961134 Fill tracking issue for const_slice_from_ref and const_array_from_ref 2021-10-23 20:59:15 +03:00
The8472
fd25491807 Add caveat about changing parallelism and function call overhead 2021-10-23 13:01:07 +02:00
Ilya Yanok
508fadab16 Update control_flow.rs
Fix and extent ControlFlow `traverse_inorder` example

1. The existing example compiles on its own, but any usage fails to be monomorphised and so doesn't compile. Fix that by using Fn trait instead of FnMut.
2. Added an example usage of `traverse_inorder` showing how we can terminate the traversal early.

Fixes #90063
2021-10-23 11:40:46 +02:00
Matthias Krüger
a05a1294d0
Rollup merge of #90166 - smmalis37:patch-1, r=joshtriplett
Add comment documenting why we can't use a simpler solution

See #90144 for context.

r? ```@joshtriplett```
2021-10-23 05:28:28 +02:00
Matthias Krüger
270c800d35
Rollup merge of #90117 - calebsander:fix/rsplit-clone, r=yaahc
Make RSplit<T, P>: Clone not require T: Clone

This addresses a TODO comment. The behavior of `#[derive(Clone)]` *does* result in a `T: Clone` requirement. Playground example:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a8b1a9581ff8893baf401d624a53d35b

Add a manual `Clone` implementation, mirroring `Split` and `SplitInclusive`.
`(R)?SplitN(Mut)?` don't have any `Clone` implementations, but I'll leave that for its own pull request.
2021-10-23 05:28:26 +02:00
Matthias Krüger
df430624b6
Rollup merge of #88300 - ijackson:exitstatusext-methods, r=yaahc
Stabilise unix_process_wait_more, extra ExitStatusExt methods

This stabilises the feature `unix_process_wait_more`.  Tracking issue #80695, FCP needed.

This was implemented in #79982 and merged in January.
2021-10-23 05:28:20 +02:00
Matthias Krüger
5ea0274563
Rollup merge of #83233 - jethrogb:split_array, r=yaahc
Implement split_array and split_array_mut

This implements `[T]::split_array::<const N>() -> (&[T; N], &[T])` and `[T; N]::split_array::<const M>() -> (&[T; M], &[T])` and their mutable equivalents. These are another few “missing” array implementations now that const generics are a thing, similar to #74373, #75026, etc. Fixes #74674.

This implements `[T; N]::split_array` returning an array and a slice. Ultimately, this is probably not what we want, we would want the second return value to be an array of length N-M, which will likely be possible with future const generics enhancements. We need to implement the array method now though, to immediately shadow the slice method. This way, when the slice methods get stabilized, calling them on an array will not be automatic through coercion, so we won't have trouble stabilizing the array methods later (cf. into_iter debacle).

An unchecked version of `[T]::split_array` could also be added as in #76014. This would not be needed for `[T; N]::split_array` as that can be compile-time checked. Edit: actually, since split_at_unchecked is internal-only it could be changed to be split_array-only.
2021-10-23 05:28:19 +02:00
bors
514b387795 Auto merge of #90007 - xfix:inline-cstr-from-str, r=kennytm
Inline CStr::from_ptr

Inlining this function is valuable, as it allows LLVM to apply `strlen`-specific optimizations without having to enable LTO.

For instance, the following function:

```rust
pub fn f(p: *const c_char) -> Option<u8> {
    unsafe { CStr::from_ptr(p) }.to_bytes().get(0).copied()
}
```

Looks like this if `CStr::from_ptr` is allowed to be inlined.

```asm
before:
        push    rax
        call    qword ptr [rip + std::ffi::c_str::CStr::from_ptr@GOTPCREL]
        mov     rcx, rax
        cmp     rdx, 1
        sete    dl
        test    rax, rax
        sete    al
        or      al, dl
        jne     .LBB1_2
        mov     dl, byte ptr [rcx]
.LBB1_2:
        xor     al, 1
        pop     rcx
        ret

after:
        mov     dl, byte ptr [rdi]
        test    dl, dl
        setne   al
        ret
```

Note that optimization turned this from O(N) to O(1) in terms of performance, as LLVM knows that it doesn't really need to call `strlen` to determine whether a string is empty or not.
2021-10-22 21:01:59 +00:00
Jane Lusby
2ed566559b
Apply suggestions from code review 2021-10-22 10:47:34 -07:00
Steven
c736c2a3ae
Add comment documenting why we can't use a simpler solution
See #90144 for context.

r? @joshtriplett
2021-10-22 09:55:32 -04:00
Maybe Waffle
a288bf6afb Mark {array,slice}::{from_ref,from_mut} as const fn 2021-10-22 14:53:30 +03:00
Yuki Okushi
8b7adf63e1
Rollup merge of #89944 - mbartlett21:patch-2, r=Mark-Simulacrum
Change `Duration::[try_]from_secs_{f32, f64}` underflow error

The error message now says that it was a negative value.

Fixes #89913.
2021-10-22 19:42:47 +09:00
Yuki Okushi
62da4ab161
Rollup merge of #89665 - seanyoung:push-empty, r=m-ou-se
Ensure that pushing empty path works as before on verbatim paths

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

Signed-off-by: Sean Young <sean@mess.org>
2021-10-22 19:42:43 +09:00
Yuki Okushi
918f9cc88b
Rollup merge of #88624 - kellerkindt:master, r=JohnTitor
Stabilize feature `saturating_div` for rust 1.58.0

The tracking issue is #89381

This seems like a reasonable simple change(?). The feature `saturating_div` was added as part of the ongoing effort to implement a `Saturating` integer type (see #87921). The implementation has been discussed [here](https://github.com/rust-lang/rust/pull/87921#issuecomment-899357720) and [here](https://github.com/rust-lang/rust/pull/87921#discussion_r691888556). It extends the list of saturating operations on integer types (like `saturating_add`, `saturating_sub`, `saturating_mul`, ...) by the function `fn saturating_div(self, rhs: Self) -> Self`.

The stabilization of the feature `saturating_int_impl` (for the `Saturating` type) needs to have this stabilized first.

Closes #89381
2021-10-22 19:42:42 +09:00
Jethro Beekman
4a439769ec Implement split_array and split_array_mut 2021-10-22 09:58:24 +02:00
Caleb Sander
afcee19d88 Make RSplit<T, P>: Clone not require T: Clone
This addresses a TODO comment. The behavior of #[derive(Clone)]
*does* result in a T: Clone requirement.

Add a manual Clone implementation, matching Split and SplitInclusive.
2021-10-21 21:25:59 -07:00
Michael Watzko
0dba9d0e42 Stabilize feature saturating_div for rust 1.58 2021-10-21 18:08:03 +02:00
Wilfred Hughes
04c1ec51f1 Clarify undefined behaviour for binary heap, btree and hashset
Previously, it wasn't clear whether "This could include" was referring
to logic errors, or undefined behaviour. Tweak wording to clarify this
sentence does not relate to UB.
2021-10-21 09:30:46 -04:00
Yuki Okushi
3680ecd8a6
Rollup merge of #90099 - SkiFire13:fix-vec-swap-remove, r=dtolnay
Fix MIRI UB in `Vec::swap_remove`

Fixes #90055

I find it weird that `Vec::swap_remove` read the last element to the stack just to immediately put it back in the `Vec` in place of the one at index `index`. It seems much more natural to me to just read the element at position `index` and then move the last element in its place. I guess this might also slightly improve codegen.
2021-10-21 14:11:13 +09:00
Yuki Okushi
e4cfaa1a7e
Rollup merge of #90077 - woppopo:const_nonzero_from, r=oli-obk
Make `From` impls of NonZero integer const.

I also changed the feature gate added to `From` impls of Atomic integer to `const_num_from_num` from `const_convert`.

Tracking issue: #87852
2021-10-21 14:11:10 +09:00
Yuki Okushi
d29e98fe93
Rollup merge of #90010 - rusticstuff:vecdeque_with_capacity_in_overflow, r=m-ou-se
Avoid overflow in `VecDeque::with_capacity_in()`.

The overflow only happens if alloc is compiled with overflow checks enabled and the passed capacity is greater or equal 2^(usize::BITS-1). The overflow shadows the expected "capacity overflow" panic leading to a test failure if overflow checks are enabled for std in the CI.

Unblocks [CI: Enable overflow checks for test (non-dist) builds #89776](https://github.com/rust-lang/rust/pull/89776).

For some reason the overflow is only observable with optimization turned off, but that is a separate issue.
2021-10-21 14:11:05 +09:00
Yuki Okushi
20687bb4f1
Rollup merge of #89292 - CleanCut:stabilize-cstring_from_vec_with_nul, r=JohnTitor
Stabilize CString::from_vec_with_nul[_unchecked]

Closes the tracking issue #73179. I am keeping this in _draft_ mode until the FCP has ended.

This is my first time stabilizing a feature, so I would appreciate any guidance on things I should do differently.

Closes #73179
2021-10-21 14:11:04 +09:00
Yuki Okushi
fb9232b453
Rollup merge of #87440 - twetzel59:fix-barrier-no-op, r=yaahc
Remove unnecessary condition in Barrier::wait()

This is my first pull request for Rust, so feel free to call me out if anything is amiss.

After some examination, I realized that the second condition of the "spurious-wakeup-handler" loop in ``std::sync::Barrier::wait()`` should always evaluate to ``true``, making it redundant in the ``&&`` expression.

Here is the affected function before the fix:
```rust
#[stable(feature = "rust1", since = "1.0.0")]
pub fn wait(&self) -> BarrierWaitResult {
    let mut lock = self.lock.lock().unwrap();
    let local_gen = lock.generation_id;
    lock.count += 1;
    if lock.count < self.num_threads {
        // We need a while loop to guard against spurious wakeups.
        // https://en.wikipedia.org/wiki/Spurious_wakeup
        while local_gen == lock.generation_id && lock.count < self.num_threads { // fixme
            lock = self.cvar.wait(lock).unwrap();
        }
        BarrierWaitResult(false)
    } else {
        lock.count = 0;
        lock.generation_id = lock.generation_id.wrapping_add(1);
        self.cvar.notify_all();
        BarrierWaitResult(true)
    }
}
```

At first glance, it seems that the check that ``lock.count < self.num_threads`` would be necessary in order for a thread A to detect when another thread B has caused the barrier to reach its thread count, making thread B the "leader".

However, the control flow implicitly results in an invariant that makes observing ``!(lock.count < self.num_threads)``, i.e. ``lock.count >= self.num_threads`` impossible from thread A.

When thread B, which will be the leader, calls ``.wait()`` on this shared instance of the ``Barrier``, it locks the mutex in the first line and saves the ``MutexGuard`` in the ``lock`` variable. It then increments the value of ``lock.count``. However, it then proceeds to check if ``lock.count < self.num_threads``. Since it is the leader, it is the case that (after the increment of ``lock.count``), the lock count is *equal* to the number of threads. Thus, the second branch is immediately taken and ``lock.count`` is zeroed. Additionally, the generation ID is incremented (with wrap). Then, the condition variable is signalled. But, the other threads are waiting at the line ``lock = self.cvar.wait(lock).unwrap();``, so they cannot resume until thread B's call to ``Barrier::wait()`` returns, which drops the ``MutexGuard`` acquired in the first ``let`` statement and unlocks the mutex.

The order of events is thus:
1. A thread A calls `.wait()`
2. `.wait()` acquires the mutex, increments `lock.count`, and takes the first branch
3. Thread A enters the ``while`` loop since the generation ID has not changed and the count is less than the number of threads for the ``Barrier``
3. Spurious wakeups occur, but both conditions hold, so the thread A waits on the condition variable
4. This process repeats for N - 2 additional times for non-leader threads A'
5. *Meanwhile*, Thread B calls ``Barrier::wait()`` on the same barrier that threads A, A', A'', etc. are waiting on. The thread count reaches the number of threads for the ``Barrier``, so all threads should now proceed, with B being the leader. B acquires the mutex and increments the value ``lock.count`` only to find that it is not less than ``self.num_threads``. Thus, it immediately clamps ``self.num_threads`` back down to 0 and increments the generation. Then, it signals the condvar to tell the A (prime) threads that they may continue.
6. The A, A', A''... threads wake up and attempt to re-acquire the ``lock`` as per the internal operation of a condition variable. When each A has exclusive access to the mutex, it finds that ``lock.generation_id`` no longer matches ``local_generation`` **and the ``&&`` expression short-circuits -- and even if it were to evaluate it, ``self.count`` is definitely less than ``self.num_threads`` because it has been reset to ``0`` by thread B *before* B dropped its ``MutexGuard``**.

Therefore, it my understanding that it would be impossible for the non-leader threads to ever see the second boolean expression evaluate to anything other than ``true``. This PR simply removes that condition.

Any input would be appreciated. Sorry if this is terribly verbose. I'm new to the Rust community and concurrency can be hard to explain in words. Thanks!
2021-10-21 14:11:02 +09:00
Yuki Okushi
09de34c107
Rollup merge of #86984 - Smittyvb:ipv4-octal-zero, r=m-ou-se
Reject octal zeros in IPv4 addresses

This fixes #86964 by rejecting octal zeros in IP addresses, such that `192.168.00.00000000` is rejected with a parse error, since having leading zeros in front of another zero indicates it is a zero written in octal notation, which is not allowed in the strict mode specified by RFC 6943 3.1.1. Octal rejection was implemented in #83652, but due to the way it was implemented octal zeros were still allowed.
2021-10-21 14:11:01 +09:00
Nathan Stocks
39af41ed65
fix 'since' version number
Co-authored-by: Yuki Okushi <jtitor@2k36.org>
2021-10-20 15:36:55 -06:00
Nathan Stocks
86b3dd9e0a stabilize CString::from_vec_with_nul[_unchecked] 2021-10-20 14:19:13 -06:00
Giacomo Stevanato
0aa68a8db9 Prevent invalid values from existing in Vec::swap_remove 2021-10-20 15:42:54 +02:00
mbartlett21
fe060bf247 Change Duration::from_secs_* underflow error
Now explicitly says negative value.
2021-10-20 08:48:00 +00:00
woppopo
2fc780638e Make From impls of NonZero integer const.
I also changed the feature gate added to `From` impls of Atomic integer to `const_num_from_num` from `const_convert`.
2021-10-20 12:04:58 +09:00
Yuki Okushi
9f2ad0a061
Rollup merge of #90009 - woppopo:const_from_more, r=dtolnay
Make more `From` impls `const` (libcore)

Adding `const` to `From` implementations in the core. `rustc_const_unstable` attribute is not added to unstable implementations.

Tracking issue: #88674

<details>
<summary>Done</summary><div>

- `T` from `T`
- `T` from `!`
- `Option<T>` from `T`
- `Option<&T>` from `&Option<T>`
- `Option<&mut T>` from `&mut Option<T>`
- `Cell<T>` from `T`
- `RefCell<T>` from `T`
- `UnsafeCell<T>` from `T`
- `OnceCell<T>` from `T`
- `Poll<T>` from `T`
- `u32` from `char`
- `u64` from `char`
- `u128` from `char`
- `char` from `u8`
- `AtomicBool` from `bool`
- `AtomicPtr<T>` from `*mut T`
- `AtomicI(bits)` from `i(bits)`
- `AtomicU(bits)` from `u(bits)`
- `i(bits)` from `NonZeroI(bits)`
- `u(bits)` from `NonZeroU(bits)`
- `NonNull<T>` from `Unique<T>`
- `NonNull<T>` from `&T`
- `NonNull<T>` from `&mut T`
- `Unique<T>` from `&mut T`
- `Infallible` from `!`
- `TryIntError` from `!`
- `TryIntError` from `Infallible`
- `TryFromSliceError` from `Infallible`
- `FromResidual for Option<T>`
</div></details>

<details>
<summary>Remaining</summary><dev>

- `NonZero` from `NonZero`
These can't be made const at this time because these use Into::into.
https://github.com/rust-lang/rust/blob/master/library/core/src/convert/num.rs#L393

- `std`, `alloc`
There may still be many implementations that can be made `const`.
</div></details>
2021-10-20 04:35:15 +09:00
Yuki Okushi
f7024998c7
Rollup merge of #88860 - nbdd0121:panic, r=m-ou-se
Deduplicate panic_fmt

std's begin_panic_fmt and core's panic_fmt are duplicates. Merge them to declutter code and remove a lang item.
2021-10-20 04:35:14 +09:00
Yuki Okushi
84fe598f00
Rollup merge of #88789 - the8472:rm-zip-bound, r=JohnTitor
remove unnecessary bound on Zip specialization impl

I originally added this bound in an attempt to make the specialization
sound for owning iterators but it was never correct here and the correct
and [already implemented](497ee321af/library/alloc/src/vec/into_iter.rs (L220-L232)) solution is is to place it on the IntoIter
implementation.
2021-10-20 04:35:13 +09:00
Yuki Okushi
71fcb72307
Rollup merge of #87769 - m-ou-se:alloc-features-cleanup, r=yaahc,dtolnay
Alloc features cleanup

This sorts and categorizes the `#![features]` in `alloc` and removes unused ones.

This is part of #87766

The following feature attributes were unnecessary and are removed:

```diff
// Library features:
-#![feature(cow_is_borrowed)]
-#![feature(maybe_uninit_uninit_array)]
-#![feature(slice_partition_dedup)]

// Language features:
-#![feature(arbitrary_self_types)]
-#![feature(auto_traits)]
-#![feature(box_patterns)]
-#![feature(decl_macro)]
-#![feature(nll)]
```
2021-10-20 04:35:12 +09:00
Yuki Okushi
ca6798ab07
Rollup merge of #86479 - exphp-forks:float-debug-exponential, r=yaahc
Automatic exponential formatting in Debug

Context: See [this comment from the libs team](https://github.com/rust-lang/rfcs/pull/2729#issuecomment-853454204)

---

Makes `"{:?}"` switch to exponential for floats based on magnitude. The libs team suggested exploring this idea in the discussion thread for RFC rust-lang/rfcs#2729. (**note:** this is **not** an implementation of the RFC; it is an implementation of one of the alternatives)

Thresholds chosen were 1e-4 and 1e16.  Justification described [here](https://github.com/rust-lang/rfcs/pull/2729#issuecomment-864482954).

**This will require a crater run.**

---

As mentioned in the commit message of 8731d4dfb4, this behavior will not apply when a precision is supplied, because I wanted to preserve the following existing and useful behavior of `{:.PREC?}` (which recursively applies `{:.PREC}` to floats in a struct):

```rust
assert_eq!(
    format!("{:.2?}", [100.0, 0.000004]),
    "[100.00, 0.00]",
)
```

I looked around and am not sure where there are any tests that actually use this in the test suite, though?

All things considered, I'm surprised that this change did not seem to break even a single existing test in `x.py test --stage 2`.  (even when I tried a smaller threshold of 1e6)
2021-10-20 04:35:10 +09:00
Gary Guo
9370156957 Deduplicate panic_fmt
std's begin_panic_fmt and core's panic_fmt are duplicates.
Merge them to declutter code and remove a lang item.
2021-10-19 15:02:21 +01:00
Mara Bos
6fdcedc9c8 Reenable feature(nll) in alloc. 2021-10-19 14:54:35 +02:00
Mara Bos
2104ac5706 Remove unused language #![feature]s from alloc. 2021-10-19 14:53:37 +02:00
Mara Bos
4ddc1f2109 Remove unused library #![feature]s from alloc. 2021-10-19 14:51:25 +02:00
Mara Bos
e0c5ed0c18 Sort and categorize #![feature]s in alloc. 2021-10-19 14:51:22 +02:00