Commit Graph

6046 Commits

Author SHA1 Message Date
bors 8b09ba6a5d Auto merge of #90734 - matthiaskrgr:rollup-e1euotp, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #89561 (Type inference for inline consts)
 - #90035 (implement rfc-2528 type_changing-struct-update)
 - #90613 (Allow to run a specific rustdoc-js* test)
 - #90683 (Make `compiler-docs` only control the default instead of being a hard off-switch)
 - #90685 (x.py: remove fixme by deleting code)
 - #90701 (Record more artifact sizes during self-profiling.)
 - #90723 (Better document `Box` and `alloc::alloc::box_free` connection)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-11-09 20:09:53 +00:00
The8472 a6e0aa20d9 remove redundant .iter() call since zip() takes an IntoIterator argument 2021-11-09 20:54:42 +01:00
The8472 7f6e080120 add fast path on Path::eq for exact equality 2021-11-09 20:54:42 +01:00
The8472 a083dd653a optimize Hash for Path
Hashing does not have to use the whole Components parsing machinery because we only need it to match the
normalizations that Components does.

* stripping redundant separators -> skipping separators
* stripping redundant '.' directories -> skipping '.' following after a separator

That's all it takes.

And instead of hashing individual slices for each component we feed the bytes directly into the hasher which avoids
hashing the length of each component in addition to its contents.
2021-11-09 20:54:42 +01:00
The8472 82b4544ddc add benchmarks and tests for Hash and Eq impls on Path
The tests check for consistency between Ord, Eq and Hash
2021-11-09 20:54:00 +01:00
est31 eeaa2f16aa Extend the const_swap feature
This makes the inherent method ptr::swap unstably
const, as well as slice::swap{,_unchecked}.
2021-11-09 20:09:56 +01:00
Jubilee Young caf206b820 Stabilize File::options()
Renames File::with_options to File::options, per consensus in
rust-lang/rust#65439, and stabilizes it.
2021-11-09 10:22:28 -08:00
Matthias Krüger 9c1aa12ff1
Rollup merge of #90723 - asquared31415:box_docs, r=jyn514
Better document `Box` and `alloc::alloc::box_free` connection

The internal `alloc::alloc::box_free` function requires that its signature matches the `owned_box` struct's declaration, but previously that connection was only documented on the `box_free` function.

This PR makes the documentation two-way to help anyone making theoretical changes to `Box` to see the connection, since changes are more likely to originate from `Box`.
2021-11-09 19:00:46 +01:00
bors d6082292a6 Auto merge of #86041 - bstrie:unmagic-array-copy, r=jackh726
Replace Copy/Clone compiler magic on arrays with library impls

With const generics the compiler no longer needs to fake these impls.
2021-11-09 17:13:44 +00:00
Yuki Okushi d638c1d13c
Rollup merge of #87530 - bstrie:commentsync, r=bstrie
Add comments regarding superfluous `!Sync` impls
2021-11-09 22:02:21 +09:00
asquared31415 db4e60b29f document Box and box_free connection 2021-11-09 07:13:53 -05:00
Julian Frimmel 60a9d5a5a9 Re-enable `copy[_nonoverlapping]()` runtime checks
This commit re-enables the debug checks for valid usages of the two
functions `copy()` and `copy_nonoverlapping()`. Those checks were com-
mented out in #79684 in order to make the functions const. All that's
been left was a FIXME, that could not be resolved until there is was way
to only do the checks at runtime.
Since #89247 there is such a way: `const_eval_select()`. This commit
uses that new intrinsic in order to either do nothing (at compile time)
or to do the old checks (at runtime).

The change itself is rather small: in order to make the checks usable
with `const_eval_select`, they are moved into a local function (one for
`copy` and one for `copy_nonoverlapping` to keep symmetry).

The change does not break referential transparency, as there is nothing
you can do at compile time, which you cannot do on runtime without get-
ting undefined behavior. The CTFE-engine won't allow missuses. The other
way round is also fine.
2021-11-09 10:02:09 +01:00
Jacob Pratt 6d2f8af1db
Permit const assertions in stdlib 2021-11-08 17:06:00 -05:00
bstrie 61b1394ac7 Attempt to address perf regressions with #[inline] 2021-11-08 15:51:56 -05:00
bstrie 3024efff59 Update Copy/Clone documentation WRT arrays 2021-11-08 13:11:59 -05:00
bstrie ce1143e94d impl Copy/Clone for arrays in std, not in compiler 2021-11-08 13:11:58 -05:00
bstrie 86c0ef8adc Add comments regarding superfluous `!Sync` impls 2021-11-08 13:07:20 -05:00
Guillaume Gomez f07f800364
Rollup merge of #90494 - Meziu:armv6k-3ds-target, r=sanxiyn
ARMv6K Horizon OS panic change

After a small change to `backtrace-rs` ([#448](https://github.com/rust-lang/backtrace-rs/pull/448)), `PanicStrategy::Unwind` is now fully supported.
2021-11-08 15:15:22 +01:00
Tomoaki Kawada f17077002b kmc-solid: Avoid the use of `asm_const` 2021-11-08 19:13:31 +09:00
bors fecfc0e6cc Auto merge of #89310 - joshtriplett:available-concurrency-affinity, r=m-ou-se
Make `std:🧵:available_concurrency` support process-limited number of CPUs

Use `libc::sched_getaffinity` and count the number of CPUs in the returned mask. This handles cases where the process doesn't have access to all CPUs, such as when limited via `taskset` or similar.

This also covers cgroup cpusets.
2021-11-07 11:53:25 +00:00
bors 90a273b785 Auto merge of #90348 - Amanieu:asm_feature_gates, r=joshtriplett
Add features gates for experimental asm features

This PR splits off parts of `asm!` into separate features because they are not ready for stabilization.

Specifically this adds:
- `asm_const` for `const` operands.
- `asm_sym` for `sym` operands.
- `asm_experimental_arch` for architectures other than x86, x86_64, arm, aarch64 and riscv.

r? `@nagisa`
2021-11-07 04:59:42 +00:00
Amanieu d'Antras eb32c00216 Add features gates for experimental asm features 2021-11-07 01:23:53 +00:00
Jacob Pratt 0cdbeaa2a3
Stabilize `const_raw_ptr_deref` for `*const T`
This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is placed behind the
`const_raw_mut_ptr_deref` feature gate.
2021-11-06 17:05:15 -04:00
Matthias Krüger 0a5640b55f use matches!() macro in more places 2021-11-06 16:13:14 +01:00
bors 7276a6a117 Auto merge of #90297 - dtolnay:dotzero, r=petrochenkov
Append .0 to unsuffixed float if it would otherwise become int token

Previously the unsuffixed f32/f64 constructors of `proc_macro::Literal` would create literal tokens that are definitely not a float:

```rust
Literal::f32_unsuffixed(10.0)  // 10
Literal::f32_suffixed(10.0)    // 10f32
Literal::f64_unsuffixed(10.0)  // 10
Literal::f64_suffixed(10.0)    // 10f64
```

Notice that the `10` are actually integer tokens if you were to reparse them, not float tokens.

This diff updates `Literal::f32_unsuffixed` and `Literal::f64_unsuffixed` to produce tokens that unambiguously parse as a float. This matches longstanding behavior of the proc-macro2 crate's implementation of these APIs dating back at least 3.5 years, so it's likely an unobjectionable behavior.

```rust
Literal::f32_unsuffixed(10.0)  // 10.0
Literal::f32_suffixed(10.0)    // 10f32
Literal::f64_unsuffixed(10.0)  // 10.0
Literal::f64_suffixed(10.0)    // 10f64
```

Fixes https://github.com/dtolnay/syn/issues/1085.
2021-11-06 07:15:05 +00:00
Josh Stone 6edaaa6db8 Also note tool expectations of fork vs clone3
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2021-11-05 14:49:24 -07:00
Josh Stone fa2eee7bf2 Update another comment on fork vs. clone3 2021-11-05 14:48:52 -07:00
Josh Stone 85b55ce00d Only use `clone3` when needed for pidfd
In #89522 we learned that `clone3` is interacting poorly with Gentoo's
`sandbox` tool. We only need that for the unstable pidfd extensions, so
otherwise avoid that and use a normal `fork`.
2021-11-05 14:48:41 -07:00
Yuki Okushi 0b3a002805
Reorder `widening_impl`s to make the doc clearer 2021-11-05 11:55:51 -07:00
bors d22dd65835 Auto merge of #90604 - mbartlett21:iterator-reexports, r=kennytm
Re-export some iterators from `core` in `std`

These iterators seem to have been forgotten to be re-exported from `std` (through `alloc`)

These are stable:

`core::slice::{SplitInclusive, SplitInclusiveMut}`

This one is still unstable:

`core::slice::EscapeAscii` (cc #77174)
2021-11-05 12:22:13 +00:00
bors 489ec310d2 Auto merge of #90577 - matthiaskrgr:clippy_perf_nov, r=petrochenkov
clippy::perf fixes
2021-11-05 09:17:39 +00:00
mbartlett21 ed63c71d61
Fix `str::SplitInclusive` stabilisation date 2021-11-05 17:46:58 +10:00
mbartlett21 d606dbe256
Add feature to `alloc` so we can re-export. 2021-11-05 17:35:07 +10:00
mbartlett21 9ae92ad19a
Re-export `core::slice::EscapeAscii` 2021-11-05 17:14:57 +10:00
mbartlett21 03d1f24db8
Re-export `core::slice::SplitInclusive[Mut]` 2021-11-05 15:44:43 +10:00
Yuki Okushi 5aa6eaf4c0
Rollup merge of #90556 - scottmcm:carrying_comments, r=joshtriplett
Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue https://github.com/rust-lang/rust/issues/85532

cc `````@clarfonthey`````
2021-11-05 10:32:46 +09:00
Matthias Krüger 28ef4169cc clippy::perf fixes 2021-11-04 21:07:56 +01:00
Scott McMurray dc2c2603c6 Add more text and examples to `carrying_{add|mul}" 2021-11-04 00:51:45 -07:00
bors 4061c04079 Auto merge of #87467 - inquisitivecrystal:ref-unwind, r=dtolnay
Implement `RefUnwindSafe` for `Rc<T>`

This PR implements `RefUnwindSafe` for `Rc<T>`, where `T: RefUnwindSafe`.

This impl was omitted by an apparent oversight. `Rc<T>` already implements `UnwindSafe`. `Arc<T>` implements both `UnwindSafe` and `RefUnwindSafe`. There is no reason why an `&Rc<T>` is any less unwind safe than a `Rc<T>` or an `&Arc<T>`, so this should be safe to add.

Resolves #45924.
2021-11-04 06:54:21 +00:00
bors 0b4ac62dda Auto merge of #90392 - solid-rs:fix-solid-support, r=Mark-Simulacrum
kmc-solid: Fix SOLID target

This PR is a follow-up for #86191 and necessary to make the [`*-kmc-solid_*`](https://doc.rust-lang.org/nightly/rustc/platform-support/kmc-solid.html) Tier 3 targets actually usable.

 - Bumps `libc` to 0.2.106, which includes <https://github.com/rust-lang/libc/pull/2227>.
 - Applies the change made by #89324 to this target's target-specific code.
2021-11-04 03:48:43 +00:00
The8472 7afe6f52e4 Make RawVec private to alloc
RawVec was previously exposed for compiler-internal use (libarena specifically) in 1acbb0a935

Since it is unstable, doc-hidden and has no associated tracking issue it was never meant for public use. And since
it is no longer used outside alloc itself it can be made private again.

Also remove some functions that are dead due to lack of internal users.
2021-11-03 20:52:16 +01:00
bors 87ec5680c9 Auto merge of #90421 - thomcc:friendship-ended-with-ssize_t-now-ptrdiff_t-is-my-best-friend, r=joshtriplett
Replace `std::os::raw::c_ssize_t` with `std::os::raw::c_ptrdiff_t`

The discussions in #88345 brought up that `ssize_t` is not actually the signed index type defined in stddef.h, but instead it's `ptrdiff_t`. It seems pretty clear that the use of `ssize_t` here was a mistake on my part, and that if we're going to bother having a isize-alike for FFI in `std::os::raw`, it should be `ptrdiff_t` and not `ssize_t`.

Anyway, both this and `c_size_t` are dubious in the face of the discussion in https://internals.rust-lang.org/t/pre-rfc-usize-is-not-size-t/15369, and any RFC/project-group/etc that handles those issues there should contend with these types in some manner, but that doesn't mean we shouldn't fix something wrong like this, even if it is unstable.

All that said, `size_t` is *vastly* more common in function signatures than either `ssize_t` or `ptrdiff_t`, so I'm going to update the tracking issue's list of unresolved questions to note that perhaps we only want `c_size_t` — I mostly added the signed version for symmetry, rather than to meet a need. (Given this, I'm also fine with modifying this patch to instead remove `c_ssize_t` without a replacement)

CC `@magicant` (who brought the issue up)
CC `@chorman0773` (who has a significantly firmer grasp on the minutae of the C standard than I do)

r? `@joshtriplett` (original reviewer, active in the discussions around this)
2021-11-03 05:36:30 +00:00
inquisitivecrystal bd194da4c2 Implement `RefUnwindSafe` for `Rc<T>` 2021-11-02 16:30:55 -07:00
bors c3190c1eb4 Auto merge of #90442 - ChrisDenton:win-tls-dtor, r=alexcrichton
Windows thread-local keyless drop

`#[thread_local]` allows us to maintain a per-thread list of destructors. This also avoids the need to synchronize global data (which is particularly tricky within the TLS callback function).

r? `@alexcrichton`
2021-11-02 12:15:08 +00:00
Meziu d379147219 Updated backtrace submodule 2021-11-02 12:31:34 +01:00
bors 6384dca100 Auto merge of #90439 - m-ou-se:thread-is-running, r=Mark-Simulacrum
Add JoinHandle::is_running.

This adds:
```rust
impl<T> JoinHandle<T> {
    /// Checks if the the associated thread is still running its main function.
    ///
    /// This might return `false` for a brief moment after the thread's main
    /// function has returned, but before the thread itself has stopped running.
    pub fn is_running(&self) -> bool;
}
```
The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information.

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.
2021-11-02 08:11:57 +00:00
r00ster91 5f6cfd211a mention `remove` in `swap_remove` 2021-11-01 18:52:26 +01:00
Chris Denton 1048651fa3
Run destructors from existing tls callback 2021-11-01 15:19:49 +00:00
Mara Bos 978ebd9c8c Add tracking issue for thread_is_running. 2021-11-01 15:04:24 +01:00
Tomoaki Kawada 26a6cc4515 itron: Rename `itron:🧵:{available_conccurrency -> available_parallelism}`
Catching up with commit b4615b5bf9
2021-11-01 10:45:51 +09:00
Tomoaki Kawada 15af06795c Bump libc dependency of std to 0.2.106 2021-11-01 10:45:49 +09:00
Thom Chiovoloni 8d19819781
Re-add `std::os::raw::c_ssize_t`, with more accurate documentation 2021-10-31 13:01:57 -07:00
Chris Denton d9a1f9a79c
Windows: Resolve Command program without using the current directory 2021-10-31 16:32:34 +00:00
Chris Denton 9212f4070e
Windows thread-local keyless drop
`#[thread_local]` allows us to maintain a per-thread list of destructors. This also avoids the need to synchronize global data (which is particularly tricky within the TLS callback function).
2021-10-31 16:09:35 +00:00
bors c7e4740ec1 Auto merge of #86336 - camsteffen:char-array-pattern, r=joshtriplett
impl Pattern for char array

Closes #39511
Closes #86329
2021-10-31 15:45:39 +00:00
Mara Bos 67362b301b Add test for JoinHandle::is_running. 2021-10-31 15:23:36 +01:00
Mara Bos d718b1a795 Add JoinHandle::is_running. 2021-10-31 15:09:36 +01:00
Matthias Krüger 455a79acab
Rollup merge of #90431 - jkugelman:must-use-std-o-through-z, r=joshtriplett
Add #[must_use] to remaining std functions (O-Z)

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is half of the remaining items from the `std` crate, from O-Z.

`panicking::take_hook` has a side effect: it unregisters the current panic hook, returning it. I almost ignored it, but the documentation example shows `let _ = panic::take_hook();`, so following suit I went ahead and added a `#[must_use]`.

```rust
std::panicking   fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>;
```

I added these functions that clippy did not flag:

```rust
std::path::Path   fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool;
std::path::Path   fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool;
std::path::Path   fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf;
std::path::Path   fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf;
```

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 13:20:07 +01:00
Matthias Krüger 26f505c433
Rollup merge of #90430 - jkugelman:must-use-std-a-through-n, r=joshtriplett
Add #[must_use] to remaining std functions (A-N)

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is half of the remaining items from the `std` crate, from A-N.

I added these functions myself. Clippy predictably ignored the `mut` ones, but I don't know why the rest weren't flagged. Check them closely, please? Maybe I overlooked good reasons.

```rust
std::backtrace::Backtrace                                   const fn disabled() -> Backtrace;
std::backtrace::Backtrace<'a>                               fn frames(&'a self) -> &'a [BacktraceFrame];
std::collections::hash_map::RawOccupiedEntryMut<'a, K, V>   fn key_mut(&mut self) -> &mut K;
std::collections::hash_map::RawOccupiedEntryMut<'a, K, V>   fn get_mut(&mut self) -> &mut V;
std::collections::hash_map::RawOccupiedEntryMut<'a, K, V>   fn get_key_value(&mut self) -> (&K, &V);
std::collections::hash_map::RawOccupiedEntryMut<'a, K, V>   fn get_key_value_mut(&mut self) -> (&mut K, &mut V);
std::env                                                    fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString>;
std::env                                                    fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_>;
std::io::Error                                              fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)>;
```

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 13:20:06 +01:00
Matthias Krüger 88e5ae2dd3
Rollup merge of #89786 - jkugelman:must-use-len-and-is_empty, r=joshtriplett
Add #[must_use] to len and is_empty

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 13:20:05 +01:00
Matthias Krüger 6c5aa765fb
Rollup merge of #89068 - bjorn3:restructure_rt2, r=joshtriplett
Restructure std::rt (part 2)

A couple more cleanups on top of https://github.com/rust-lang/rust/pull/89011

Blocked on #89011
2021-10-31 13:20:04 +01:00
Matthias Krüger ff6d8ecd64
Rollup merge of #90427 - jkugelman:must-use-alloc-leak, r=joshtriplett
Add #[must_use] to alloc functions that would leak memory

As [requested](https://github.com/rust-lang/rust/pull/89899#issuecomment-955600779) by `@joshtriplett.`

> Please do go ahead and add the ones whose only legitimate use for ignoring the return value is leaking memory. (In a separate PR please.) I think it's sufficiently error-prone to call something like alloc and ignore the result that it's legitimate to require `let _ =` for that.

I added `realloc` myself. Clippy ignored it because of its `mut` argument.

```rust
alloc/src/alloc.rs:123:1   alloc   unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8;
```

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 09:20:27 +01:00
Matthias Krüger d4bdcdb1ec
Rollup merge of #89951 - ojeda:stable-unwrap_unchecked, r=dtolnay
Stabilize `option_result_unwrap_unchecked`

Closes https://github.com/rust-lang/rust/issues/81383.

Stabilization report: https://github.com/rust-lang/rust/issues/81383#issuecomment-944498212.

```@rustbot``` label +A-option-result +T-libs-api
2021-10-31 09:20:27 +01:00
Matthias Krüger 95750ae439
Rollup merge of #89897 - jkugelman:must-use-core, r=joshtriplett
Add #[must_use] to remaining core functions

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `core` crate.

Ignored by clippy for reasons unknown:

```rust
core::alloc::Layout   unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self;
core::any             const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str;
```

Ignored by clippy because of `mut`:

```rust
str   fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
```

<del>
Ignored by clippy presumably because a caller might want `f` called for side effects. That seems like a bad usage of `map` to me.

```rust
core::cell::Ref<'b, T>   fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, T>;
core::cell::Ref<'b, T>   fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>);
```
</del>

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:26 +01:00
Matthias Krüger e79e9f5e2a
Rollup merge of #89839 - jkugelman:must-use-mem-ptr-functions, r=joshtriplett
Add #[must_use] to mem/ptr functions

There's a lot of low-level / unsafe stuff here. Are there legit use cases for ignoring any of these return values?

* No regressions in `./x.py test --stage 1 library/std src/tools/clippy`.
* One regression in `./x.py test --stage 1 src/test/ui`. Fixed.
* I am unable to run `./x.py doc` on my machine so I'll need to wait for the CI to verify doctests pass. I eyeballed all the adjacent tests and they all look okay.

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:25 +01:00
Matthias Krüger a26b1d2259
Rollup merge of #89835 - jkugelman:must-use-expensive-computations, r=joshtriplett
Add #[must_use] to expensive computations

The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work.

Given the grab bag nature of this commit, the messages I used vary quite a bit. I'm open to wording changes.

For some reason clippy flagged four `BTreeSet` methods but didn't say boo about equivalent ones on `HashSet`. I stared at them for a while but I can't figure out the difference so I added the `HashSet` ones in.

```rust
// Flagged by clippy.
alloc::collections::btree_set::BTreeSet<T>   fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>;
alloc::collections::btree_set::BTreeSet<T>   fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
alloc::collections::btree_set::BTreeSet<T>   fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>;
alloc::collections::btree_set::BTreeSet<T>   fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>;

// Ignored by clippy, but not by me.
std::collections::HashSet<T, S>              fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>;
std::collections::HashSet<T, S>              fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S>
std::collections::HashSet<T, S>              fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>;
std::collections::HashSet<T, S>              fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>;
```

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:24 +01:00
Matthias Krüger 3cf3910c15
Rollup merge of #89833 - jkugelman:must-use-rc-downgrade, r=joshtriplett
Add #[must_use] to Rc::downgrade

Missed this in previous PR https://github.com/rust-lang/rust/pull/89796#issuecomment-941456006

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:23 +01:00
Matthias Krüger 15a0cddff3
Rollup merge of #89677 - maxwase:is-symlink-stabilization, r=joshtriplett
Stabilize `is_symlink()` for `Metadata` and `Path`

I'm not fully sure about `since` version, correct me if I'm wrong

Needs update after stabilization: [cargo-test-support](8063672238/crates/cargo-test-support/src/paths.rs (L202))

Linked issue: #85748
2021-10-31 09:20:22 +01:00
Matthias Krüger e7be8a2c07
Rollup merge of #89446 - chrismit3s:issue-88715-fix, r=joshtriplett
Add paragraph to ControlFlow docs to menion it works with the ? operator (#88715)

fixes #88715

r? ```@steveklabnik```
2021-10-31 09:20:21 +01:00
John Kugelman e129d49f88 Add #[must_use] to remaining std functions (A-N) 2021-10-30 23:44:02 -04:00
John Kugelman a81d4b18ea Add #[must_use] to remaining std functions (O-Z) 2021-10-30 23:37:32 -04:00
John Kugelman 42e0282d52 Add #[must_use] to alloc functions that would leak memory 2021-10-30 22:19:07 -04:00
bors 0a09858b05 Auto merge of #90306 - kornelski:slicecloneasset, r=joshtriplett
track_caller for slice length assertions

`clone_from_slice` was missing `#[track_caller]`, and its assert did not report a useful location.

These are small generic methods, so hopefully track_caller gets inlined into nothingness, but it may be worth running a benchmark on this.
2021-10-31 01:56:40 +00:00
Josh Triplett 7c9611d124 Make std:🧵:available_concurrency support process-limited number of CPUs
Use libc::sched_getaffinity and count the number of CPUs in the returned
mask. This handles cases where the process doesn't have access to all
CPUs, such as when limited via taskset or similar.
2021-10-31 01:38:14 +02:00
Josh Triplett 23be29aace Update libc to 0.2.106 to get definitions for CPU_* 2021-10-31 01:38:05 +02:00
John Kugelman 6745e8da06 Add #[must_use] to len and is_empty 2021-10-30 19:25:12 -04:00
John Kugelman 887503ad14 Add #[must_use] to mem/ptr functions 2021-10-30 18:54:48 -04:00
Matthias Krüger 0da75bcc9c
Rollup merge of #90401 - mkroening:hermit-condvar, r=joshtriplett
hermit: Implement Condvar::wait_timeout

This implements `Condvar::wait_timeout` for the `hermit` target.

See
* https://github.com/hermitcore/rust/pull/2
* https://github.com/hermitcore/rust/pull/5

CC: `@stlankes`
2021-10-31 00:33:25 +02:00
Matthias Krüger 1adb664392
Rollup merge of #89899 - jkugelman:must-use-alloc, r=joshtriplett
Add #[must_use] to remaining alloc functions

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `alloc` crate.

I ignored these because they might be used to purposefully leak memory... or other allocator shenanigans? I dunno. I'll add them if y'all tell me to.

```rust
alloc::alloc          unsafe fn alloc(layout: Layout) -> *mut u8;
alloc::alloc          unsafe fn alloc_zeroed(layout: Layout) -> *mut u8;
alloc::sync::Arc<T>   fn into_raw(this: Self) -> *const T;
```

I don't know why clippy ignored these. I added them myself:

```rust
alloc::collections::btree_map::BTreeMap<K, V>   fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>;
alloc::collections::btree_set::BTreeSet<T>      fn range<K: ?Sized, R>(&self, range: R) -> Range<'_, T>;
```

I added these non-mutating `mut` functions:

```rust
alloc::collections::btree_map::BTreeMap<K, V>     fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>;
alloc::collections::btree_map::BTreeMap<K, V>     fn iter_mut(&mut self) -> IterMut<'_, K, V>;
alloc::collections::btree_map::BTreeMap<K, V>     fn values_mut(&mut self) -> ValuesMut<'_, K, V>;
alloc::collections::linked_list::LinkedList<T>    fn iter_mut(&mut self) -> IterMut<'_, T>;
alloc::collections::linked_list::LinkedList<T>    fn cursor_front_mut(&mut self) -> CursorMut<'_, T>;
alloc::collections::linked_list::LinkedList<T>    fn cursor_back_mut(&mut self) -> CursorMut<'_, T>;
alloc::collections::linked_list::LinkedList<T>    fn front_mut(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::LinkedList<T>    fn back_mut(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::CursorMut<'a, T> fn current(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::CursorMut<'a, T> fn peek_next(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::CursorMut<'a, T> fn peek_prev(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::CursorMut<'a, T> fn front_mut(&mut self) -> Option<&mut T>;
alloc::collections::linked_list::CursorMut<'a, T> fn back_mut(&mut self) -> Option<&mut T>;
```

I moved a few existing `#[must_use]`s from functions onto the iterator types they return: `IntoIterSorted`, `IntoKeys`, `IntoValues`.

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 00:33:24 +02:00
Matthias Krüger d872d7fd00
Rollup merge of #89789 - jkugelman:must-use-thread-builder, r=joshtriplett
Add #[must_use] to thread::Builder

I copied the wording of the [`fmt::Debug` builders](https://doc.rust-lang.org/src/core/fmt/builders.rs.html#444).

Affects:

```rust
std/src/thread/mod.rs:289:5   std:🧵:Builder   fn new() -> Builder;
std/src/thread/mod.rs:318:5   std:🧵:Builder   fn name(mut self, name: String) -> Builder;
std/src/thread/mod.rs:341:5   std:🧵:Builder   fn stack_size(mut self, size: usize) -> Builder;
```

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 00:33:23 +02:00
John Kugelman 68b0d86294 Add #[must_use] to remaining core functions 2021-10-30 18:21:29 -04:00
Thom Chiovoloni d429d0df33
Replace `std::os::raw::c_ssize_t` with `std::os::raw::c_ptrdiff_t` 2021-10-30 10:54:34 -07:00
bors 2609fab8e4 Auto merge of #90205 - mati865:link-modifiers-in-rustc, r=petrochenkov
Repace use of `static_nobundle` with `native_link_modifiers` within Rust codebase

This fixes warnings when building Rust and running tests:
```
warning: library kind `static-nobundle` has been superseded by specifying `-bundle` on library kind `static`. Try `static:-bundle`
warning: `rustc_llvm` (lib) generated 2 warnings (1 duplicate)
```
2021-10-30 16:22:49 +00:00
Matthias Krüger b531364a1a
Rollup merge of #90377 - WaffleLapkin:const_slice_from_raw_parts, r=oli-obk
Make `core::slice::from_raw_parts[_mut]` const

Responses to #90012 seem to allow ``@rust-lang/wg-const-eval`` to decide on use of `const_eval_select`, so we can make `core::slice::from_raw_parts[_mut]` const :)

---
This PR marks the following APIs as const:
```rust
// core::slice
pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T];
pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T];
```
---

Resolves #90011
r? ``@oli-obk``
2021-10-30 14:37:01 +02:00
Matthias Krüger 86087f906d
Rollup merge of #90371 - Veykril:patch-2, r=jyn514
Fix incorrect doc link

Looks like a copy paste mistake
2021-10-30 14:36:59 +02:00
Matthias Krüger 20bb93210d
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
Make most std::ops traits const on numeric types

This PR makes existing implementations of `std::ops` traits (`Add`, `Sub`, etc) [`impl const`](https://github.com/rust-lang/rust/issues/67792) where possible.
This affects:
- All numeric primitives (`u*`, `i*`, `f*`)
- `NonZero*`
- `Wrapping`

This is under the `rustc_const_unstable` feature `const_ops`.
I will write tests once I know what can and can't be kept for the final version of this PR.

Since this is my first PR to rustc (and hopefully one of many), please give me feedback on how to better handle the PR process wherever possible. Thanks

[Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Const.20std.3A.3Aops.20traits.20PR)
2021-10-30 14:36:58 +02:00
Chris Denton 07f54d94e6
Use "rustc" for testing Command args
"echo" is not an application on Windows so `Command` tests could fail even if that's not what's being tested for.
2021-10-30 12:03:49 +01:00
bors 2b643e9871 Auto merge of #89174 - ChrisDenton:automatic-verbatim-paths, r=dtolnay
Automatically convert paths to verbatim for filesystem operations that support it

This allows using longer paths without the user needing to `canonicalize` or manually prefix paths. If the path is already verbatim then this has no effect.

Fixes: #32689
2021-10-30 07:21:21 +00:00
bors 6d42707cde Auto merge of #90346 - ferrocene:pa-short-circuit, r=oli-obk
Replace some operators in libcore with their short-circuiting equivalents

In libcore there are a few occurrences of bitwise operators used in boolean expressions instead of their short-circuiting equivalents. This makes it harder to perform some kinds of source code analysis over libcore, for example [MC/DC] code coverage (a requirement in safety-critical environments).

This PR aims to remove as many bitwise operators in boolean expressions from libcore as possible, without any performance regression and without other changes. This means not all bitwise operators are removed, only the ones that don't have any difference with their short-circuiting counterparts. This already simplifies achieving MC/DC coverage, and the other functions can be changed in future PRs.

The PR is best reviewed commit-by-commit, and each commit has the resulting assembly in the message.

## Checked integer methods

These methods recently switched to bitwise operators in PRs https://github.com/rust-lang/rust/pull/89459 and https://github.com/rust-lang/rust/pull/89351. I confirmed bitwise operators are needed in most of the functions, except these two:

* `{integer}::checked_div` ([Godbolt link (nightly)](https://rust.godbolt.org/z/17efh5jPc))
* `{integer}::checked_rem` ([Godbolt link (nightly)](https://rust.godbolt.org/z/85qGWc94K))

`@tspiteri` already mentioned this was the case in https://github.com/rust-lang/rust/pull/89459#issuecomment-932728384, but opted to also switch those two to bitwise operators for consistency. As that makes MC/DC analysis harder this PR proposes switching those two back to short-circuiting operators.

## `{unsigned_ints}::carrying_add`

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/vG9vx8x48)

In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.

## `{unsigned_ints}::borrowing_sub`

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/asEfKaGE4)

In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.

## String UTF-8 validation

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/a4rEbTvvx)

In this instance replacing the `|` with `||` produces practically the same assembly, with the two operands for the "or" swapped:

```asm
; Old
mov  rax, qword ptr [rdi + rdx + 8]
or   rax, qword ptr [rdi + rdx]
test rax, r9
je   .LBB0_7

; New
mov  rax, qword ptr [rdi + rdx]
or   rax, qword ptr [rdi + rdx + 8]
test rax, r8
je   .LBB0_7
```

[MC/DC]: https://en.wikipedia.org/wiki/Modified_condition/decision_coverage
2021-10-29 21:50:46 +00:00
Maybe Waffle afaa54a99d Apply changes proposed in the review 2021-10-29 23:45:09 +03:00
Maybe Waffle 878ac10fe1 Use proper issue number for `feature(const_slice_from_raw_parts)` 2021-10-29 22:45:10 +03:00
Martin Kröning 42cab439f5 hermit: Implement Condvar::wait_timeout 2021-10-29 17:20:03 +02:00
bors 88a5a984fe Auto merge of #90380 - Mark-Simulacrum:revert-89558-query-stable-lint, r=lcnr
Revert "Add rustc lint, warning when iterating over hashmaps"

Fixes perf regressions introduced in https://github.com/rust-lang/rust/pull/90235 by temporarily reverting the relevant PR.
2021-10-29 04:55:51 +00:00
Matthias Krüger ae244d8b78
Rollup merge of #90336 - mbartlett21:patch-4, r=Mark-Simulacrum
Remove extra lines in examples for `Duration::try_from_secs_*`

None of the other examples have extra lines below the `#![feature(...)]` statements, so I thought it appropriate that these examples shouldn't either.
2021-10-29 00:30:30 +02:00
Mark Rousskov 3215eeb99f
Revert "Add rustc lint, warning when iterating over hashmaps" 2021-10-28 11:01:42 -04:00
Maybe Waffle 991a296ce7 Make `core::slice::from_raw_parts[_mut]` const 2021-10-28 17:15:25 +03:00
Lukas Wirth 29a4e4a009
Fix incorrect doc link 2021-10-28 11:51:00 +02:00
bors 4e0d3973fa Auto merge of #90347 - matthiaskrgr:rollup-rp2ms7j, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #90239 (Consistent big O notation in map.rs)
 - #90267 (fix: inner attribute followed by outer attribute causing ICE)
 - #90288 (Add hint for people missing `TryFrom`, `TryInto`, `FromIterator` import pre-2021)
 - #90304 (Add regression test for #75961)
 - #90344 (Add tracking issue number to const_cstr_unchecked)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-10-27 18:42:13 +00:00
Matthias Krüger 623c3e144e
Rollup merge of #90344 - xfix:tracking-issue-const_cstr_unchecked, r=Mark-Simulacrum
Add tracking issue number to const_cstr_unchecked

Also created a tracking issue, see #90343.

I think it makes sense to stabilize this somewhat soon considering abuse of `transmute` to have this feature in constants, see https://crates.io/crates/cstr for an example. Code can be rewritten to use `mem::transmute` to work on stable.
2021-10-27 18:25:47 +02:00
Matthias Krüger 088dc91e0a
Rollup merge of #90239 - r00ster91:patch-1, r=fee1-dead
Consistent big O notation in map.rs

Follow up to #89216
2021-10-27 18:25:43 +02:00
r00ster91 b1b4c6cb00 Remove big O notation 2021-10-27 17:43:14 +02:00
bors dd757b9e06 Auto merge of #90273 - nbdd0121:const, r=fee1-dead
Clean up special function const checks

Mark them as const and `#[rustc_do_not_const_check]` instead of hard-coding them in const-eval checks.

r? `@oli-obk`
`@rustbot` label A-const-eval T-compiler
2021-10-27 15:32:42 +00:00
Pietro Albini 68a4460b61
replace `&` with `&&` in {integer}::checked_rem
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:

```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov eax, 1
ret
```
2021-10-27 17:01:05 +02:00
Pietro Albini 81130fe188
replace `&` with `&&` in {integer}::checked_div
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:

```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov edx, eax
mov eax, 1
ret
```
2021-10-27 17:00:57 +02:00
Pietro Albini a5a8bb0125
replace `|` with `||` in string validation
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is
equivalent between the old and new versions.

Old assembly of that condition:

```
mov  rax, qword ptr [rdi + rdx + 8]
or   rax, qword ptr [rdi + rdx]
test rax, r9
je   .LBB0_7
```

New assembly of that condition:

```
mov  rax, qword ptr [rdi + rdx]
or   rax, qword ptr [rdi + rdx + 8]
test rax, r8
je   .LBB0_7
```
2021-10-27 17:00:49 +02:00
Pietro Albini 9fb66969e3
replace `|` with `||` in {unsigned_int}::borrowing_sub
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:

```
mov eax, edi
add dl, -1
sbb eax, esi
setb dl
ret
```
2021-10-27 17:00:46 +02:00
Pietro Albini 5913ef6660
replace `|` with `||` in {unsigned_int}::carrying_add
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:

```
mov eax, edi
add dl, -1
adc eax, esi
setb dl
ret
```
2021-10-27 17:00:36 +02:00
Konrad Borowski 50ca08c5f5 Add tracking issue number to const_cstr_unchecked 2021-10-27 15:18:25 +02:00
Matthias Krüger e3eebfeea6
Rollup merge of #90154 - camelid:remove-getdefid, r=jyn514
rustdoc: Remove `GetDefId`

See the individual commit messages for details.

r? `@jyn514`
2021-10-27 06:11:35 +02:00
mbartlett21 aa48de0b0e
Remove extra lines in examples for `Duration::try_from_secs_*` 2021-10-27 13:52:39 +10:00
bors e269e6bf47 Auto merge of #90314 - matthiaskrgr:rollup-ag1js8n, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #90296 (Remove fNN::lerp)
 - #90302 (Remove unneeded into_iter)
 - #90303 (Add regression test for issue 90164)
 - #90305 (Add regression test for #87258)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-10-26 17:50:46 +00:00
Matthias Krüger 8871fe8bda
Rollup merge of #90296 - CAD97:rip-lerp, r=Mark-Simulacrum
Remove fNN::lerp

Lerp is [surprisingly complex with multiple tradeoffs depending on what guarantees you want to provide](https://github.com/rust-lang/rust/issues/86269#issuecomment-869108301) (and what you're willing to drop for raw speed), so we don't have consensus on what implementation to use, let alone what signature - `t.lerp(a, b)` nicely puts `a, b` together, but makes dispatch to lerp custom types with the same signature basically impossible, and major ecosystem crates (e.g. nalgebra, glium) use `a.lerp(b, t)`, which is easily confusable. It was suggested to maybe provide a `Lerp<T>` trait and `t.lerp([a, b])`, which _could_ be implemented by downstream math libraries for their types, but also significantly raises the bar from a simple fNN method to a full trait, and does nothing to solve the implementation question. (It also raises the question of whether we'd support higher-order bezier interpolation.)

The only consensus we have is the lack of consensus, and the [general temperature](https://github.com/rust-lang/rust/issues/86269#issuecomment-951347135) is that we should just remove this method (giving the method space back to 3rd party libs) and revisit this if (and likely only if) IEEE adds lerp to their specification.

If people want a lerp, they're _probably_ already using (or writing) a math support library, which provides a lerp function for its custom math types and can provide the same lerp implementation for the primitive types via an extension trait.

See also [previous Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/lerp.20API.20design)

cc ``@clarfonthey`` (original PR author), ``@m-ou-se`` (original r+), ``@scottmcm`` (last voice in tracking issue, prompted me to post this)

Closes #86269 (removed)
2021-10-26 19:32:44 +02:00
bors 612356aa9a Auto merge of #90290 - nyanpasu64:fix-string-as-mut-vec, r=m-ou-se
Fix copy-paste error in String::as_mut_vec() docs

Did not expect the comments to be perfectly justified... can't wait to be told to change it to `Vec<u8>`, which destroys the justification 😼
2021-10-26 14:44:47 +00:00
Kornel 90ea93bf1a track_caller for slice length assertions 2021-10-26 13:03:02 +01:00
bors 3c8f001d45 Auto merge of #90284 - tonyyzy:patch-1, r=JohnTitor
Remove redundant Aligner

The `Aligner` struct seems to be unnecessary.
Previously noted by `@arthurprs` https://github.com/rust-lang/rust/pull/44963#discussion_r145340754
Reddit discussion: https://www.reddit.com/r/rust/comments/pfvvz2/aligner_and_cachealigned/
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fa7ca554922755f9d1b62b017d785c6f
2021-10-26 11:45:13 +00:00
Tony Yang f54663767d
Remove redundant Aligner
The `Aligner` struct seems to be unnecessary.
Previously noted by @arthurprs https://github.com/rust-lang/rust/pull/44963#discussion_r145340754
Reddit discussion: https://www.reddit.com/r/rust/comments/pfvvz2/aligner_and_cachealigned/
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fa7ca554922755f9d1b62b017d785c6f
2021-10-26 11:34:03 +01:00
nyanpasu64 6b90c0f1b4 Fix copy-paste error in String::as_mut_vec() docs 2021-10-25 23:22:57 -07:00
CAD97 6b449b49bb Remove fNN::lerp - consensus unlikely 2021-10-25 22:44:41 -05:00
David Tolnay c5025f0e4e
Append .0 to unsuffixed float if it would otherwise become int token 2021-10-25 20:30:47 -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
Gary Guo cc4345a1c5 Clean up special function const checks
Mark them as const and `#[rustc_do_not_const_check]` instead of hard-coding
them in const-eval checks.
2021-10-25 17:32:01 +01:00
woppopo 7430b22b5f Make `Option::expect` const 2021-10-26 00:41:39 +09: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
Chris Denton 37e4c84b23
Fix typo
Co-authored-by: Ruslan Sayfutdinov <ruslan@sayfutdinov.com>
2021-10-23 20:04:45 +01:00
Chris Denton f1efc7efb2
Make sure `CreateDirectoryW` works for path lengths > 247 2021-10-23 19:35:24 +01: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
Mateusz Mikuła a076f2b9b4 Repace use of `static_nobundle` with `native_link_modifiers`
This fixes warning when building Rust and running tests:
```
warning: library kind `static-nobundle` has been superseded by specifying `-bundle` on library kind `static`. Try `static:-bundle`
warning: `rustc_llvm` (lib) generated 2 warnings (1 duplicate)
```
2021-10-23 15:51:22 +02: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
Noah Lev 865d99f82b docs: Escape brackets to satisfy the linkchecker
My change to use `Type::def_id()` (formerly `Type::def_id_full()`) in
more places caused some docs to show up that used to be missed by
rustdoc. Those docs contained unescaped square brackets, which triggered
linkcheck errors. This commit escapes the square brackets and adds this
particular instance to the linkcheck exception list.
2021-10-22 14:08:43 -07: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
AlexApps99 361c978fbd
Added docs to internal_macro const 2021-10-22 10:07:35 +13:00
AlexApps99 23d033e177
Added const versions of common numeric operations
# Conflicts:
#	library/core/src/lib.rs
2021-10-22 10:03:18 +13: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
Miguel Ojeda 63d7882575 Stabilize `option_result_unwrap_unchecked`
Closes https://github.com/rust-lang/rust/issues/81383.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-10-20 04:03:43 +02: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
bors 2f22e63cc4 Auto merge of #90037 - matthiaskrgr:rollup-cdfhxtn, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #89766 (RustWrapper: adapt for an LLVM API change)
 - #89867 (Fix macro_rules! duplication when reexported in the same module)
 - #89941 (removing TLS support in x86_64-unknown-none-hermitkernel)
 - #89956 (Suggest a case insensitive match name regardless of levenshtein distance)
 - #89988 (Do not promote values with const drop that need to be dropped)
 - #89997 (Add test for issue #84957 - `str.as_bytes()` in a `const` expression)
 - #90002 (⬆️ rust-analyzer)
 - #90034 (Tiny tweak to Iterator::unzip() doc comment example.)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-10-19 05:04:38 +00:00
Matthias Krüger 5bcaf04cbb
Rollup merge of #90034 - moxian:unzip-doc, r=cuviper
Tiny tweak to Iterator::unzip() doc comment example.

It's easier to figure out what it's doing and which output elements map to which input ones if the matrix we are dealing with is rectangular 2x3 rather than square 2x2.
2021-10-19 05:40:56 +02:00
Matthias Krüger 9dccb7bd89
Rollup merge of #89941 - hermitcore:kernel, r=joshtriplett
removing TLS support in x86_64-unknown-none-hermitkernel

HermitCore's kernel itself doesn't support TLS. Consequently, the entries in x86_64-unknown-none-hermitkernel should be removed. This commit should help to finalize #89062.
2021-10-19 05:40:52 +02:00
bors cd8b56f528 Auto merge of #89905 - matthiaskrgr:rev_89709_entirely, r=michaelwoerister
Revert "Auto merge of #89709 - clemenswasser:apply_clippy_suggestions…

…_2, r=petrochenkov"

The PR had some unforseen perf regressions that are not as easy to find.
Revert the PR for now.

This reverts commit 6ae8912a3e, reversing
changes made to 86d6d2b738.
2021-10-19 02:03:21 +00:00
moxian 1519ca99d8 Tiny tweak to Iterator::unzip() doc comment example.
It's easier to figure out what it's doing and which output
elements map to which input ones if the matrix we are dealing
with is rectangular 2x3 rather than square 2x2.
2021-10-19 00:03:51 +00:00
Hans Kratz 4a37b9cbff Avoid overflow in `VecDeque::with_capacity_in()`. 2021-10-18 13:18:12 +02:00
woppopo 7936ecff48 Make more `From` impls `const` 2021-10-18 19:19:28 +09:00
Konrad Borowski 86c309c27f Inline CStr::from_ptr 2021-10-18 11:38:51 +02:00
Matthias Krüger 2724b00065
Rollup merge of #89996 - winterqt:bump-backtrace, r=Mark-Simulacrum
Bump backtrace

https://github.com/rust-lang/backtrace-rs/pull/446 allows binaries built with Nix on macOS to be symbolized.
2021-10-18 08:13:32 +02:00
Winter 3f87b7cc0b bump backtrace
https://github.com/rust-lang/backtrace-rs/pull/446 allows binaries built
with Nix on macOS to be symbolized.
2021-10-17 21:20:18 -04:00
Matthias Krüger f044a84f5d
Rollup merge of #89977 - woppopo:result_const_as_mut, r=oli-obk
Make Result::as_mut const

Adding `const` for `Result::as_mut`.

Tracking issue: #82814
2021-10-17 18:19:00 +02:00
Matthias Krüger 1520fffecc
Rollup merge of #89945 - JohnTitor:we-now-specialize-clone-from-slice, r=the8472
Remove a mention to `copy_from_slice` from `clone_from_slice` doc

Fixes #84736
I think removing it would be the best but I'm happy to clarify it instead if someone would like.
2021-10-17 18:18:57 +02:00
woppopo ea28abee28 Make Result::as_mut const 2021-10-17 18:39:54 +09:00
bors 1d6f24210c Auto merge of #88652 - AGSaidi:linux-aarch64-should-be-actually-monotonic, r=yaahc
linux/aarch64 Now() should be actually_monotonic()

While issues have been seen on arm64 platforms the Arm architecture requires
that the counter monotonically increases and that it must provide a uniform
view of system time (e.g. it must not be possible for a core to receive a
message from another core with a time stamp and observe time going backwards
(ARM DDI 0487G.b D11.1.2). While there have been a few 64bit SoCs that have
bugs (#49281, #56940) which cause time to not monotonically increase, these have
been fixed in the Linux kernel and we shouldn't penalize all Arm SoCs for those
who refuse to update their kernels:
SUN50I_ERRATUM_UNKNOWN1 - Allwinner A64 / Pine A64 - fixed in 5.1
FSL_ERRATUM_A008585 - Freescale LS2080A/LS1043A - fixed in 4.10
HISILICON_ERRATUM_161010101 - Hisilicon 1610 - fixed in 4.11
ARM64_ERRATUM_858921 - Cortex A73 - fixed in 4.12

255a3f3e18 std: Force `Instant::now()` to be monotonic added a Mutex to work around
this problem and a small test program using glommio shows the majority of time spent
acquiring and releasing this Mutex. 3914a7b0da tries to improve this, but actually
makes it worse on big systems as for 128b atomics a ldxp/stxp pair (and successful loop)
for v8.4 systems that don't support FEAT_LSE2 is required which is expensive as a lock
and because of how the load/store-exclusives scale on large Arm systems is both unfair
to threads and tends to go backwards in performance.

A small sample program using glommio improves by 70x on a 32 core Graviton2
system with this change.
2021-10-17 09:30:30 +00:00
Yuki Okushi 0029af7930
Rollup merge of #89953 - woppopo:option_const_as_mut, r=oli-obk
Make Option::as_mut const

Adding `const` for `Option::as_mut`.

Tracking issue: #67441
2021-10-17 07:52:21 +09:00
Yuki Okushi 9614da27cd
Rollup merge of #89507 - lopopolo:lopopolo/ordering-repr-i8, r=joshtriplett
Add `#[repr(i8)]` to `Ordering`

Followup to #89491 to allow `Ordering` to auto-derive `AsRepr` once the proposal to add `AsRepr` (#81642) lands.

cc ``@joshtriplett``
2021-10-17 07:52:17 +09:00
woppopo d1f7608699 Add `#![cfg_attr(bootstrap, feature(const_panic))]` to `library/core/tests/lib.rs` 2021-10-17 00:32:01 +09:00
woppopo 00dba3a693 Make Option::as_mut const 2021-10-17 00:02:42 +09:00
Yuki Okushi 1df185ac02
Remove a mention to `copy_from_slice` from `clone_from_slice` doc 2021-10-16 17:30:34 +09:00
Stefan Lankes 2f4cbf003f remove compiler warnings 2021-10-16 09:45:05 +02:00
Matthias Krüger 8e20470425
Rollup merge of #89925 - gilescope:update-docs-atomic-usage, r=m-ou-se
updating docs to mention usage of AtomicBool

Mouse mentioned we should point out that atomic bool is used by the std lib these days. ( https://github.com/m-ou-se/getrandom/pull/1 )
2021-10-16 08:02:28 +02:00
Matthias Krüger 29f05c6220
Rollup merge of #89921 - joshuaseaton:zircon-process, r=tmandry
[fuchsia] Update process info struct

The fuchsia platform is in the process of softly transitioning over to
using a new value for ZX_INFO_PROCESS with a new corresponding struct.
This change migrates libstd.

See [fxrev.dev/510478](https://fxrev.dev/510478) and [fxbug.dev/30751](https://fxbug.dev/30751) for more detail.
2021-10-16 08:02:27 +02:00
Matthias Krüger dfed1a6c07
Rollup merge of #89898 - Amanieu:remove_alloc_prelude, r=joshtriplett
Remove alloc::prelude

As per the libs team decision in #58935.

Closes #58935
2021-10-16 08:02:21 +02:00
Matthias Krüger 9ae0804859
Rollup merge of #89509 - jhpratt:stabilize-const_unreachable_unchecked, r=oli-obk
Stabilize `unreachable_unchecked` as `const fn`

Closes #53188

This PR stabilizes `core::hint::unreachable_unchecked` as `const fn`. MIRI is able to detect when this method is called. Stabilization was delayed until `const_panic` was stabilized so as to avoid users calling this method in its place (thus resulting in runtime UB). With #89508, that is no longer an issue.

````@rustbot```` label +A-const-eval +A-const-fn +T-lang +S-blocked

(not sure why it's T-lang, but that's what the tracking issue is)
2021-10-16 08:02:20 +02:00
est31 7272b6fc8c Make char conversion functions unstably const 2021-10-16 01:20:02 +02:00
bors 6cc0a764e0 Auto merge of #85379 - mdaverde:uds-abstract, r=joshtriplett
Add abstract namespace support for Unix domain sockets

Hello! The other day I wanted to mess around with UDS in Rust and found that abstract namespaces ([unix(7)](https://man7.org/linux/man-pages/man7/unix.7.html)) on Linux still needed development. I took the approach of adding `_addr` specific public functions to reduce conflicts.

Feature name: `unix_socket_abstract`
Tracking issue: #85410
Further context: #42048

## Non-platform specific additions

`UnixListener::bind_addr(&SocketAddr) -> Result<UnixListener>`

`UnixStream::connect_addr(&SocketAddr) -> Result<()>`

`UnixDatagram::bind_addr(&SocketAddr) -> Result<UnixDatagram>`

`UnixDatagram::connect_addr(&SocketAddr) -> Result<()>`

`UnixDatagram::send_to_addr(&self, &[u8], &SocketAddr) -> Result<usize>`

## Platform-specific (Linux) additions

`SocketAddr::from_abstract_namespace(&[u8]) -> SocketAddr`

`SockerAddr::as_abstract_namespace() -> Option<&[u8]>`

## Example

```rust
#![feature(unix_socket_abstract)]
use std::os::unix::net::{UnixListener, SocketAddr};

fn main() -> std::io::Result<()> {
    let addr = SocketAddr::from_abstract_namespace(b"namespace")?; // Linux only
    let listener = match UnixListener::bind_addr(&addr) {
        Ok(sock) => sock,
        Err(err) => {
            println!("Couldn't bind: {:?}", err);
            return Err(err);
        }
    };
    Ok(())
}
```

## Further Details

The main inspiration for the implementation came from the [nix-rust](https://github.com/nix-rust/nix/blob/master/src/sys/socket/addr.rs#L558) crate but there are also other [historical](c4db0685b1) [attempts](https://github.com/tormol/uds/blob/master/src/addr.rs#L324) with similar approaches.

A comment I did have was with this change, we now allow a `SocketAddr` to be constructed explicitly rather than just used almost as a handle for the return of `peer_addr` and `local_addr`. We could consider adding other explicit constructors (e.g. `SocketAddr::from_pathname`, `SockerAddr::from_unnamed`).

Cheers!
2021-10-15 22:31:53 +00:00
Giles Cope d3bddf3ea1
updating docs to reflect current situation 2021-10-15 20:43:52 +01:00
bors c1026539bd Auto merge of #84096 - m-ou-se:windows-bcrypt-random, r=dtolnay
Use BCryptGenRandom instead of RtlGenRandom on Windows.

This removes usage of RtlGenRandom on Windows, in favour of BCryptGenRandom.

BCryptGenRandom isn't available on XP, but we dropped XP support a while ago.
2021-10-15 19:03:57 +00:00
Joshua Seaton 024baa9c32 [fuchsia] Update process info struct
The fuchsia platform is in the process of softly transitioning over to
using a new value for ZX_INFO_PROCESS with a new corresponding struct.
This change migrates libstd.

See fxrev.dev/510478 and fxbug.dev/30751 for more detail.
2021-10-15 10:40:39 -07:00
bors 265fef45f2 Auto merge of #89337 - mbrubeck:vec-leak, r=m-ou-se
Avoid allocations and copying in Vec::leak

The [`Vec::leak`] method (#62195) is currently implemented by calling `Vec::into_boxed_slice` and `Box::leak`.  This shrinks the vector before leaking it, which potentially causes a reallocation and copies the vector's contents.

By avoiding the conversion to `Box`, we can instead leak the vector without any expensive operations, just by returning a slice reference and forgetting the `Vec`.  Users who *want* to shrink the vector first can still do so by calling `shrink_to_fit` explicitly.

**Note:**  This could break code that uses `Box::from_raw` to “un-leak” the slice returned by `Vec::leak`.  However, the `Vec::leak` docs explicitly forbid this, so such code is already incorrect.

[`Vec::leak`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.leak
2021-10-15 15:55:08 +00:00
John Kugelman fb2d0f5c03 Add #[must_use] to remaining alloc functions 2021-10-15 11:46:49 -04:00
bors af9b508e1d Auto merge of #88717 - tabokie:vecdeque-fast-append, r=m-ou-se
Optimize VecDeque::append

Optimize `VecDeque::append` to do unsafe copy rather than iterating through each element.

On my `Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz`, the benchmark shows 37% improvements:
```
Master:
custom-bench vec_deque_append 583164 ns/iter
custom-bench vec_deque_append 550040 ns/iter

Patched:
custom-bench vec_deque_append 349204 ns/iter
custom-bench vec_deque_append 368164 ns/iter
```

Additional notes on the context: this is the third attempt to implement a non-trivial version of `VecDeque::append`, the last two are reverted due to unsoundness or regression, see:
- https://github.com/rust-lang/rust/pull/52553, reverted in https://github.com/rust-lang/rust/pull/53571
- https://github.com/rust-lang/rust/pull/53564, reverted in https://github.com/rust-lang/rust/pull/54851

Both cases are covered by existing tests.

Signed-off-by: tabokie <xy.tao@outlook.com>
2021-10-15 12:51:31 +00:00
Mara Bos 1ed123828c Use BCryptGenRandom instead of RtlGenRandom on Windows.
BCryptGenRandom isn't available on XP, but we dropped XP support a while
ago.
2021-10-15 13:22:28 +02:00
bors 1dafe6d1c3 Auto merge of #88540 - ibraheemdev:swap-unchecked, r=kennytm
add `slice::swap_unchecked`

An unsafe version of `slice::swap` that does not do bounds checking.
2021-10-15 09:35:45 +00:00
Matthias Krüger 4457014398 Revert "Auto merge of #89709 - clemenswasser:apply_clippy_suggestions_2, r=petrochenkov"
The PR had some unforseen perf regressions that are not as easy to find.
Revert the PR for now.

This reverts commit 6ae8912a3e, reversing
changes made to 86d6d2b738.
2021-10-15 11:28:23 +02:00
lcnr 80fe0bb76e add a `rustc::query_stability` lint 2021-10-15 10:58:18 +02:00
Amanieu d'Antras 8007dfa3b2 Remove alloc::prelude
As per the libs team decision in #58935.

Closes #58935
2021-10-15 01:41:31 +02:00
Matthias Krüger d6eff5ac4c
Rollup merge of #89878 - GuillaumeGomez:add-missing-cfg-hide, r=notriddle
Fix missing remaining compiler specific cfg information

Follow-up of #89596. We forgot a few of them:

![Screenshot from 2021-10-14 11-36-44](https://user-images.githubusercontent.com/3050060/137292700-64ebc59f-d9d2-41f2-be3a-fa5bf211523c.png)
![Screenshot from 2021-10-14 11-36-56](https://user-images.githubusercontent.com/3050060/137292703-f63fa4e5-2c56-446b-9f86-3652f03dfe59.png)

r? `@notriddle`
2021-10-14 16:06:47 +02:00
Matthias Krüger 686857f5bf
Rollup merge of #89873 - askoufis:patch-1, r=Mark-Simulacrum
Add missing word to `FromStr` trait documentation

The doc comment is getting a bit wide, let me know if I should restructure it/add a new line.
2021-10-14 16:06:46 +02:00
Matthias Krüger d177791791
Rollup merge of #89433 - arlosi:stdin-fix, r=joshtriplett
Fix ctrl-c causing reads of stdin to return empty on Windows.

Pressing ctrl+c (or ctrl+break) on Windows caused a blocking read of stdin to unblock and return empty, unlike other platforms which continue to block.

On ctrl-c, `ReadConsoleW` will return success, but also set `LastError` to `ERROR_OPERATION_ABORTED`.

This change detects this case, and re-tries the call to `ReadConsoleW`.

Fixes #89177. See issue for further details.

Tested on Windows 7 and Windows 10 with both MSVC and GNU toolchains
2021-10-14 16:06:44 +02:00
Ibraheem Ahmed cf12732a38
don't duplicate slice `panic_bounds_check` 2021-10-14 09:31:34 -04:00
bors c34ac8747c Auto merge of #89247 - fee1-dead:const-eval-select, r=oli-obk
Add `const_eval_select` intrinsic

Adds an intrinsic that calls a given function when evaluated at compiler time, but generates a call to another function when called at runtime.

See https://github.com/rust-lang/const-eval/issues/7 for previous discussion.

r? `@oli-obk.`
2021-10-14 10:06:30 +00:00
Guillaume Gomez 30a20f8c83 Fix missing remaining compiler specific cfg information 2021-10-14 11:39:30 +02:00
Sean Young 1bb399c342 Ensure that pushing empty path works as before
Fixes: https://github.com/rust-lang/rust/issues/89658
2021-10-14 08:59:28 +01:00
Deadbeef 26b78ccd31
Fix const stability 2021-10-14 07:07:34 +00:00
Deadbeef 6770dbd4b5
Avoid tupling at the callee 2021-10-14 06:18:53 +00:00
Adam Skoufis 4b59b35b76
Add missing word to `FromStr` trait docs 2021-10-14 13:47:54 +11:00
Matthias Krüger 06110c0c46
Rollup merge of #89670 - yoshuawuyts:available-parallelism-docs, r=joshtriplett
Improve `std:🧵:available_parallelism` docs

_Tracking issue: https://github.com/rust-lang/rust/issues/74479_

This PR reworks the documentation of `std:🧵:available_parallelism`, as requested [here](https://github.com/rust-lang/rust/pull/89324#issuecomment-934343254).

## Changes

The following changes are made:

- We've removed prior mentions of "hardware threads" and instead centers the docs around "parallelism" as a resource available to a program.
- We now provide examples of when `available_parallelism` may return numbers that differ from the number of CPU cores in the host machine.
- We now mention that the amount of available parallelism may change over time.
- We make note of which platform components we don't take into account which more advanced users may want to take note of.
- The example has been updated, which should be a bit easier to use.
- We've added a docs alias to `num-cpus` which provides similar functionality to `available_parallelism`, and is one of the most popular crates on crates.io.

---

Thanks!

r? `@BurntSushi`
2021-10-13 22:51:01 +02:00
Yoshua Wuyts 21429eda2d Improve `std:🧵:available_parallelism` docs 2021-10-13 17:57:05 +02:00
Yuki Okushi 59ebfdd7e0
Rollup merge of #89817 - m-ou-se:int-log-10-inline, r=the8472
Add #[inline] to int log10 functions.
2021-10-13 21:55:16 +09:00
Yuki Okushi 06e4aee220
Rollup merge of #89814 - jkugelman:must-use-string-transforms-typo, r=joshtriplett
Fix uppercase/lowercase error

Fix https://github.com/rust-lang/rust/pull/89694#discussion_r726829890

r? ````@joshtriplett````
2021-10-13 21:55:14 +09:00
Yuki Okushi c1bde6e4b6
Rollup merge of #89794 - jkugelman:must-use-to_value-conversions, r=joshtriplett
Add #[must_use] to to_value conversions

`NonNull<T>::cast` snuck in when I wasn't looking. What a scamp!

Parent issue: #89692

r? ````@joshtriplett````
2021-10-13 21:55:13 +09:00
Yuki Okushi f759fff447
Rollup merge of #89781 - Wilfred:patch-2, r=JohnTitor
Add missing words in `Infallible` docs

This sentence was previously incomplete.
2021-10-13 21:55:11 +09:00
John Kugelman 21f4677744 Add #[must_use] to expensive computations
The unifying theme for this commit is weak, admittedly. I put together a
list of "expensive" functions when I originally proposed this whole
effort, but nobody's cared about that criterion. Still, it's a decent
way to bite off a not-too-big chunk of work.

Given the grab bag nature of this commit, the messages I used vary quite
a bit.
2021-10-12 23:27:17 -04:00
bors ef4b3069ba Auto merge of #89774 - the8472:inline-mut-iter-next, r=m-ou-se
inline next() on &mut Iterator impl

In [#87431](https://github.com/rust-lang/rust/pull/87431/files#diff-79a6b417b85ecf4f1a4ef2235135fedf540199caf6e9e1d154ac6a413b40a757R132-R136)   I found that `(&mut range).fold` doesn't optimize well because the default impl for for `fold` on `&mut Iterator` doesn't inline `next`. In that particular case it was worked around by using `try_fold` which takes a `&mut self` instead of `self`.

Let's see if this can be fixed more broadly.
2021-10-12 23:59:48 +00:00
John Kugelman 5bb99bb02d Add #[must_use] to Rc::downgrade 2021-10-12 18:53:56 -04:00
Max Wase 3e0360f3d4
Merge branch 'master' into is-symlink-stabilization 2021-10-13 01:33:12 +03:00
John Kugelman 6a8311cbfd
Update library/std/src/thread/mod.rs
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2021-10-12 10:48:27 -04:00
Mara Bos a6bb1fb641 Add #[inline] to int log10 functions. 2021-10-12 15:21:14 +02:00
Mara Bos df15b289f3 Remove potentially unsound note on reconstructing a leaked Vec. 2021-10-12 15:02:52 +02:00
John Kugelman 81eeb3e775 Fix uppercase/lowercase error 2021-10-12 08:53:54 -04:00
the8472 7017410e5d
Rollup merge of #89799 - ast-ral:ready-method-spellck, r=joshtriplett
fix minor spelling error in Poll::ready docs

Fixes minor spelling error in the proposed `Poll::ready` docs. Not that my opinion matters, but +1 on the original PR (#89651), it reads much nicer to me than the `ready!` macro.
2021-10-12 14:53:11 +02:00
the8472 4cf0f1fede
Rollup merge of #89797 - jkugelman:must-use-is_condition-tests, r=joshtriplett
Add #[must_use] to is_condition tests

I threw in `std::path::Path::has_root` for funsies.

A continuation of #89718.

Parent issue: #89692

r? ```@joshtriplett```
2021-10-12 14:53:11 +02:00
the8472 a1bdd48106
Rollup merge of #89796 - jkugelman:must-use-non-mutating-verb-methods, r=joshtriplett
Add #[must_use] to non-mutating verb methods

These are methods that could be misconstrued to mutate their input, similar to #89694. I gave each one a different custom message.

I wrote that `upgrade` and `downgrade` don't modify the input pointers. Logically they don't, but technically they do...

Parent issue: #89692

r? ```@joshtriplett```
2021-10-12 14:53:10 +02:00
the8472 b55a3c5d15
Rollup merge of #89778 - jkugelman:must-use-as_type-conversions, r=joshtriplett
Add #[must_use] to as_type conversions

Clippy missed these:

```rust
alloc::string::String   fn as_mut_str(&mut self) -> &mut str;
core::mem::NonNull<T>   unsafe fn as_uninit_mut<'a>(&mut self) -> &'a MaybeUninit<T>;
str                     unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
str                     fn as_mut_ptr(&mut self) -> *mut u8;
```

Parent issue: #89692

r? ````@joshtriplett````
2021-10-12 14:53:08 +02:00
Mara Bos 129af049fe Mention Rust version in Vec::leak docs. 2021-10-12 14:50:46 +02:00
bors 9475e609b8 Auto merge of #89770 - jkugelman:must-use-from-and-into, r=joshtriplett
Add #[must_use] to From::from and Into::into

Risk of churn: **High**
Magic 8-Ball says: **Outlook not so good**

I figured I'd put this out there. If we don't do it now maybe we save it for a rainy day.

Parent issue: #89692

r? `@joshtriplett`
2021-10-12 09:43:37 +00:00
bors 02f2b31e61 Auto merge of #89769 - jkugelman:must-use-maybe-uninit-new, r=joshtriplett
Add #[must_use] to MaybeUninit::new

As discussed in https://github.com/rust-lang/rust/pull/89729#issuecomment-939775659.

Parent issue: #89692

r? `@joshtriplett`
2021-10-12 07:02:53 +00:00
Deadbeef 5387b6542f
Add const_eval_select intrinsic 2021-10-12 05:42:23 +00:00
Max Wase 36e050b85f
Update library/std/src/path.rs
Co-authored-by: Jane Lusby <jlusby42@gmail.com>
2021-10-12 08:01:24 +03:00
ast-ral 5100630dcd
fix minor spelling error in Poll::ready docs 2021-10-11 21:00:02 -07:00
bors ffdf18d144 Auto merge of #88788 - falk-hueffner:speedup-int-log10-branchless, r=joshtriplett
Speedup int log10 branchless

This is achieved with a branchless bit-twiddling implementation of the case x < 100_000, and using this as building block.

Benchmark on an Intel i7-8700K (Coffee Lake):

```
name                                   old ns/iter  new ns/iter  diff ns/iter   diff %  speedup
num::int_log::u8_log10_predictable     165          169                     4    2.42%   x 0.98
num::int_log::u8_log10_random          438          423                   -15   -3.42%   x 1.04
num::int_log::u8_log10_random_small    438          423                   -15   -3.42%   x 1.04
num::int_log::u16_log10_predictable    633          417                  -216  -34.12%   x 1.52
num::int_log::u16_log10_random         908          471                  -437  -48.13%   x 1.93
num::int_log::u16_log10_random_small   945          471                  -474  -50.16%   x 2.01
num::int_log::u32_log10_predictable    1,496        1,340                -156  -10.43%   x 1.12
num::int_log::u32_log10_random         1,076        873                  -203  -18.87%   x 1.23
num::int_log::u32_log10_random_small   1,145        874                  -271  -23.67%   x 1.31
num::int_log::u64_log10_predictable    4,005        3,171                -834  -20.82%   x 1.26
num::int_log::u64_log10_random         1,247        1,021                -226  -18.12%   x 1.22
num::int_log::u64_log10_random_small   1,265        921                  -344  -27.19%   x 1.37
num::int_log::u128_log10_predictable   39,667       39,579                -88   -0.22%   x 1.00
num::int_log::u128_log10_random        6,456        6,696                 240    3.72%   x 0.96
num::int_log::u128_log10_random_small  4,108        3,903                -205   -4.99%   x 1.05
```

Benchmark on an M1 Mac Mini:

```
name                                   old ns/iter  new ns/iter  diff ns/iter   diff %  speedup
num::int_log::u8_log10_predictable     143          130                   -13   -9.09%   x 1.10
num::int_log::u8_log10_random          375          325                   -50  -13.33%   x 1.15
num::int_log::u8_log10_random_small    376          325                   -51  -13.56%   x 1.16
num::int_log::u16_log10_predictable    500          322                  -178  -35.60%   x 1.55
num::int_log::u16_log10_random         794          405                  -389  -48.99%   x 1.96
num::int_log::u16_log10_random_small   1,035        405                  -630  -60.87%   x 2.56
num::int_log::u32_log10_predictable    1,144        894                  -250  -21.85%   x 1.28
num::int_log::u32_log10_random         832          786                   -46   -5.53%   x 1.06
num::int_log::u32_log10_random_small   832          787                   -45   -5.41%   x 1.06
num::int_log::u64_log10_predictable    2,681        2,057                -624  -23.27%   x 1.30
num::int_log::u64_log10_random         1,015        806                  -209  -20.59%   x 1.26
num::int_log::u64_log10_random_small   1,004        795                  -209  -20.82%   x 1.26
num::int_log::u128_log10_predictable   56,825       56,526               -299   -0.53%   x 1.01
num::int_log::u128_log10_random        9,056        8,861                -195   -2.15%   x 1.02
num::int_log::u128_log10_random_small  1,528        1,527                  -1   -0.07%   x 1.00
```

The 128 bit case remains ridiculously slow because llvm fails to optimize division by a constant 128-bit value to multiplications. This could be worked around but it seems preferable to fix this in llvm.

From u32 up, table lookup (like suggested [here](https://github.com/rust-lang/rust/issues/70887#issuecomment-881099813)) is still faster, but requires a hardware `leading_zeros` to be viable, and might clog up the cache.
2021-10-12 03:18:54 +00:00
John Kugelman c3f0577002 Add #[must_use] to non-mutating verb methods 2021-10-11 21:21:32 -04:00