Commit graph

1777 commits

Author SHA1 Message Date
Yuki Okushi 9085656512
Rollup merge of #78322 - ssomers:btree_no_min_len_at_node_level, r=Mark-Simulacrum
BTreeMap: stop mistaking node::MIN_LEN for a node level constraint

Correcting #77612 that fell into the trap of assuming that node::MIN_LEN is an imposed minimum everywhere, and trying to make it much more clear it is an offered minimum at the node level.

r? @Mark-Simulacrum
2020-10-25 18:43:47 +09:00
Yuki Okushi 3e017c709d
Rollup merge of #78276 - cutsoy:bump-backtrace, r=nagisa
Bump backtrace-rs to enable Mach-O support on iOS.

Related to rust-lang/backtrace-rs#378. Fixes backtraces on iOS that were missing in Rust v1.47.0 after switching to gimli because it only enabled Mach-O support on macOS.
2020-10-25 18:43:44 +09:00
Yuki Okushi 72e02b015e
Rollup merge of #78208 - liketechnik:issue-69399, r=oli-obk
replace `#[allow_internal_unstable]` with `#[rustc_allow_const_fn_unstable]` for `const fn`s

`#[allow_internal_unstable]` is currently used to side-step feature gate and stability checks.
While it was originally only meant to be used only on macros, its use was expanded to `const fn`s.

This pr adds stricter checks for the usage of `#[allow_internal_unstable]` (only on macros) and introduces the `#[rustc_allow_const_fn_unstable]` attribute for usage on `const fn`s.

This pr does not change any of the functionality associated with the use of `#[allow_internal_unstable]` on macros or the usage of `#[rustc_allow_const_fn_unstable]` (instead of `#[allow_internal_unstable]`) on `const fn`s (see https://github.com/rust-lang/rust/issues/69399#issuecomment-712911540).

Note: The check for `#[rustc_allow_const_fn_unstable]` currently only validates that the attribute is used on a function, because I don't know how I would check if the function is a `const fn` at the place of the check. I therefore openend this as a 'draft pull request'.

Closes rust-lang/rust#69399

r? @oli-obk
2020-10-25 18:43:40 +09:00
Jonas Schievink e3808edeee
Rollup merge of #78119 - fusion-engineering-forks:panic-use-as-str, r=Amanieu
Throw core::panic!("message") as &str instead of String.

This makes `core::panic!("message")` consistent with `std::panic!("message")`, which throws a `&str` and not a `String`.

This also makes any other panics from `core::panicking::panic` result in a `&str` rather than a `String`, which includes compiler-generated panics such as the panics generated for `mem::zeroed()`.

---

Demonstration:

```rust
use std::panic;
use std::any::Any;

fn main() {
    panic::set_hook(Box::new(|panic_info| check(panic_info.payload())));

    check(&*panic::catch_unwind(|| core::panic!("core")).unwrap_err());
    check(&*panic::catch_unwind(|| std::panic!("std")).unwrap_err());
}

fn check(msg: &(dyn Any + Send)) {
    if let Some(s) = msg.downcast_ref::<String>() {
        println!("Got a String: {:?}", s);
    } else if let Some(s) = msg.downcast_ref::<&str>() {
        println!("Got a &str: {:?}", s);
    }
}
```

Before:
```
Got a String: "core"
Got a String: "core"
Got a &str: "std"
Got a &str: "std"
```

After:
```
Got a &str: "core"
Got a &str: "core"
Got a &str: "std"
Got a &str: "std"
```
2020-10-24 22:39:53 +02:00
Jonas Schievink 0a06d7344b
Rollup merge of #78069 - fusion-engineering-forks:core-const-panic-str, r=RalfJung
Fix const core::panic!(non_literal_str).

Invocations of `core::panic!(x)` where `x` is not a string literal expand to `panic!("{}", x)`, which is not understood by the const panic logic right now. This adds `panic_str` as a lang item, and modifies the const eval implementation to hook into this item as well.

This fixes the issue mentioned here: https://github.com/rust-lang/rust/issues/51999#issuecomment-687604248

r? `@RalfJung`

`@rustbot` modify labels: +A-const-eval
2020-10-24 22:39:49 +02:00
Jonas Schievink e34263d86a
Rollup merge of #77610 - hermitcore:dtors, r=m-ou-se
revise Hermit's mutex interface to support the behaviour of StaticMutex

rust-lang/rust#77147 simplifies things by splitting this Mutex type into two types matching the two use cases: StaticMutex and MovableMutex. To support the new behavior of StaticMutex, we move part of the mutex implementation into libstd.

The interface to the OS changed. Consequently, I removed a few functions, which aren't longer needed.
2020-10-24 22:39:44 +02:00
Jonas Schievink a547055184
Rollup merge of #76614 - NoraCodes:nora/control_flow_enum, r=scottmcm
change the order of type arguments on ControlFlow

This allows ControlFlow<BreakType> which is much more ergonomic for common iterator combinator use cases.

Addresses one component of #75744
2020-10-24 22:39:41 +02:00
Jonas Schievink 01a38f0d9a
Rollup merge of #75115 - chansuke:sys-cloudabi-unsafe, r=KodrAus
`#[deny(unsafe_op_in_unsafe_fn)]` in sys/cloudabi

Partial fix of #73904.

This encloses unsafe operations in unsafe fn in sys/cloudabi.
2020-10-24 22:39:35 +02:00
Stein Somers 3b6c4fe465 BTreeMap: stop mistaking node::MIN_LEN as a node level constraint 2020-10-24 15:24:37 +02:00
Jonas Schievink eaa982305d
Rollup merge of #78274 - Enet4:patch-1, r=jonas-schievink
Update description of Empty Enum for accuracy

An empty enum is similar to the never type `!`, rather than the unit type `()`.
2020-10-24 14:12:11 +02:00
Jonas Schievink d9acd7d148
Rollup merge of #78109 - cuviper:exhausted-rangeinc, r=dtolnay
Check for exhaustion in RangeInclusive::contains and slicing

When a range has finished iteration, `is_empty` returns true, so it
should also be the case that `contains` returns false.

Fixes #77941.
2020-10-24 14:12:01 +02:00
Jonas Schievink d7c635b3a5
Rollup merge of #77392 - Canop:option_insert, r=m-ou-se
add `insert` to `Option`

This removes a cause of `unwrap` and code complexity.

This allows replacing

```
option_value = Some(build());
option_value.as_mut().unwrap()
```

with

```
option_value.insert(build())
```

It's also useful in contexts not requiring the mutability of the reference.

Here's a typical cache example:

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => {
	    cache = Some(compute_cache_entry());
	    // unwrap is OK because we just filled the option
	    &cache.as_ref().unwrap().content
	}
};
```

It can be changed into

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => &cache.insert(compute_cache_entry()).content,
};
```

*(edited: I removed `insert_with`)*
2020-10-24 14:11:57 +02:00
chansuke d37b8cf729 Remove unnecessary unsafe block from condvar_atomics & mutex_atomics 2020-10-24 18:22:18 +09:00
chansuke d147f78e36 Fix unsafe operation of wasm32::memory_atomic_notify 2020-10-24 18:14:17 +09:00
chansuke de87ae7961 Add documents for DLMALLOC 2020-10-24 17:59:58 +09:00
chansuke eed45107da Add some description for (malloc/calloc/free/realloc) 2020-10-24 11:50:09 +09:00
chansuke d413bb6f57 #[deny(unsafe_op_in_unsafe_fn)] in sys/wasm 2020-10-24 11:50:09 +09:00
Tim Diekmann 693a2bf18b Rename Box::alloc to Box::alloc_ref 2020-10-23 22:45:15 +02:00
Nicolas Nattis 929f80ece9 Add a spin loop hint for Arc::downgrade 2020-10-23 16:10:56 -03:00
Tim 7d30c53656
Bump backtrace-rs to enable Mach-O support on iOS. 2020-10-23 13:47:09 +02:00
Eduardo Pinho efedcb2344
Update description of Empty Enum for accuracy
An empty enum is similar to the never type `!`, rather than the unit type `()`.
2020-10-23 12:13:07 +01:00
Canop 216d0fe364 add tracking issue number to option_insert feature gate 2020-10-23 11:44:58 +02:00
Canop 415a8e526d Update library/core/src/option.rs
Co-authored-by: Ivan Tham <pickfire@riseup.net>
2020-10-23 11:41:19 +02:00
Canop 39557799c7 Update library/core/src/option.rs
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2020-10-23 11:41:19 +02:00
Canop cc8b77a7cf fix naming unconsistency between function doc and prototype 2020-10-23 11:41:19 +02:00
Canop 60a96cae33 more tests in option.insert, code cleaning in option
Code cleaning made according to suggestions in discussion
on PR ##77392 impacts insert, get_or_insert and get_or_insert_with.
2020-10-23 11:41:19 +02:00
Canop e8df2a4269 remove option.insert_with
`option.insert` covers both needs anyway, `insert_with` is
redundant.
2020-10-23 11:41:19 +02:00
Canop 9b90e1762e add insert and insert_with to Option
This removes a cause of `unwrap` and code complexity.

This allows replacing

```
option_value = Some(build());
option_value.as_mut().unwrap()
```

with

```
option_value.insert(build())
```

or

```
option_value.insert_with(build)
```

It's also useful in contexts not requiring the mutability of the reference.

Here's a typical cache example:

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => {
	    cache = Some(compute_cache_entry());
	    // unwrap is OK because we just filled the option
	    &cache.as_ref().unwrap().content
	}
};
```

It can be changed into

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => &cache.insert_with(compute_cache_entry).content,
};
```
2020-10-23 11:41:19 +02:00
Yuki Okushi dfb0d09bae
Rollup merge of #78163 - camelid:fixup-lib-docs, r=m-ou-se
Clean up lib docs

Cherry-picked out of #78094.
2020-10-23 18:26:33 +09:00
Yuki Okushi 39f8289e38
Rollup merge of #77969 - ryan-scott-dev:bigo-notation-consistency, r=m-ou-se
Doc formating consistency between slice sort and sort_unstable, and big O notation consistency

Updated documentation for slice sorting methods to be consistent between stable and unstable versions, which just ended up being minor formatting differences.

I also went through and updated any doc comments with big O notation to be consistent with #74010 by italicizing them rather than having them in a code block.
2020-10-23 18:26:26 +09:00
Yuki Okushi b968738348
Rollup merge of #77918 - wcampbell0x2a:cleanup-network-tests, r=m-ou-se
Cleanup network tests

Some cleanup for network related tests
2020-10-23 18:26:22 +09:00
Yuki Okushi 4859786c69
Rollup merge of #77890 - gilescope:welformed-json-output-from-libtest, r=KodrAus
Fixing escaping to ensure generation of welformed json.

doc tests' json name have a filename in them. When json test output is asked for on windows currently produces invalid json.
Tracking issue for json test output: #49359
2020-10-23 18:26:20 +09:00
Yuki Okushi 8e373304ed
Rollup merge of #77339 - fusion-engineering-forks:tryfrom-nonzero-to-nonzero, r=dtolnay
Implement TryFrom between NonZero types.

This will instantly be stable, as trait implementations for stable types and traits can not be `#[unstable]`.

Closes #77258.

@rustbot modify labels: +T-libs
2020-10-23 18:26:16 +09:00
Sergio Benitez db15596c57 Only load LOCAL_STREAMS if they are being used 2020-10-22 18:15:48 -07:00
Tyler Mandry d0d0e78208 Capture output from threads spawned in tests
Fixes #42474.
2020-10-22 18:15:44 -07:00
Leonora Tindall 84daccc559 change the order of type arguments on ControlFlow
This allows ControlFlow<BreakType> which is much more ergonomic for
common iterator combinator use cases.
2020-10-22 17:26:48 -07:00
Camelid 13bc087a73 Clean up lib docs 2020-10-22 10:36:35 -07:00
Mara Bos 4f7ffbf351 Fix const core::panic!(non_literal_str). 2020-10-22 18:41:35 +02:00
Stein Somers 2c5f64f683 BTreeMap/Set: merge the implementations of MergeIter 2020-10-22 09:39:24 +02:00
Yuki Okushi 69e0658f41
Rollup merge of #78200 - LeSeulArtichaut:controlflow-is-meth, r=scottmcm
Add `ControlFlow::is_{break,continue}` methods

r? @scottmcm cc #75744
2020-10-22 09:45:45 +09:00
Yuki Okushi 6bfbc24645
Rollup merge of #78188 - fusion-engineering-forks:static-ref-tracking-issue, r=withoutboats
Add tracking issue number for pin_static_ref

Forgot to add a tracking issue in #77726. Opened #78186 as tracking issue.
2020-10-22 09:45:43 +09:00
varkor 878c97e70c Update to rustc-demangle 0.1.18 2020-10-21 21:11:11 +01:00
varkor 2b9d22d3a9 Update rustc-demangle 2020-10-21 21:05:38 +01:00
LeSeulArtichaut d25c97a3f8 Add ControlFlow::is_{break,continue} methods 2020-10-21 21:50:08 +02:00
Florian Warzecha 05f4a9a42a
switch allow_internal_unstable const fns to rustc_allow_const_fn_unstable 2020-10-21 20:54:20 +02:00
Mara Bos 51de5908c9 Add tracking issue number for pin_static_ref. 2020-10-21 16:30:41 +02:00
Marc-Antoine Perennou 66fa42a946 allow using the system-wide llvm-libunwind as the unwinder
Signed-off-by: Marc-Antoine Perennou <Marc-Antoine@Perennou.com>
2020-10-21 14:45:58 +02:00
Yuki Okushi 89c98cd6b4
Rollup merge of #78063 - camelid:improve-cannot-multiply-error, r=estebank
Improve wording of "cannot multiply" type error

For example, if you had this code:

    fn foo(x: i32, y: f32) -> f32 {
        x * y
    }

You would get this error:

    error[E0277]: cannot multiply `f32` to `i32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`

However, that's not usually how people describe multiplication. People
usually describe multiplication like how the division error words it:

    error[E0277]: cannot divide `i32` by `f32`
     --> src/lib.rs:2:7
      |
    2 |     x / y
      |       ^ no implementation for `i32 / f32`
      |
      = help: the trait `Div<f32>` is not implemented for `i32`

So that's what this change does. It changes this:

    error[E0277]: cannot multiply `f32` to `i32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`

To this:

    error[E0277]: cannot multiply `i32` by `f32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`
2020-10-21 13:59:39 +09:00
Yuki Okushi f8bae8b102
Rollup merge of #78056 - ssomers:btree_chop_up_1, r=dtolnay
BTreeMap: split off most code of remove and split_off

Putting map.rs on a diet, in addition to #77851.
r? @dtolnay
2020-10-21 13:59:37 +09:00
Yuki Okushi ff3c8cb518
Rollup merge of #77726 - fusion-engineering-forks:static-pin, r=dtolnay
Add Pin::static_ref, static_mut.

This adds `Pin::static_ref` and `Pin::static_mut`, which convert a static reference to a pinned static reference.

Static references are effectively already pinned, as what they refer to has to live forever and can never be moved.

---

Context: I want to update the `sys` and `sys_common` mutexes/rwlocks/condvars to use `Pin<&self>` in their functions, instead of only warning in the unsafety comments that they may not be moved. That should make them a little bit less dangerous to use. Putting such an object in a `static` (e.g. through `sys_common::StaticMutex`) fulfills the requirements about never moving it, but right now there's no safe way to get a `Pin<&T>` to a `static`. This solves that.
2020-10-21 13:59:29 +09:00
Josh Stone 9202fbdbdb Check for exhaustion in SliceIndex for RangeInclusive 2020-10-20 17:18:08 -07:00
bors f965120ad3 Auto merge of #77244 - ssomers:btree_love_the_leaf_edge, r=Mark-Simulacrum
BTreeMap: more refactoring around edges

Continuation of #77005.

r? `@Mark-Simulacrum`
2020-10-20 23:33:56 +00:00
Guillaume Gomez adda858356
Rollup merge of #78129 - mbartlett21:patch-1, r=kennytm
Wrapping intrinsics doc links update.

The links in the wrapping intrinsics docs now refer to the `wrapping_*` functions, not the `checked_*` functions.
2020-10-20 21:46:37 +02:00
Stein Somers 76c466a18f BTreeMap: less sharing, more similarity between leaf and internal nodes 2020-10-20 15:13:57 +02:00
Stein Somers 7829e18899 BTreeMap: reuse BoxedNode instances directly instead of their contents 2020-10-20 13:58:11 +02:00
mbartlett21 061cf5363c
Wrapping intrinsics update link
Now refers to `wrapping_*`, not `checked_*` for wrapping intrinsics.
2020-10-20 14:09:01 +10:00
Yuki Okushi 6df79bf8a8
Rollup merge of #77923 - wcampbell0x2a:cleanup-net-module, r=scottmcm
[net] apply clippy lints

Applied helpful clippy lints to the network std library module.
2020-10-20 12:11:04 +09:00
Yuki Okushi f9db00839e
Rollup merge of #77838 - RalfJung:const-fn, r=kennytm
const keyword: brief paragraph on 'const fn'

`const fn` were mentioned in the title, but called "deterministic functions" which is not their main property (though at least currently it is a consequence of being const-evaluable). This adds a brief paragraph discussing them, also in the hopes of clarifying that they do *not* have any effect on run-time uses.
2020-10-20 12:11:02 +09:00
Yuki Okushi b09ef114bb
Rollup merge of #77761 - tmiasko:pthread-mutex, r=cuviper
Assert that pthread mutex initialization succeeded

If pthread mutex initialization fails, the failure will go unnoticed unless
debug assertions are enabled. Any subsequent use of mutex will also silently
fail, since return values from lock & unlock operations are similarly checked
only through debug assertions.

In some implementations the mutex initialization requires a memory
allocation and so it does fail in practice.

Assert that initialization succeeds to ensure that mutex guarantees
mutual exclusion.

Fixes #34966.
2020-10-20 12:10:58 +09:00
Yuki Okushi c5b0a88669
Rollup merge of #77612 - ssomers:btree_cleanup_2, r=Mark-Simulacrum
BTreeMap: test invariants more thoroughly and more readably

r? @Mark-Simulacrum
2020-10-20 12:10:52 +09:00
Tomasz Miąsko 21c29b1e95 Check that pthread mutex initialization succeeded
If pthread mutex initialization fails, the failure will go unnoticed unless
debug assertions are enabled. Any subsequent use of mutex will also silently
fail, since return values from lock & unlock operations are similarly checked
only through debug assertions.

In some implementations the mutex initialization requires a memory
allocation and so it does fail in practice.

Check that initialization succeeds to ensure that mutex guarantees
mutual exclusion.
2020-10-20 00:00:00 +00:00
Josh Stone 9fd79a3904 make exhausted RangeInclusive::end_bound return Excluded(end) 2020-10-19 13:46:30 -07:00
Mara Bos 2780e35246 Throw core::panic!("message") as &str instead of String.
This makes it consistent with std::panic!("message"), which also throws
a &str, not a String.
2020-10-19 22:31:11 +02:00
Josh Stone b62b352f47 Check for exhaustion in RangeInclusive::contains
When a range has finished iteration, `is_empty` returns true, so it
should also be the case that `contains` returns false.
2020-10-19 10:02:51 -07:00
Guillaume Gomez 81180f4d99
Rollup merge of #78099 - pierwill:patch-5, r=jonas-schievink
Add missing punctuation
2020-10-19 18:20:24 +02:00
Guillaume Gomez a6919ef889
Rollup merge of #77877 - scottmcm:fewer-try-trait-method-references, r=shepmaster
Use `try{}` in `try_fold` to decouple iterators in the library from `Try` details

I'd like to experiment with changing the `?`/`try` desugaring and correspondingly the `Try` trait (see #42327 for discussions about the suboptimalities of the current one) and this change would keep from needing any `cfg(bootstrap)` in iterator things.

This will be lowered to the same thing, so shouldn't cause any perf issues:
08e2d46166/compiler/rustc_ast_lowering/src/expr.rs (L428-L429)

But ~~I'll trigger~~ I've triggered [a perf run](https://perf.rust-lang.org/compare.html?start=d65c08e9cc164b7b44de53503fae859a4fafd976&end=2c067c5235e779cd75e9f0cdfe572c64f1a12b9b) just in case.

~~EDIT: changed to a draft because of the rustfmt-only syntax error.  zulip thread about it: https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/New.20bootstrap.20rustfmt.20doesn't.20support.20syntax.20from.20sept.3F/near/213098097~~

EDIT: This now includes a rustfmt version bump to get through tidy.
2020-10-19 18:20:20 +02:00
wcampbell 736c27ec0b Revert "[net] clippy: needless_update"
This reverts commit 058699d0a2.
2020-10-19 07:22:45 -04:00
Stein Somers 488b999fc2 BTreeMap: test invariants more thoroughly and more readably 2020-10-19 11:36:39 +02:00
pierwill 67dc9b7581
Add missing punctuation 2020-10-18 23:03:16 -07:00
bors e42cbe8edc Auto merge of #77874 - camelid:range-docs-readability, r=scottmcm
Improve range docs

* Improve code formatting and legibility
* Various other readability improvements
2020-10-19 00:11:08 +00:00
Camelid a885c5008c Improve range docs
* Mention that `RangeFull` is a ZST and thus a singleton
* Improve code formatting and legibility
* Various other readability improvements
2020-10-18 16:02:08 -07:00
bors b1496c6e60 Auto merge of #78075 - est31:remove_redundant_static, r=jonas-schievink
Remove redundant 'static
2020-10-18 21:02:05 +00:00
bors 187b8771dc Auto merge of #76885 - dylni:move-slice-check-range-to-range-bounds, r=KodrAus
Move `slice::check_range` to `RangeBounds`

Since this method doesn't take a slice anymore (#76662), it makes more sense to define it on `RangeBounds`.

Questions:
- Should the new method be `assert_len` or `assert_length`?
2020-10-18 18:50:43 +00:00
est31 a687420d17 Remove redundant 'static from library crates 2020-10-18 17:25:51 +02:00
Stein Somers 003516f91a BTreeMap: split off most code of remove and split_off 2020-10-18 13:13:23 +02:00
chansuke d3467fe520 #[deny(unsafe_op_in_unsafe_fn)] in sys/cloudabi 2020-10-18 17:59:54 +09:00
Camelid 7b33ae642e Improve wording of "cannot multiply" type error
For example, if you had this code:

    fn foo(x: i32, y: f32) -> f32 {
        x * y
    }

You would get this error:

    error[E0277]: cannot multiply `f32` to `i32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`

However, that's not usually how people describe multiplication. People
usually describe multiplication like how the division error words it:

    error[E0277]: cannot divide `i32` by `f32`
     --> src/lib.rs:2:7
      |
    2 |     x / y
      |       ^ no implementation for `i32 / f32`
      |
      = help: the trait `Div<f32>` is not implemented for `i32`

So that's what this change does. It changes this:

    error[E0277]: cannot multiply `f32` to `i32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`

To this:

    error[E0277]: cannot multiply `i32` by `f32`
     --> src/lib.rs:2:7
      |
    2 |     x * y
      |       ^ no implementation for `i32 * f32`
      |
      = help: the trait `Mul<f32>` is not implemented for `i32`
2020-10-17 22:19:25 -07:00
bors c38ddb8040 Auto merge of #74480 - yoshuawuyts:hardware_threads, r=dtolnay
Add std:🧵:available_concurrency

This PR adds a counterpart to [C++'s `std:🧵:hardware_concurrency`](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) to Rust, tracking issue https://github.com/rust-lang/rust/issues/74479.

cc/ `@rust-lang/libs`

## Motivation

Being able to know how many hardware threads a platform supports is a core part of building multi-threaded code. In C++ 11 this has become available through the [`std:🧵:hardware_concurrency`](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) API. Currently in Rust most of the ecosystem depends on the [`num_cpus` crate](https://docs.rs/num_cpus/1.13.0/num_cpus/) ([no.35 in top 500 crates](https://docs.google.com/spreadsheets/d/1wwahRMHG3buvnfHjmPQFU4Kyfq15oTwbfsuZpwHUKc4/edit#gid=1253069234)) to provide this functionality. This PR proposes an API to provide access to the number of hardware threads available on a given platform.

__edit (2020-07-24):__ The purpose of this PR is to provide a hint for how many threads to spawn to saturate the processor. There's value in introducing APIs for NUMA and Windows processor groups, but those are intentionally out of scope for this PR. See: https://github.com/rust-lang/rust/pull/74480#issuecomment-662116186.

## Naming

Discussing the naming of the API on Zulip surfaced two options:

- `std:🧵:hardware_concurrency`
- `std:🧵:hardware_threads`

Both options seemed acceptable, but overall people seem to gravitate the most towards `hardware_threads`. Additionally `@jonas-schievink` pointed out that the "hardware threads" terminology is well-established and is used in among other the [RISC-V specification](https://riscv.org/specifications/isa-spec-pdf/) (page 20):

> A component is termed a core if it contains an independent instruction fetch unit. A RISC-V-compatible core might support multiple RISC-V-compatible __hardware threads__, or harts, through multithreading.

It's also worth noting that [the original paper introducing C++'s `std::thread` submodule](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html) unfortunately doesn't feature any discussion on the naming of `hardware_concurrency`, so we can't use that to help inform our decision here.

## Return type

An important consideration `@joshtriplett` brought up is that we don't want to default to `1` for platforms where the number of available threads cannot be retrieved. Instead we want to inform the users of the fact that we don't know and allow them to handle that case. Which is why this PR uses `Option<NonZeroUsize>` as its return type, where `None` is returned on platforms where we don't know the number of hardware threads available.

The reasoning for `NonZeroUsize` vs `usize` is that if the number of threads for a platform are known, they'll always be at least 1. As evidenced by the example the `NonZero*` family of APIs may currently not be the most ergonomic to use, but improving the ergonomics of them is something that I think we can address separately.

## Implementation

`@Mark-Simulacrum` pointed out that most of the code we wanted to expose here was already available under `libtest`. So this PR mostly moves the internal code of libtest into a public API.
2020-10-18 02:28:21 +00:00
Yuki Okushi a0242e73bb
Rollup merge of #77851 - exrook:split-btreemap, r=dtolnay
BTreeMap: refactor Entry out of map.rs into its own file

btree/map.rs is approaching the 3000 line mark, splitting out the entry
code buys about 500 lines of headroom.

I've created this PR because the changes I've made in #77438 will push `map.rs` over the 3000 line limit and cause tidy to complain.

I picked `Entry` to factor out because it feels less tightly coupled to the rest of `BTreeMap` than the various iterator implementations.

Related: #60302
2020-10-18 04:11:07 +09:00
bors 4cb7ef0f94 Auto merge of #77455 - asm89:faster-spawn, r=kennytm
Use posix_spawn() on unix if program is a path

Previously `Command::spawn` would fall back to the non-posix_spawn based
implementation if the `PATH` environment variable was possibly changed.
On systems with a modern (g)libc `posix_spawn()` can be significantly
faster. If program is a path itself the `PATH` environment variable is
not used for the lookup and it should be safe to use the
`posix_spawnp()` method. [1]

We found this, because we have a cli application that effectively runs a
lot of subprocesses. It would sometimes noticeably hang while printing
output. Profiling showed that the process was spending the majority of
time in the kernel's `copy_page_range` function while spawning
subprocesses. During this time the process is completely blocked from
running, explaining why users were reporting the cli app hanging.

Through this we discovered that `std::process::Command` has a fast and
slow path for process execution. The fast path is backed by
`posix_spawnp()` and the slow path by fork/exec syscalls being called
explicitly. Using fork for process creation is supposed to be fast, but
it slows down as your process uses more memory.  It's not because the
kernel copies the actual memory from the parent, but it does need to
copy the references to it (see `copy_page_range` above!).  We ended up
using the slow path, because the command spawn implementation in falls
back to the slow path if it suspects the PATH environment variable was
changed.

Here is a smallish program demonstrating the slowdown before this code
change:

```
use std::process::Command;
use std::time::Instant;

fn main() {
    let mut args = std::env::args().skip(1);
    if let Some(size) = args.next() {
        // Allocate some memory
        let _xs: Vec<_> = std::iter::repeat(0)
            .take(size.parse().expect("valid number"))
            .collect();

        let mut command = Command::new("/bin/sh");
        command
            .arg("-c")
            .arg("echo hello");

        if args.next().is_some() {
            println!("Overriding PATH");
            command.env("PATH", std::env::var("PATH").expect("PATH env var"));
        }

        let now = Instant::now();
        let child = command
            .spawn()
            .expect("failed to execute process");

        println!("Spawn took: {:?}", now.elapsed());

        let output = child.wait_with_output().expect("failed to wait on process");
        println!("Output: {:?}", output);
    } else {
        eprintln!("Usage: prog [size]");
        std::process::exit(1);
    }
    ()
}
```

Running it and passing different amounts of elements to use to allocate
memory shows that the time taken for `spawn()` can differ quite
significantly. In latter case the `posix_spawnp()` implementation is 30x
faster:

```
$ cargo run --release 10000000
...
Spawn took: 324.275µs
hello
$ cargo run --release 10000000 changepath
...
Overriding PATH
Spawn took: 2.346809ms
hello
$ cargo run --release 100000000
...
Spawn took: 387.842µs
hello
$ cargo run --release 100000000 changepath
...
Overriding PATH
Spawn took: 13.434677ms
hello
```

[1]: 5f72f9800b/posix/execvpe.c (L81)
2020-10-17 06:16:00 +00:00
Dylan DPC 16b878fd0f
Rollup merge of #77932 - ssomers:btree_cleanup_gdb, r=Mark-Simulacrum
BTreeMap: improve gdb introspection of BTreeMap with ZST keys or values

I accidentally pushed an earlier revision in #77788: it changes the index of tuples for BTreeSet from ""[{}]".format(i) to "key{}".format(i). Which doesn't seem to make the slightest difference on my linux box nor on CI. In fact, gdb doesn't make any distinction between "key{}" and "val{}" for a BTreeMap either, leading to confusing output if you test more. But easy to improve.

r? @Mark-Simulacrum
2020-10-17 03:27:18 +02:00
Dylan DPC f40ecff964
Rollup merge of #77751 - vojtechkral:vecdeque-binary-search, r=scottmcm,dtolnay
liballoc: VecDeque: Add binary search functions

I am submitting rust-lang/rfcs#2997 as a PR as suggested by @scottmcm

I haven't yet created a tracking issue - if there's a favorable feedback I'll create one and update the issue links in the unstable attribs.
2020-10-17 03:27:15 +02:00
bors f1b97ee7f8 Auto merge of #77997 - fusion-engineering-forks:to-string-no-shrink, r=joshtriplett
Remove shrink_to_fit from default ToString::to_string implementation.

As suggested by `@scottmcm` on Zulip. shrink_to_fit() seems like the wrong thing to do here in most use cases of to_string(). Would be intereseting to see if it makes any difference in a timer run.

r? `@joshtriplett`
2020-10-16 22:53:50 +00:00
Yoshua Wuyts 3717646366 Add std:🧵:available_concurrency 2020-10-16 23:36:15 +02:00
Yuki Okushi b4282b37f1
Rollup merge of #77991 - Aaron1011:bump-backtrace-again, r=Mark-Simulacrum
Bump backtrace-rs

This pulls in https://github.com/rust-lang/backtrace-rs/pull/376, which
fixes Miri support for `std::backtrace::Backtrace`.
2020-10-17 05:36:50 +09:00
Yuki Okushi 050eb4d7e4
Rollup merge of #77971 - jyn514:broken-intra-doc-links, r=mark-simulacrum
Deny broken intra-doc links in linkchecker

Since rustdoc isn't warning about these links, check for them manually.

This also fixes the broken links that popped up from the lint.
2020-10-17 05:36:49 +09:00
Yuki Okushi 9abf81afa8
Rollup merge of #77900 - Thomasdezeeuw:fdatasync, r=dtolnay
Use fdatasync for File::sync_data on more OSes

Add support for the following OSes:
 * Android
 * FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=fdatasync&sektion=2
 * OpenBSD: https://man.openbsd.org/OpenBSD-5.8/fsync.2
 * NetBSD: https://man.netbsd.org/fdatasync.2
 * illumos: https://illumos.org/man/3c/fdatasync
2020-10-17 05:36:45 +09:00
Yuki Okushi 3356ad7c26
Rollup merge of #77547 - RalfJung:stable-union-drop, r=matthewjasper
stabilize union with 'ManuallyDrop' fields and 'impl Drop for Union'

As [discussed by @SimonSapin and @withoutboats](https://github.com/rust-lang/rust/issues/55149#issuecomment-634692020), this PR proposes to stabilize parts of the `untagged_union` feature gate:

* It will be possible to have a union with field type `ManuallyDrop<T>` for any `T`.
* While at it I propose we also stabilize `impl Drop for Union`; to my knowledge, there are no open concerns around this feature.

In the RFC discussion, we also talked about allowing `&mut T` as another non-`Copy` non-dropping type, but that felt to me like an overly specific exception so I figured we'd wait if there is actually any use for such a special case.

Some things remain unstable and still require the `untagged_union` feature gate:
* Union with fields that do not drop, are not `Copy`, and are not `ManuallyDrop<_>`. The reason to not stabilize this is to avoid semver concerns around libraries adding `Drop` implementations later. (This is already not fully semver compatible as, to my knowledge, the borrow checker will exploit the non-dropping nature of any type, but it seems prudent to avoid further increasing the amount of trouble adding an `impl Drop` can cause.)

Due to this, quite a few tests still need the `untagged_union` feature, but I think the ones where I could remove the feature flag provide good test coverage for the stable part.

Cc @rust-lang/lang
2020-10-17 05:36:38 +09:00
Vojtech Kral c7a787a327 liballoc: VecDeque: Simplify binary_search_by() 2020-10-16 20:49:19 +02:00
Vojtech Kral e0506d1e9a liballoc: VecDeque: Add tracking issue for binary search fns 2020-10-16 18:17:55 +02:00
bors 8850893d96 Auto merge of #77850 - kornelski:resizedefault, r=dtolnay
Remove deprecated unstable Vec::resize_default

It's [been deprecated](https://github.com/rust-lang/rust/pull/57656) for 15 releases.
2020-10-16 12:11:32 +00:00
Ralf Jung defcd7ff47 stop relying on feature(untagged_unions) in stdlib 2020-10-16 11:33:35 +02:00
Mara Bos 0b062887db Remove shrink_to_fit from default ToString::to_string implementation.
Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>
2020-10-16 11:15:12 +02:00
Tim Diekmann 955b37b305
Merge branch 'master' into box-alloc 2020-10-16 08:54:38 +02:00
Mara Bos 0f0257be10 Take some of sys/vxworks/process/* from sys/unix instead. 2020-10-16 06:22:05 +02:00
Mara Bos 408db0da85 Take sys/vxworks/{os,path,pipe} from sys/unix instead. 2020-10-16 06:22:00 +02:00
Mara Bos 71bb1dc2a0 Take sys/vxworks/{fd,fs,io} from sys/unix instead. 2020-10-16 06:19:00 +02:00
Mara Bos 3f196dc137 Take sys/vxworks/cmath from sys/unix instead. 2020-10-16 06:19:00 +02:00
Mara Bos ba483c51df Take sys/vxworks/args from sys/unix instead. 2020-10-16 06:19:00 +02:00
Mara Bos 08bcaac091 Take sys/vxworks/memchar from sys/unix instead. 2020-10-16 06:19:00 +02:00