Commit Graph

3108 Commits

Author SHA1 Message Date
Sebastian Dröge 12b605af88 Implement `TrustedLen` for `iter::Fuse<I: TrustedLen>` 2021-02-01 09:47:23 +02:00
Sebastian Dröge 99893346e8 Add SAFETY comment for the `TrustedRandomAccess` impl of `iter::Fuse` 2021-02-01 09:47:22 +02:00
Waffle d5c221107e add `Vec::extend_from_within` method
Implement <https://github.com/rust-lang/rfcs/pull/2714>, changes from the RFC:
- Rename the method `append_from_within` => `extend_from_within`
- Loose :Copy bound => :Clone
- Specialize in case of :Copy

This commit also adds `Vec::split_at_spare` private method and use it to implement
`Vec::spare_capacity_mut` and `Vec::extend_from_within`. This method returns 2
slices - initialized elements (same as `&mut vec[..]`) and uninitialized but
allocated space (same as `vec.spare_capacity_mut()`).
2021-01-31 22:30:19 +03:00
rodrimati1992 21c2343d3f
Update comment about leaking 2021-01-31 14:20:04 -03:00
Arlie Davis 3acd1a4f92 Fix calling convention for CRT startup
My PR #81478 used the wrong calling convention for a set of
functions that are called by the CRT. These functions need to use
`extern "C"`.

This would only affect x86, which is the only target (that I know of)
that has multiple calling conventions.
2021-01-31 08:49:23 -08:00
Jonas Schievink 9165676d91
Rollup merge of #81590 - KodrAus:stabilize/int_bits_const, r=m-ou-se
Stabilize int_bits_const

Closes #76904

The FCP to stabilize the `int_bits_const` feature completed on the tracking issue.
2021-01-31 16:36:57 +01:00
Jonas Schievink 600b2d3e5a
Rollup merge of #81589 - Seppel3210:master, r=jonas-schievink
Fix small typo in string.rs
2021-01-31 16:36:56 +01:00
Jonas Schievink 47a5312c30
Rollup merge of #81549 - est31:wording_fix, r=jonas-schievink
Misc ip documentation fixes
2021-01-31 16:36:47 +01:00
Jonas Schievink 99f2f5a830
Rollup merge of #80404 - JulianKnodt:arr_ref, r=oli-obk
Remove const_in_array_repeat

Fixes #80371. Fixes #81315. Fixes #80767. Fixes #75682.

I thought there might be some issue with `Repeats(_, 0)`, but if you increase the items in the array it still ICEs. I'm not sure if this is the best fix but it does fix the given issue.
2021-01-31 16:36:42 +01:00
The8472 4105506656 specialize io::copy to use the memory of the writer if it is a BufWriter 2021-01-31 14:58:03 +01:00
Ashley Mannix 8940a2652e stabilize int_bits_const 2021-01-31 21:50:47 +10:00
Sebastian Widua 6695690d49 Fix small typo 2021-01-31 12:19:09 +01:00
Konrad Borowski 15701f7531 Add doc aliases for "delete"
This patch adds doc aliases for "delete". The added aliases are
supposed to reference usages `delete` in other programming
languages.

- `HashMap::remove`, `BTreeMap::remove` -> `Map#delete` and `delete`
  keyword in JavaScript.

- `HashSet::remove`, `BTreeSet::remove` -> `Set#delete` in JavaScript.

- `mem::drop` -> `delete` keyword in C++.

- `fs::remove_file`, `fs::remove_dir`, `fs::remove_dir_all`
  -> `File#delete` in Java, `File#delete` and `Dir#delete` in Ruby.

Before this change, searching for "delete" in documentation
returned no results.
2021-01-31 11:07:37 +01:00
bors 0e63af5da3 Auto merge of #81478 - sivadeilra:windows_dll_imports, r=m-ou-se
Resolve DLL imports at CRT startup, not on demand

On Windows, libstd uses GetProcAddress to locate some DLL imports, so
that libstd can run on older versions of Windows. If a given DLL import
is not present, then libstd uses other behavior (such as fallback
implementations).

This commit uses a feature of the Windows CRT to do these DLL imports
during module initialization, before main() (or DllMain()) is called.
This is the ideal time to resolve imports, because the module is
effectively single-threaded at that point; no other threads can
touch the data or code of the module that is being initialized.

This avoids several problems. First, it makes the cost of performing
the DLL import lookups deterministic. Right now, the DLL imports are
done on demand, which means that application threads _might_ have to
do the DLL import during some time-sensitive operation. This is a
small source of unpredictability. Since threads can race, it's even
possible to have more than one thread running the same redundant
DLL lookup.

This commit also removes using the heap to allocate strings, during
the DLL lookups.
2021-01-31 10:01:15 +00:00
rodrimati1992 aa83e2aa04
Update maybe_uninit.rs 2021-01-31 01:56:53 -03:00
rodrimati1992 0974026a5d
Removed trailing whitespace 2021-01-31 01:37:48 -03:00
rodrimati1992 c351107cdc
Document how `MaybeUninit<Struct>` can be initialized. 2021-01-31 01:21:06 -03:00
Jonas Schievink 709710564a
Rollup merge of #81562 - the8472:improve-inplaceiterable-docs, r=sfackler
Clarify that InPlaceIterable guarantees extend to all advancing iterator methods.

A documentation update that should answer a question that came up in [this zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Safety.20guarantees.20of.20InPlaceIterable/near/223743336)

CC `@SkiFire13`
2021-01-31 01:47:46 +01:00
Jonas Schievink 635dbd60bf
Rollup merge of #81550 - xfix:replace-mention-of-predecessor, r=jonas-schievink
Replace predecessor with range in collections documentation

Fixes #81548.
2021-01-31 01:47:43 +01:00
Jonas Schievink fd868d02d1
Rollup merge of #81484 - Kogia-sima:perf/optimize-udiv_1e19, r=nagisa
Optimize decimal formatting of 128-bit integers

## Description

This PR optimizes the `udivmod_1e19` function, which is used for formatting 128-bit integers, based on the algorithm provided in \[1\]. This optimization improves performance of formatting 128-bit integers, especially on 64-bit architectures. It also slightly reduces the output binary size.

## Assembler comparison

https://godbolt.org/z/YrG5zY

## Performance

#### previous results

```
test fmt::write_u128_max                                        ... bench:         552 ns/iter (+/- 4)
test fmt::write_u128_min                                        ... bench:         125 ns/iter (+/- 2)
```

#### new results

```
test fmt::write_u128_max                                        ... bench:         205 ns/iter (+/- 13)
test fmt::write_u128_min                                        ... bench:         129 ns/iter (+/- 5)
```

## Reference

\[1\] T. Granlund and P. Montgomery, “Division by Invariant Integers Using Multiplication” in Proc. of the SIGPLAN94 Conference on Programming Language Design and Implementation, 1994, pp. 61–72
2021-01-31 01:47:36 +01:00
Jonas Schievink 13b3294e91
Rollup merge of #81198 - dtolnay:partialeq, r=m-ou-se
Remove requirement that forces symmetric and transitive PartialEq impls to exist

### Counterexample of symmetry:

If you [have](https://docs.rs/proc-macro2/1.0.24/proc_macro2/struct.Ident.html#impl-PartialEq%3CT%3E) an impl like:

```rust
impl<T> PartialEq<T> for Ident
where
    T: ?Sized + AsRef<str>
```

then Rust will not even allow the symmetric impl to exist.

```console
error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Ident`)
 --> src/main.rs:9:6
  |
9 | impl<T> PartialEq<Ident> for T where T: ?Sized + AsRef<str> {
  |      ^ type parameter `T` must be covered by another type when it appears before the first local type (`Ident`)
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type
  = note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last
```

<br>

### Counterexample of transitivity:

Consider these two existing impls from `regex` and `clap`:

```rust
// regex

/// An inline representation of `Option<char>`.
pub struct Char(u32);

impl PartialEq<char> for Char {
    fn eq(&self, other: &char) -> bool {
        self.0 == *other as u32
    }
}
```

```rust
// clap

pub(crate) enum KeyType {
    Short(char),
    Long(OsString),
    Position(u64),
}

impl PartialEq<char> for KeyType {
    fn eq(&self, rhs: &char) -> bool {
        match self {
            KeyType::Short(c) => c == rhs,
            _ => false,
        }
    }
}
```

It's nice to be able to add `PartialEq<proc_macro::Punct> for char` in libproc_macro (https://github.com/rust-lang/rust/pull/80595), but it makes no sense to force an `impl PartialEq<Punct> for Char` and `impl PartialEq<Punct> for KeyType` in `regex` and `clap` in code that otherwise has nothing to do with proc macros.

<br>

`@rust-lang/libs`
2021-01-31 01:47:31 +01:00
Jonas Schievink 0793fab0c3
Rollup merge of #81048 - yoshuawuyts:stabilize-core-slice-fill-with, r=m-ou-se
Stabilize `core::slice::fill_with`

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

This stabilizes the `slice_fill_with` feature for Rust 1.51, following the stabilization of `slice_fill` in 1.50. This was requested by libs team members in https://github.com/rust-lang/rust/pull/79213.

This PR also adds the "memset" alias for `slice::fill_with`, mirroring the alias set on the `slice::fill` sibling API. This will ensure someone looking for "memset" will find both variants.

r? `@Amanieu`
2021-01-31 01:47:29 +01:00
Jonas Schievink caf2c0652a
Rollup merge of #80945 - sdroege:downcast-send-sync, r=m-ou-se
Add Box::downcast() for dyn Any + Send + Sync

Looks like a plain omission, but unfortunately I just needed that in my code :)
2021-01-31 01:47:27 +01:00
Jonas Schievink 1e99f26894
Rollup merge of #80470 - SimonSapin:array-intoiter-type, r=m-ou-se
Stabilize by-value `[T; N]` iterator `core::array::IntoIter`

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

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

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

`new` would become unnecessary when `IntoIterator` is implemented and might be deprecated then, although it will stay stable.
2021-01-31 01:47:25 +01:00
Jonas Schievink 054c29d22c
Rollup merge of #80279 - Yaulendil:str-as-mut, r=m-ou-se
Implement missing `AsMut<str>` for `str`

Allows `&mut str` to be taken by a Generic which requires `T` such that `T: AsMut<str>`. Motivating example:

```rust
impl<'i, T> From<T> for StructImmut<'i> where
    T: AsRef<str> + 'i,
{
    fn from(asref: T) -> Self {
        let string: &str = asref.as_ref();
        //  ...
    }
}

impl<'i, T> From<T> for StructMut<'i> where
    T: AsMut<str> + 'i,
{
    fn from(mut asmut: T) -> Self {
        let string: &mut str = asmut.as_mut();
        //  ...
    }
}
```

The Immutable form of this structure can be constructed by `StructImmut::from(s)` where `s` may be a `&String` or a `&str`, because `AsRef<str>` is implemented for `str`. However, the mutable form of the structure can be constructed in the same way **only** with a `&mut String`, and **not** with a `&mut str`.

This change does have some precedent, because as can be seen in [the Implementors](https://doc.rust-lang.org/std/convert/trait.AsMut.html#implementors), `AsMut<[T]>` is implemented for `[T]` as well as for `Vec<T>`, but `AsMut<str>` is implemented only for `String`. This would complete the symmetry.

As a trait implementation, this should be immediately stable.
2021-01-31 01:47:23 +01:00
Jonas Schievink b28a1b2951
Rollup merge of #80053 - gilescope:include-ignore, r=m-ou-se
stabilise `cargo test -- --include-ignored`

stabilise `cargo test -- --include-ignored`

On stable there's no way to run ignored tests as well as the normal tests.

An example use case where stabilising this would help:
Exercism has some initial tests and then some additional ignored tests that people run currently with --ignore but currently they can't run all the tests in one go without being on nightly. It would be a little more ergonomic if this flag was stablilised.

( Fixes  #65770 )

I built with ./x.py build -i library/test - but as libtest is a dylib is there an easy way to invoke it manually to check it's working as expected? (I've updated the automated tests.)
2021-01-31 01:47:22 +01:00
Jonas Schievink ac37c326ae
Rollup merge of #79285 - yoshuawuyts:stabilize-arc_mutate_strong_count, r=m-ou-se
Stabilize Arc::{increment,decrement}_strong_count

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

Stabilizes `Arc::{incr,decr}_strong_count`, enabling unsafely incrementing an decrementing the Arc strong count directly with fewer gotchas. This API was first introduced on nightly six months ago, and has not seen any changes since. The initial PR showed two existing pieces of code that would benefit from this API, and included a change inside the stdlib to use this.

Given the small surface area, predictable use, and no changes since introduction, I'd like to propose we stabilize this.

closes https://github.com/rust-lang/rust/issues/71983
r? `@Mark-Simulacrum`

## Links
 * [Initial implementation](https://github.com/rust-lang/rust/pull/70733)
 * [Motivation from #68700](https://github.com/rust-lang/rust/pull/68700#discussion_r396169064)
 * [Real world example in an executor](https://docs.rs/extreme/666.666.666666/src/extreme/lib.rs.html#13)
2021-01-31 01:47:20 +01:00
Jonas Schievink 1bf130519c
Rollup merge of #78044 - oberien:empty-seek, r=m-ou-se
Implement io::Seek for io::Empty

Fix #78029
2021-01-31 01:47:18 +01:00
kadmin 6946534d84 Remove const_in_array_rep_expr 2021-01-30 23:20:24 +00:00
Eric Huss 4749ad0912 Add some links to the cell docs. 2021-01-30 14:41:23 -08:00
oberien f1cd17961c impl Seek for Empty
Fix #78029
2021-01-30 23:00:10 +01:00
Mara Bos bef4ec2fc5
Bump as_mut_str_for_str stable version. 2021-01-30 22:10:25 +01:00
Mara Bos fe4ac95cb8
Bump stable version of arc_mutate_strong_count 2021-01-30 21:08:30 +01:00
The8472 55d6247f52 Clarify that guarantees extend to other advancing iterator methods. 2021-01-30 18:07:48 +01:00
Konrad Borowski 56c27360b1 Replace predecessor with range in collections documentation
Fixes #81548.
2021-01-30 14:24:06 +01:00
est31 cddeb5e47b Misc ip documentation fixes 2021-01-30 12:06:06 +01:00
Yuki Okushi 0f11a943cc
Rollup merge of #81499 - SOF3:patch-1, r=sanxiyn
Updated Vec::splice documentation

Replacing with equal number of values does not increase the length of the vec.

Reference: https://stackoverflow.com/a/62559271/3990767
2021-01-30 13:36:55 +09:00
Yuki Okushi c26dd4d414
Rollup merge of #81409 - gilescope:chars_count, r=joshtriplett
Slight simplification of chars().count()

Slight simplification: No need to call len(), we can just count the number of non continuation bytes.

I can't see any reason not to do this, can you?
2021-01-30 13:36:48 +09:00
Yuki Okushi 91ea1cbc17
Rollup merge of #80959 - jhpratt:unsigned_abs-stabilization, r=m-ou-se
Stabilize `unsigned_abs`

Resolves #74913.

This PR stabilizes the `i*::unsigned_abs()` method, which returns the absolute value of an integer _as its unsigned equivalent_. This has the advantage that it does not overflow on `i*::MIN`.

I have gone ahead and used this in a couple locations throughout the repository.
2021-01-30 13:36:44 +09:00
Yuki Okushi b94d84d38a
Rollup merge of #80886 - RalfJung:stable-raw-ref-macros, r=m-ou-se
Stabilize raw ref macros

This stabilizes `raw_ref_macros` (https://github.com/rust-lang/rust/issues/73394), which is possible now that https://github.com/rust-lang/rust/issues/74355 is fixed.

However, as I already said in https://github.com/rust-lang/rust/issues/73394#issuecomment-751342185, I am not particularly happy with the current names of the macros. So I propose we also change them, which means I am proposing to stabilize the following in `core::ptr`:
```rust
pub macro const_addr_of($e:expr) {
    &raw const $e
}

pub macro mut_addr_of($e:expr) {
    &raw mut $e
}
```

The macro name change means we need another round of FCP. Cc `````@rust-lang/libs`````
Fixes #73394
2021-01-30 13:36:43 +09:00
Yuki Okushi ecd7cb1c3a
Rollup merge of #79023 - yoshuawuyts:stream, r=KodrAus
Add `core::stream::Stream`

[[Tracking issue: #79024](https://github.com/rust-lang/rust/issues/79024)]

This patch adds the `core::stream` submodule and implements `core::stream::Stream` in accordance with [RFC2996](https://github.com/rust-lang/rfcs/pull/2996). The RFC hasn't been merged yet, but as requested by the libs team in https://github.com/rust-lang/rfcs/pull/2996#issuecomment-725696389 I'm filing this PR to get the ball rolling.

## Documentatation

The docs in this PR have been adapted from [`std::iter`](https://doc.rust-lang.org/std/iter/index.html), [`async_std::stream`](https://docs.rs/async-std/1.7.0/async_std/stream/index.html), and [`futures::stream::Stream`](https://docs.rs/futures/0.3.8/futures/stream/trait.Stream.html). Once this PR lands my plan is to follow this up with PRs to add helper methods such as `stream::repeat` which can be used to document more of the concepts that are currently missing. That will allow us to cover concepts such as "infinite streams" and "laziness" in more depth.

## Feature gate

The feature gate for `Stream` is `stream_trait`. This matches the `#[lang = "future_trait"]` attribute name. The intention is that only the APIs defined in RFC2996 will use this feature gate, with future additions such as `stream::repeat` using their own feature gates. This is so we can ensure a smooth path towards stabilizing the `Stream` trait without needing to stabilize all the APIs in `core::stream` at once. But also don't start expanding the API until _after_ stabilization, as was the case with `std::future`.

__edit:__ the feature gate has been changed to `async_stream` to match the feature gate proposed in the RFC.

## Conclusion

This PR introduces `core::stream::{Stream, Next}` and re-exports it from `std` as `std::stream::{Stream, Next}`. Landing `Stream` in the stdlib has been a mult-year process; and it's incredibly exciting for this to finally happen!

---

r? `````@KodrAus`````
cc/ `````@rust-lang/wg-async-foundations````` `````@rust-lang/libs`````
2021-01-30 13:36:39 +09:00
Ingvar Stepanyan 5882cce54e Expose correct symlink API on WASI
As described in https://github.com/rust-lang/rust/issues/68574, the currently exposed API for symlinks is, in fact, a thin wrapper around the corresponding syscall, and not suitable for public usage.

The reason is that the 2nd param in the call is expected to be a handle of a "preopened directory" (a WASI concept for exposing dirs), and the only way to retrieve such handle right now is by tinkering with a private `__wasilibc_find_relpath` API, which is an implementation detail and definitely not something we want users to call directly.

Making matters worse, the semantics of this param aren't obvious from its name (`fd`), and easy to misinterpret, resulting in people trying to pass a handle of the target file itself (as in https://github.com/vitiral/path_abs/pull/50), which doesn't work as expected.

I did a codesearch among open-source repos, and the usage above is so far the only usage of this API at all, but we should fix it before more people start using it incorrectly.

While this is technically a breaking API change, I believe it's a justified one, as 1) it's OS-specific and 2) there was strictly no way to correctly use the previous form of the API, and if someone does use it, they're likely doing it wrong like in the example above.

The new API does not lead to the same confusion, as it mirrors `std::os::unix::fs::symlink` and `std::os::windows::fs::symlink_{file,dir}` variants by accepting source/target paths.

Fixes #68574.
2021-01-30 02:30:52 +00:00
Miguel Ojeda c7f4154c6a sys: use `process::abort()` instead of `arch::wasm32::unreachable()`
Rationale:

  - `abort()` lowers to `wasm32::unreachable()` anyway.
  - `abort()` isn't `unsafe`.
  - `abort()` matches the comment better.
  - `abort()` avoids confusion by future readers (e.g.
    https://github.com/rust-lang/rust/pull/81527): the naming of wasm's
    `unreachable' instruction is a bit unfortunate because it is not
    related to the `unreachable()` intrinsic (intended to trigger UB).

Codegen is likely to be different since `unreachable()` is `inline`
while `abort()` is `cold`. Since it doesn't look like we are expecting
here to trigger this case, the latter seems better anyway.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-01-29 20:25:23 +01:00
Arlie Davis f4debc8e94 Resolve DLL imports at CRT startup, not on demand
On Windows, libstd uses GetProcAddress to locate some DLL imports, so
that libstd can run on older versions of Windows. If a given DLL import
is not present, then libstd uses other behavior (such as fallback
implementations).

This commit uses a feature of the Windows CRT to do these DLL imports
during module initialization, before main() (or DllMain()) is called.
This is the ideal time to resolve imports, because the module is
effectively single-threaded at that point; no other threads can
touch the data or code of the module that is being initialized.

This avoids several problems. First, it makes the cost of performing
the DLL import lookups deterministic. Right now, the DLL imports are
done on demand, which means that application threads _might_ have to
do the DLL import during some time-sensitive operation. This is a
small source of unpredictability. Since threads can race, it's even
possible to have more than one thread running the same redundant
DLL lookup.

This commit also removes using the heap to allocate strings, during
the DLL lookups.
2021-01-29 10:41:49 -08:00
Miguel Ojeda 62f98a2509 btree: use Option's unwrap_unchecked()
Now that https://github.com/rust-lang/rust/issues/81383 is available,
start using it.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-01-29 19:10:58 +01:00
Ralf Jung 13ffa43bbb rename raw_const/mut -> const/mut_addr_of, and stabilize them 2021-01-29 15:18:45 +01:00
Chan Kwan Yin 02094f9962
Updated Vec::splice documentation
Replacing with equal number of values does not increase the length of the vec.

Reference: https://stackoverflow.com/a/62559271/3990767
2021-01-29 12:21:53 +08:00
bors c6bc46227a Auto merge of #81073 - ssomers:btree_owned_root_vs_dying, r=Mark-Simulacrum
BTreeMap: prevent tree from ever being owned by non-root node

This introduces a new marker type, `Dying`, which is used to note trees which are in the process of deallocation. On such trees, some fields may be in an inconsistent state as we are deallocating the tree. Unfortunately, there's not a great way to express conditional unsafety, so the methods for traversal can cause UB if not invoked correctly, but not marked as such. This is not a regression from the previous state, but rather isolates the destructive methods to solely being called on the dying state.
2021-01-29 04:06:38 +00:00
Yuki Okushi 94e093ab97
Rollup merge of #81306 - SkiFire13:fuse-flatten, r=cuviper
Fuse inner iterator in FlattenCompat and improve related tests

Fixes #81248
2021-01-29 09:17:36 +09:00
Kogia-sima ada714d9ce Optimize udiv_1e19() function 2021-01-29 02:27:20 +09:00
Yuki Okushi 70be5cef69
Rollup merge of #81277 - flip1995:from_diag_items, r=matthewjasper
Make more traits of the From/Into family diagnostic items

Following traits are now diagnostic items:
- `From` (unchanged)
- `Into`
- `TryFrom`
- `TryInto`

This also adds symbols for those items:
- `into_trait`
- `try_from_trait`
- `try_into_trait`

Related: https://github.com/rust-lang/rust-clippy/pull/6620#discussion_r562482587
2021-01-28 15:09:08 +09:00
Yuki Okushi 98226638fd
Rollup merge of #80868 - johanngan:should-panic-msg-with-expected, r=m-ou-se
Print failure message on all tests that should panic, but don't

Fixes #80861. Tests with the `#[should_panic]` attribute should always print a failure message if no panic occurs, regardless of whether or not an `expected` panic message is specified.
2021-01-28 15:09:04 +09:00
Yuki Okushi 025a850d21
Rollup merge of #70904 - LukasKalbertodt:stabilize-seek-convenience, r=m-ou-se
Stabilize `Seek::stream_position` (feature `seek_convenience`)

Tracking issue: #59359

Unresolved questions from tracking issue:
- "Override `stream_len` for `File`?" → we can do that in the future, this does not block stabilization.
- "Rename to `len` and `position`?" → as noted in the tracking issue, both of these shorter names have problems (`len` is usually a cheap getter, `position` clashes with `Cursor`). I do think the current names are perfectly fine.
- "Rename `stream_position` to `tell`?" → as mentioned in [the comment bringing this up](https://github.com/rust-lang/rust/issues/59359#issuecomment-559541545), `stream_position` is more descriptive. I don't think `tell` would be a good name.

What remains to decide, is whether or not adding these methods is worth it.
2021-01-28 15:09:00 +09:00
Amanieu d'Antras 06f14df43b Support AArch64 ILP32 in libunwind bindings 2021-01-27 22:47:57 +00:00
bors a2f8f62818 Auto merge of #81335 - thomwiggers:no-panic-shrink-to, r=Mark-Simulacrum
Trying to shrink_to greater than capacity should be no-op

Per the discussion in https://github.com/rust-lang/rust/issues/56431, `shrink_to` shouldn't panic if you try to make a vector shrink to a capacity greater than its current capacity.
2021-01-27 18:36:32 +00:00
Giles Cope a623ea5301
Same instructions, but simpler. 2021-01-26 21:57:50 +00:00
Yuki Okushi b2f6c2aa9b
Rollup merge of #81412 - hyd-dev:array-assume-init-wrong-assertion, r=m-ou-se
Fix assertion in `MaybeUninit::array_assume_init()` for zero-length arrays

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

use std::mem::MaybeUninit;

enum Uninhabited {}

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

This PR makes it ignore zero-length arrays.

cc #80908
2021-01-27 04:43:37 +09:00
Yuki Okushi 8299105821
Rollup merge of #81191 - ssomers:btree_more_order_chaos, r=Mark-Simulacrum
BTreeMap: test all borrowing interfaces and test more chaotic order behavior

Inspired by #81169, test what happens if you mess up order of the type with which you search (as opposed to the key type).

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

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

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

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

Fixes #48278.
2021-01-27 04:43:14 +09:00
Stein Somers 417eefedfa BTreeMap: stop tree from being owned by non-root node 2021-01-26 19:32:03 +01:00
Thom Wiggers d069c58e78
shrink_to shouldn't panic on len greater than capacity 2021-01-26 19:25:37 +01:00
hyd-dev f52066726d
Fix assertion in `MaybeUninit::array_assume_init()` for zero-length arrays 2021-01-27 00:16:58 +08:00
bors 7907345e58 Auto merge of #81217 - ssomers:btree_bring_back_the_slice, r=Mark-Simulacrum
BTreeMap: bring back the key slice for immutable lookup

Pave the way for binary search, by reverting a bit of #73971, which banned `keys` for misbehaving while it was defined for every `BorrowType`. Adding some `debug_assert`s along the way.

r? `@Mark-Simulacrum`
2021-01-26 14:47:51 +00:00
Giles Cope c07e5585b3
Let's try the most idiomatic way. 2021-01-26 11:36:02 +00:00
Giles Cope 425a70a460
Removing if so it's more like the previous implementation. 2021-01-26 11:26:58 +00:00
bors 1483e67add Auto merge of #81367 - andersk:join-test-threads, r=dtolnay
libtest: Wait for test threads to exit after they report completion

Otherwise we can miss bugs where a test reports that it succeeded but then panics within a TLS destructor.

Example:

```rust
use std:🧵:sleep;
use std::time::Duration;

struct Foo;

impl Drop for Foo {
    fn drop(&mut self) {
        sleep(Duration::from_secs(1));
        panic!()
    }
}

thread_local!(static FOO: Foo = Foo);

#[test]
pub fn test() {
    FOO.with(|_| {});
}
```

Before this fix, `cargo test` incorrectly reports success.

```console
$ cargo test
    Finished test [unoptimized + debuginfo] target(s) in 0.01s
     Running target/debug/deps/panicking_test-85130fa46b54f758

running 1 test
test test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

$ echo $?
0
```

After this fix, the failure is visible. (The entire process is aborted due to #24479.)

```console
$ cargo test
    Finished test [unoptimized + debuginfo] target(s) in 0.01s
     Running target/debug/deps/panicking_test-76180625bc2ee3c9

running 1 test
thread 'test' panicked at 'explicit panic', src/main.rs:9:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5
error: test failed, to rerun pass '--bin panicking-test'

Caused by:
  process didn't exit successfully: `/tmp/panicking-test/target/debug/deps/panicking_test-76180625bc2ee3c9 --nocapture` (signal: 6, SIGABRT: process abort signal)

$ echo $?
101
```
2021-01-26 11:15:44 +00:00
Giles Cope 328abfb943
Slight simplification of chars().count() 2021-01-26 11:14:57 +00:00
bors ff6ee2a702 Auto merge of #79113 - andjo403:raw_vec_ptr, r=m-ou-se
mark raw_vec::ptr with inline

when a lot of vectors is used in a enum as in the example in #66617 if this function is not inlined and multiple cgus is used this results in huge compile times. with this fix the compile time is 6s from minutes for the example in #66617. I did not have the patience to wait for it to compile for more then 3 min.
2021-01-26 02:56:37 +00:00
Anders Kaseorg b05788e859 libtest: Store pending timeouts in a deque
This reduces the total complexity of checking timeouts from quadratic
to linear, and should also fix an unwrap of None on completion of an
already timed-out test.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2021-01-25 12:21:33 -08:00
bors f4eb5d9f71 Auto merge of #68828 - oli-obk:inline_cycle, r=wesleywiser
Prevent query cycles in the MIR inliner

r? `@eddyb` `@wesleywiser`

cc `@rust-lang/wg-mir-opt`

The general design is that we have a new query that is run on the `validated_mir` instead of on the `optimized_mir`. That query is forced before going into the optimization pipeline, so as to not try to read from a stolen MIR.

The query should not be cached cross crate, as you should never call it for items from other crates. By its very design calls into other crates can never cause query cycles.

This is a pessimistic approach to inlining, since we strictly have more calls in the `validated_mir` than we have in `optimized_mir`, but that's not a problem imo.
2021-01-25 19:03:37 +00:00
Miguel Ojeda 01250fcec6 Add tracking issue
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-01-25 14:58:09 +01:00
Miguel Ojeda 0140dacabb Link the reference about undefined behavior
Suggested-by: Mara Bos <m-ou.se@m-ou.se>
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-01-25 14:53:19 +01:00
Mara Bos fc7c5e486c Make std::panic_2021 an alias for core::panic_2021. 2021-01-25 13:49:00 +01:00
Mara Bos d5414f9a9f Implement new panic!() behaviour for Rust 2021. 2021-01-25 13:48:11 +01:00
Mara Bos dec5cfbaba Remove unused allow_internal_unstable on core::panic. 2021-01-25 13:48:10 +01:00
Anders Kaseorg 57c72ab846 libtest: Wait for test threads to exit after they report completion
Otherwise we can miss bugs where a test reports that it succeeded but
then panics within a TLS destructor.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2021-01-24 19:09:54 -08:00
Eric Huss 30891b84ff libtest: allow multiple filters 2021-01-24 13:12:37 -08:00
Jonas Schievink 3ed8a3769a
Rollup merge of #79884 - Digital-Chaos:replace-magic, r=m-ou-se
Replace magic numbers with existing constants

Replaced magic numbers in `library/core/src/time.rs` with predefined constants.
2021-01-24 22:09:51 +01:00
Jonas Schievink 13b88c21d0
Rollup merge of #79174 - taiki-e:std-future, r=Mark-Simulacrum
Make std::future a re-export of core::future

After 1a764a7ef5, there are no `std::future`-specific items (except for `cfg(bootstrap)` items removed in 93eed402ad). So, instead of defining `std` own module, we can re-export the `core::future` directly.
2021-01-24 22:09:49 +01:00
Jonas Schievink 5a1f2ecdd7
Rollup merge of #75180 - KodrAus:feat/error-by-ref, r=m-ou-se
Implement Error for &(impl Error)

Opening this up just to see what it breaks. It's unfortunate that `&(impl Error)` doesn't actually implement `Error`. If this direct approach doesn't work out then I'll try something different, like an `Error::by_ref` method.

**EDIT:** This is a super low-priority experiment so feel free to cancel it for more important crater runs! 🙂

-----

# Stabilization Report

## Why?

We've been working for the last few years to try "fix" the `Error` trait, which is probably one of the most fundamental in the whole standard library. One of its issues is that we commonly expect you to work with abstract errors through `dyn Trait`, but references and smart pointers over `dyn Trait` don't actually implement the `Error` trait. If you have a `&dyn Error` or a `Box<dyn Error>` you simply can't pass it to a method that wants a `impl Error`.

## What does this do?

This stabilizes the following trait impl:

```rust
impl<'a, T: Error + ?Sized + 'static> Error for &'a T;
```

This means that `&dyn Error` will now satisfy a `impl Error` bound.

It doesn't do anything with `Box<dyn Error>` directly. We discussed how we could do `Box<dyn Error>` in the thread here (and elsewhere in the past), but it seems like we need something like lattice-based specialization or a sprinkling of snowflake compiler magic to make that work. Having said that, with this new impl you _can_ now get a `impl Error` from a `Box<dyn Error>`  by dereferencing it.

## What breaks?

A crater run revealed a few crates broke with something like the following:

```rust
// where e: &'short &'long dyn Error
err.source()
```

previously we'd auto-deref that `&'short &'long dyn Error` to return a `Option<&'long dyn Error>` from `source`, but now will call directly on `&'short impl Error`, so will return a `Option<&'short dyn Error>`. The fix is to manually deref:

```rust
// where e: &'short &'long dyn Error
(*err).source()
```

In the recent Libs meeting we considered this acceptable breakage.
2021-01-24 22:09:45 +01:00
Stein Somers b20f468489 BTreeMap: lightly refactor the split_off implementation 2021-01-24 17:51:35 +01:00
bors 9a9477fada Auto merge of #81250 - sivadeilra:remove_xp_compat, r=joshtriplett,m-ou-se
Remove delay-binding for Win XP and Vista

The minimum supported Windows version is now Windows 7. Windows XP
and Windows Vista are no longer supported; both are already broken, and
require extra steps to use.

This commit removes the delayed-binding support for Windows API
functions that are present on all supported Windows targets. This has
several benefits: Removes needless complexity. Removes a load and
dynamic call on hot paths in mutex acquire / release. This may have
performance benefits.

* "Drop official support for Windows XP"
  https://github.com/rust-lang/compiler-team/issues/378

* "Firefox has ended support for Windows XP and Vista"
  https://support.mozilla.org/en-US/kb/end-support-windows-xp-and-vista
2021-01-24 12:34:08 +00:00
Lukas Kalbertodt 8a18fb0f73
Stabilize `Seek::stream_position` & change feature of `Seek::stream_len` 2021-01-24 10:14:24 +01:00
Giacomo Stevanato 5aa625b903 Manually fuse the inner iterator in FlattenCompat 2021-01-23 21:33:38 +01:00
Giacomo Stevanato f241c10223 Improve flatten-fuse tests 2021-01-23 21:33:38 +01:00
Jonas Schievink ebeb6b8b26
Rollup merge of #81301 - davidgu:patch-1, r=jonas-schievink
Fix small typo

Fractional part of `12.34e56` seems to be incorrectly stated as '45' and not '34'
2021-01-23 20:16:19 +01:00
Jonas Schievink 44c668cfca
Rollup merge of #81281 - a1phyr:inline_path, r=dtolnay
Inline methods of Path and OsString

These methods are not generic, and therefore aren't candidates for cross-crate inlining without an `#[inline]` attribute.
2021-01-23 20:16:12 +01:00
Jonas Schievink 05a95a4372
Rollup merge of #81170 - xfix:vecdeque-bug-fix, r=sfackler
Avoid hash_slice in VecDeque's Hash implementation

Fixes #80303.
2021-01-23 20:16:02 +01:00
Jonas Schievink 7635462fe8
Rollup merge of #79841 - fintelia:patch-6, r=kennytm
More clear documentation for NonNull<T>

Rephrase and hopefully clarify the discussion of covariance in `NonNull<T>` documentation.

I'm very much not an expert so someone should definitely double check the correctness of what I'm saying. At the same time, the new language makes more sense to me, so hopefully it also is more logical to others whose knowledge of covariance basically begins and ends with the [Rustonomicon chapter](https://doc.rust-lang.org/nomicon/subtyping.html).

Related to #48929.
2021-01-23 20:15:54 +01:00
Sean Chen 050643a960 Add Frames iterator for Backtrace 2021-01-23 11:56:33 -06:00
David 2f5ce8e802
Fix small typo 2021-01-23 12:31:40 -05:00
oli f238148214 Allow libcore to be built with MIR inlining
Inlining caused new lints to get emitted, so we silence those lints now that we actually can.
2021-01-23 16:51:23 +00:00
oxalica 2a11c57fb0
Fix and simplify 2021-01-24 00:11:51 +08:00
oxalica 969e552355
Simplify and fix tests 2021-01-24 00:11:51 +08:00
Yoshua Wuyts a1b11321fb Remove `Stream::next`
This is a temporary change only, as we wait to resolve dynamic dispatch issues. The `Stream::next` method and corresponding documentation are expected to be fully restored once we have a path to proceed.

Ref: https://github.com/rust-lang/rfcs/pull/2996#issuecomment-757386206

update docs
2021-01-23 16:54:56 +01:00
bors 4153fa82ff Auto merge of #80715 - JulianKnodt:skip_opt, r=nagisa
Change branching in `iter.skip()`

Optimize branching in `Skip`, which was brought up in #80416.
This assumes that if `next` is called, it's likely that there will be more calls to `next`, and the branch for skip will only be hit once thus it's unlikely to take that path. Even w/o the `unlikely` intrinsic, it compiles more efficiently, I believe because the path where `next` is called is always taken.

It should be noted there are very few places in the compiler where `Skip` is used, so probably won't have a noticeable perf impact.

[New impl](https://godbolt.org/z/85rdj4)
[Old impl](https://godbolt.org/z/Wc74rh)

[Some additional asm examples](https://godbolt.org/z/feKzoz) although they really don't have a ton of difference between them.
2021-01-23 09:25:11 +00:00
bors fe0fa59b50 Auto merge of #76391 - danii:master, r=cuviper
Split up core/test/iter.rs into multiple files

This PR removes the `// ignore-tidy-filelength` at the top of [iter.rs](04f44fb923/library/core/tests/iter.rs) by splitting it into several sub files. I have split the file per test, based on what I felt the test was really trying to test.
Addresses issue #60302.
- [associated_util.rs](d29180a8ed/library/core/tests/iter/associated_util.rs) - For testing the module level functions. (Maybe should be renamed?)
- [collection.rs](d29180a8ed/library/core/tests/iter/collection.rs) - For testing methods that use the values of all the items in an iterator, and creates one value from them, whether it be a Vec of all the values, or a number that represents the sum.
- [mod.rs](d29180a8ed/library/core/tests/iter/mod.rs) - For utility structs used in all tests, and other tests I didn't know where to place.
- [range.rs](d29180a8ed/library/core/tests/iter/range.rs) - For testing ranges.
- [transformation.rs](d29180a8ed/library/core/tests/iter/transformation.rs) - For testing methods that transform all the values in an iterator.
- [util.rs](d29180a8ed/library/core/tests/iter/util.rs) - For testing methods that provide utility in more specific use cases.

"Programatically"
-----------------------
You may have noticed I "Programatically" split up the file. [This is how](https://gist.github.com/danii/a58b3bcafa9faf1c3e4b01ad7495baf4) I managed to do that. 😛 Hope that's fine.
2021-01-23 03:33:16 +00:00
Daniel Conley 0c78500426 library/core/tests/iter documentation and cleanup 2021-01-22 17:57:08 -05:00
Daniel Conley bc830a274b library/core/tests/iter rearrange & add back missed doc comments 2021-01-22 17:57:07 -05:00
Daniel Conley 1e3a2def67 library/core/test/iter add newlines between tests 2021-01-22 16:58:21 -05:00
bors 34b3d41e1a Auto merge of #79233 - yoshuawuyts:alloc-doc-alias, r=GuillaumeGomez
Add doc aliases for memory allocations

This patch adds doc aliases for various C allocation functions, making it possible to search for the C-equivalent of a function and finding the (safe) Rust counterpart:

- `Vec::with_capacity` / `Box::new` / `vec!` -> alloc + malloc, allocates memory
- `Box::new_zeroed` -> calloc, allocates zeroed-out memory
- `Vec::{reserve,reserve_exact,try_reserve_exact,shrink_to_fit,shrink_to}` -> realloc, reallocates a previously allocated slice of memory

It's worth noting that `Vec::new` does not allocate, so we don't link to it. Instead people are probably looking for `Vec::with_capacity` or `vec!`. I hope this will allow people comfortable with the system allocation APIs to make it easier to find what they may be looking for.

Thanks!
2021-01-22 21:48:41 +00:00
Jonathan Behrens 0392085f5c More clear documentation for NonNull<T>
Rephrase and hopefully clarify the discussion of covariance in `NonNull<T>` documentation.
2021-01-22 14:46:11 -05:00
bors 22ddcd1a13 Auto merge of #72160 - slo1:libstd-setgroups, r=KodrAus
Add setgroups to std::os::unix::process::CommandExt

Should fix #38527. I'm not sure groups is the greatest name though.
2021-01-22 19:00:11 +00:00
Benoît du Garreau 9880560a1c Inline methods of Path and OsString 2021-01-22 18:46:00 +01:00
Yoshua Wuyts 7d102383f9 Add doc aliases for memory allocations
- Vec::with_capacity / Box::new -> alloc + malloc
- Box::new_zeroed -> calloc
- Vec::{reserve,reserve_exact,try_reserve_exact,shrink_to_fit,shrink_to} -> realloc
2021-01-22 18:15:28 +01:00
flip1995 e25959b417
Make more traits of the From/Into family diagnostic items
Following traits are now diagnostic items:
- `From` (unchanged)
- `Into`
- `TryFrom`
- `TryInto`

This also adds symbols for those items:
- `into_trait`
- `try_from_trait`
- `try_into_trait`
2021-01-22 18:07:00 +01:00
Yoshua Wuyts 0c8db16a67 Add `core::stream::Stream`
This patch adds the `core::stream` submodule and implements `core::stream::Stream` in accordance with RFC2996.

Add feedback from @camelid
2021-01-22 17:41:56 +01:00
Mara Bos 9c2a5776b2
Rollup merge of #81242 - jyn514:const-cap, r=sfackler
Enforce statically that `MIN_NON_ZERO_CAP` is calculated at compile time

Previously, it would usually get computed by LLVM, but this enforces it. This removes the need for the comment saying "LLVM is smart enough".

I don't expect this to make a performance difference, but I do think it makes the performance properties easier to reason about.
2021-01-22 14:30:22 +00:00
Mara Bos 70597f28f6
Rollup merge of #81241 - m-ou-se:force-expr-macro-rules, r=oli-obk
Turn alloc's force_expr macro into a regular macro_rules.

This turns `alloc`'s `force_expr` macro into a regular `macro_rules`.

Otherwise rust-analyzer doesn't understand `vec![]`. See https://github.com/rust-analyzer/rust-analyzer/issues/7349 and https://github.com/rust-lang/rust/pull/81080#issuecomment-764741721

Edit: See https://github.com/rust-lang/rust/pull/81241#issuecomment-764812660 for a discussion of alternatives.
2021-01-22 14:30:21 +00:00
Mara Bos 81a60b7aa8
Rollup merge of #81233 - lzutao:dbg, r=KodrAus
Document why not use concat! in dbg! macro

Original title: Reduce code generated by `dbg!` macro
The expanded code before/after: <https://rust.godbolt.org/z/hE3j95>.

---

We cannot use `concat!` since `file!` could contains `{` or the expression is a block (`{ .. }`).
Using it will generated malformed format strings.
So let's document this reason why we don't use `concat!` macro at all.
2021-01-22 14:30:17 +00:00
Mara Bos 950ed27e8b
Rollup merge of #81202 - lzutao:dbg_ipv6, r=Amanieu
Don't prefix 0x for each segments in `dbg!(Ipv6)`

Fixes #81182
2021-01-22 14:30:12 +00:00
Mara Bos b59f6e05ef
Rollup merge of #81194 - m-ou-se:stabilize-panic-any, r=m-ou-se
Stabilize std::panic::panic_any.

This stabilizes `std::panic::panic_any`.
2021-01-22 14:30:11 +00:00
Mara Bos 226fe55057
Rollup merge of #81173 - lukaslueg:intersperse_docs, r=m-ou-se
Expand docs on Iterator::intersperse

Unstable feature in #79524. This expands on the docs to bring them more in line with how other methods of `Iterator` are demonstrated.
2021-01-22 14:30:09 +00:00
Arlie Davis 59855e0bbf Remove delay-binding for Win XP and Vista
The minimum supported Windows version is now Windows 7. Windows XP
and Windows Vista are no longer supported; both are already broken, and
require extra steps to use.

This commit removes the delayed-binding support for Windows API
functions that are present on all supported Windows targets. This has
several benefits: Removes needless complexity. Removes a load and
dynamic call on hot paths in mutex acquire / release. This may have
performance benefits.

* "Drop official support for Windows XP"
  https://github.com/rust-lang/compiler-team/issues/378

* "Firefox has ended support for Windows XP and Vista"
  https://support.mozilla.org/en-US/kb/end-support-windows-xp-and-vista
2021-01-22 02:02:39 -08:00
slo1 41e6b23000 Add setgroups to std::os::unix::process::CommandExt 2021-01-21 22:42:38 -08:00
Daniel Conley 3ce97000e1 library/core/test/iter.rs split attempt 2 2021-01-21 19:36:32 -05:00
bors a9a396d8ed Auto merge of #81160 - RalfJung:swap, r=oli-obk
use raw-ptr-addr-of for slice::swap

Fixes https://github.com/rust-lang/rust/issues/80682
2021-01-22 00:01:53 +00:00
bors 202720bf48 Auto merge of #81152 - lzutao:intersperse_fold, r=m-ou-se
Fix intersperse_fold

Here is a standalone playground link in case anybody wants to modify code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=626b4d044fb74f044a36098ad907e40f

Fixes #81145

cc #79479 `@jonas-schievink`
2021-01-21 21:05:34 +00:00
Lukas Lueg c61785ea44 Fix typo 2021-01-21 20:31:37 +01:00
Lukas Lueg 653bcc8ad2 Expand docs on Iterator::intersperse 2021-01-21 19:47:57 +01:00
Mara Bos 1934eaf6d8 Rename alloc::force_expr to __rust_force_expr. 2021-01-21 18:30:49 +01:00
Mara Bos 8f28a3269e Turn alloc's force_expr macro into a regular macro_rules!{}.
Otherwise rust-analyzer doesn't understand vec![].
2021-01-21 18:30:15 +01:00
Joshua Nelson 758d855bff Enforce statically that `MIN_NON_ZERO_CAP` is calculated at compile time
Previously, it would usually get computed by LLVM, but this enforces it.
2021-01-21 11:57:01 -05:00
Simon Sapin 83d32b0a27
Add example to array::IntoIter::new’s doc-comment
Co-authored-by: Ashley Mannix <kodraus@hey.com>
2021-01-21 15:52:53 +01:00
bors a243ad280a Auto merge of #81240 - JohnTitor:rollup-ieaz82a, r=JohnTitor
Rollup of 11 pull requests

Successful merges:

 - #79655 (Add Vec visualization to understand capacity)
 - #80172 (Use consistent punctuation for 'Prelude contents' docs)
 - #80429 (Add regression test for mutual recursion in obligation forest)
 - #80601 (Improve grammar in documentation of format strings)
 - #81046 (Improve unknown external crate error)
 - #81178 (Visit only terminators when removing landing pads)
 - #81179 (Fix broken links with `--document-private-items` in the standard library)
 - #81184 (Remove unnecessary `after_run` function)
 - #81185 (Fix ICE in mir when evaluating SizeOf on unsized type)
 - #81187 (Fix typo in counters.rs)
 - #81219 (Document security implications of std::env::temp_dir)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-01-21 12:18:32 +00:00
Yuki Okushi d6c7a797fc
Rollup merge of #81219 - joshtriplett:temp_dir-docs, r=sfackler
Document security implications of std::env::temp_dir

Update the sample code to not create an insecure temporary file.
2021-01-21 20:04:56 +09:00
Yuki Okushi b76f0f92ab
Rollup merge of #81179 - CPerezz:fix_interal_doc_warns, r=jyn514
Fix broken links with `--document-private-items` in the standard library

As it was suggested in #81037 `SpecFromIter` is not
in the scope and therefore we get a warning when we try to
do document private intems in `rust/library/alloc/`.

This addresses #81037 by adding the trait in the scope as ```@jyn514```
suggested and also adding an `allow(unused_imports)` flag so that
the compiler does not complain, Since the trait is not used
per se in the code, it's just needed to have properly documented
docs.
2021-01-21 20:04:50 +09:00
Yuki Okushi 8be36b1b3a
Rollup merge of #80601 - steffahn:improve_format_string_grammar, r=m-ou-se
Improve grammar in documentation of format strings

The docs previously were
* using some weird `<` and `>` around some nonterminals
  * _correct me if these **did** have any meaning_
* using of a (not explicitly defined) `text` nonterminal that didn’t explicitly disallow productions containing `'{'` or `'}'`
* incorrect in not allowing for `x?` and `X?` productions of `type`
* unnecessarily ambiguous, both
  * allowing `type` to be `''`, and
  * using an optional `[type]`
* using inconsistent underscore/hyphenation style between `format_string` and `format_spec` vs `maybe-format`

_Rendered:_
![Screenshot_20210101_230901](https://user-images.githubusercontent.com/3986214/103447038-69d7a180-4c86-11eb-8fa0-0a6160a7ff7a.png)
_(current docs: https://doc.rust-lang.org/nightly/std/fmt/#syntax)_

```@rustbot``` modify labels: T-doc
2021-01-21 20:04:43 +09:00
Yuki Okushi 9abd746a32
Rollup merge of #80172 - camelid:prelude-docs-consistent-punct, r=steveklabnik
Use consistent punctuation for 'Prelude contents' docs
2021-01-21 20:04:39 +09:00
Lzu Tao d0c1405564 Document why cannot use concat! in dbg!
Co-authored-by: Miguel Ojeda <ojeda@users.noreply.github.com>
2021-01-21 10:50:21 +00:00
Ralf Jung 18d12ad171 directly expose copy and copy_nonoverlapping intrinsics 2021-01-21 10:41:22 +01:00
Ivan Tham 9844d9ee97
Remove link to current section
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
2021-01-21 13:18:12 +08:00
bstrie 6f3df00610 Deprecate-in-future the constants superceded by RFC 2700 2021-01-20 20:08:11 -05:00
Josh Triplett 27f3764519 Document security implications of std::env::temp_dir
Update the sample code to not create an insecure temporary file.
2021-01-20 11:24:47 -08:00
Stein Somers c0e807563c BTreeMap: bring back the key slice for immutable lookup 2021-01-20 19:23:49 +01:00
Ivan Tham 9f338e18af Add more details explaning the Vec visualization
Suggested by oli-obk
2021-01-20 23:41:56 +08:00
Ivan Tham 9e42d14927 Add Vec visualization to understand capacity
Visualize vector while differentiating between stack and heap.

Inspired by cheats.rs, as this is probably the first place beginner go,
they could understand stack and heap, length and capacity with this. Not
sure if adding this means we should add to other places too.

Superseeds #76066
2021-01-20 23:41:55 +08:00
Lzu Tao 116b66ad49 Dont prefix 0x when `dbg!(ipv6)` 2021-01-20 04:31:34 +00:00
Lzu Tao 6b66749e17 Use slice::split_first instead of manuall slicing 2021-01-20 04:31:34 +00:00
David Tolnay 8758083aad
Remove requirement that forces symmetric and transitive PartialEq impls to exist 2021-01-19 14:26:09 -08:00
bors 14265f9c55 Auto merge of #79578 - alexcrichton:update-waasi, r=KodrAus
std: Update wasi-libc commit of the wasm32-wasi target

This brings in an implementation of `current_dir` and `set_current_dir`
(emulation in `wasi-libc`) as well as an updated version of finding
relative paths. This also additionally updates clang to the latest
release to build wasi-libc with.
2021-01-19 22:20:58 +00:00
Mara Bos 8cac04e8b8 Make 'static bound on panic_any explicit.
This was already implied because Any: 'static, but this makes it
explicit.
2021-01-19 21:41:41 +01:00
Mara Bos 230d5b1e5f Stabilize std::panic::panic_any. 2021-01-19 21:30:49 +01:00
Stein Somers 495f7cca85 BTreeMap: compile-test all borrowing interfaces and test more chaotic order 2021-01-19 19:47:31 +01:00
CPerezz bc6720f872
Add SpecFromIter ref in the comments directly 2021-01-19 18:28:33 +01:00
bors cf04ae54e6 Auto merge of #79705 - ijackson:bufwriter-disassemble, r=m-ou-se
BufWriter: Provide into_raw_parts

If something goes wrong, one might want to unpeel the layers of nested
Writers to perform recovery actions on the underlying writer, or reuse
its resources.

`into_inner` can be used for this when the inner writer is still
working.  But when the inner writer is broken, and returning errors,
`into_inner` simply gives you the error from flush, and the same
`Bufwriter` back again.

Here I provide the necessary function, which I have chosen to call
`into_raw_parts`.

I had to do something with `panicked`.  Returning it to the caller as
a boolean seemed rather bare.  Throwing the buffered data away in this
situation also seems unfriendly: maybe the programmer knows something
about the underlying writer and can recover somehow.

So I went for a custom Error.  This may be overkill, but it does have
the nice property that a caller who actually wants to look at the
buffered data, rather than simply extracting the inner writer, will be
told by the type system if they forget to handle the panicked case.

If a caller doesn't need the buffer, it can just be discarded.  That
WriterPanicked is a newtype around Vec<u8> means that hopefully the
layouts of the Ok and Err variants can be very similar, with just a
boolean discriminant.  So this custom error type should compile down
to nearly no code.

*If this general idea is felt appropriate, I will open a tracking issue, etc.*
2021-01-19 16:42:19 +00:00
Mara Bos 9272d53c5a Stop `fold` at first None when iterator yield 2021-01-19 12:17:58 +00:00
Guillaume Gomez dcb74796c0
Rollup merge of #81168 - soniasingla:doc/sonia, r=jonas-schievink
Fixes #81109 - Typo in pointer::wrapping_sub

Signed-off-by: soniasingla <soniasingla.1812@gmail.com>

Related to issue #81109
2021-01-19 10:28:04 +01:00
Guillaume Gomez 7aa3920488
Rollup merge of #81166 - RalfJung:debug-assert-comments, r=Mark-Simulacrum
remove some outdated comments regarding  debug assertions

https://github.com/rust-lang/rust/pull/79684 removed those debug assertions.
2021-01-19 10:28:03 +01:00
Guillaume Gomez 6af6c40a12
Rollup merge of #81115 - ssomers:btree_drainy_refactor_4, r=Mark-Simulacrum
BTreeMap: prefer bulk_steal functions over specialized ones

The `steal_` functions (apart from their return value) are basically specializations of the more general `bulk_steal_` functions. This PR removes the specializations. The library/alloc benchmarks say this is never slower and up to 6% faster.

r? ``@Mark-Simulacrum``
2021-01-19 10:27:54 +01:00
Guillaume Gomez de02bf399e
Rollup merge of #81112 - m-ou-se:alloc-std-ops-reexport, r=KodrAus
Remove unused alloc::std::ops re-export.

Removes unused re-export in alloc/lib.rs.
2021-01-19 10:27:53 +01:00
dylni b96063cf47 Fix soundness issue for `replace_range` and `range` 2021-01-18 22:14:38 -05:00
Lzu Tao 20d8478864 Fix intersperse_fold 2021-01-19 00:43:59 +00:00
CPerezz 9abd80c076
Fix internal rustdoc broken links
As it was suggested in #81037 `SpecFromIter` is not
in the scope and therefore (even it should fail),
we get a warning when we try do document private
intems in `rust/library/alloc/`.

This fixes #81037 by adding the trait in the scope
and also adding an `allow(unused_imports)` flag so that
the compiler does not complain, Since the trait is not used
per se in the code, it's just needed to have properly documented
docs.
2021-01-18 23:47:01 +01:00
bors d98d2f57d9 Auto merge of #80707 - oli-obk:stability_hole_const_intrinsics, r=RalfJung
Stability oddity with const intrinsics

cc `@RalfJung`

In https://github.com/rust-lang/rust/pull/80699#discussion_r551495670 `@usbalbin` realized we accepted some intrinsics as `const` without a `#[rustc_const_(un)stable]` attribute. I did some digging, and that example works because intrinsics inherit their stability from their parents... including `#[rustc_const_(un)stable]` attributes. While we may want to fix that (not sure, wasn't there just a MCPed PR that caused this on purpose?), we definitely want tests for it, thus this PR adding tests and some fun tracing statements.
2021-01-18 20:54:36 +00:00
bors 73f233b3ad Auto merge of #81159 - ssomers:btree_cleanup_search, r=Mark-Simulacrum
BTreeMap: convert search functions to methods

And further tweak the signature of `search_linear`, in preparation of a better #81094.

r? `@Mark-Simulacrum`
2021-01-18 17:30:38 +00:00
Konrad Borowski ae3a515337 Avoid hash_slice in VecDeque's Hash implementation
Fixes #80303.
2021-01-18 17:56:06 +01:00
Stein Somers 4775334f36 BTreeMap: prefer bulk_steal functions over specialized ones 2021-01-18 17:23:26 +01:00
soniasingla 47c2476c68 Fixes #81109 - Typo in pointer::wrapping_sub
Signed-off-by: soniasingla <soniasingla.1812@gmail.com>
2021-01-18 20:31:47 +05:30
Ralf Jung 712d065061 remove some outdated comments regarding debug assertions 2021-01-18 13:06:01 +01:00
Ashley Mannix 0654e20195
Rollup merge of #81123 - sirh3e:sirh3e-patch-1, r=sfackler
Update cmp.rs

Fixed space
2021-01-18 21:53:33 +10:00
oli 5bac1c9229 Only inherit const stability for methods of `impl const Trait` blocks 2021-01-18 11:07:35 +00:00
Ralf Jung dc04ceae71 use raw-ptr-addr-of for slice::swap 2021-01-18 11:24:48 +01:00
Stein Somers de6e53a327 BTreeMap: convert search functions to methods 2021-01-18 09:31:14 +01:00
bors 93e0aedb07 Auto merge of #81090 - ssomers:btree_drainy_refactor_2, r=Mark-Simulacrum
BTreeMap: offer merge in variants with more clarity

r? `@Mark-Simulacrum`
2021-01-18 02:43:19 +00:00
Nathan Nguyen 829f6bb672 fixed formatting typo in map_while 2021-01-17 18:14:58 -06:00
bors c4df63f47f Auto merge of #80537 - ehuss:macos-posix-spawn-chdir, r=dtolnay
Don't use posix_spawn_file_actions_addchdir_np on macOS.

There is a bug on macOS where using `posix_spawn_file_actions_addchdir_np` with a relative executable path will cause `posix_spawnp` to return ENOENT, even though it successfully spawned the process in the given directory.

`posix_spawn_file_actions_addchdir_np` was introduced in macOS 10.15 first released in Oct 2019.  I have tested macOS 10.15.7 and 11.0.1.

Example offending program:

```rust
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::process::*;

fn main() {
    fs::create_dir_all("bar").unwrap();
    fs::create_dir_all("foo").unwrap();
    fs::write("foo/foo.sh", "#!/bin/sh\necho hello ${PWD}\n").unwrap();
    let perms = fs::Permissions::from_mode(0o755);
    fs::set_permissions("foo/foo.sh", perms).unwrap();
    let c = Command::new("../foo/foo.sh").current_dir("bar").spawn();
    eprintln!("{:?}", c);
}
```

This prints:

```
Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
hello /Users/eric/Temp/bar
```

I wanted to open this PR to get some feedback on possible solutions.  Alternatives:
* Do nothing.
* Document the bug.
* Try to detect if the executable is a relative path on macOS, and avoid using `posix_spawn_file_actions_addchdir_np` only in that case.

I looked at the [XNU source code](https://opensource.apple.com/source/xnu/xnu-6153.141.1/bsd/kern/kern_exec.c.auto.html), but I didn't see anything obvious that would explain the behavior.  The actual chdir succeeds, it is something else further down that fails, but I couldn't see where.

EDIT: I forgot to mention, relative exe paths with `current_dir` in general are discouraged (see #37868).  I don't know if #37868 is fixable, since normalizing it would change the semantics for some platforms. Another option is to convert the executable to an absolute path with something like joining the cwd with the new cwd and the executable, but I'm uncertain about that.
2021-01-17 23:44:46 +00:00
oxalica 16deaec7f9
Format code 2021-01-18 02:11:01 +08:00
bors 1f0fc02cc8 Auto merge of #80524 - jyn514:unknown-tool-lints, r=flip1995,matthewjasper
Don't make tools responsible for checking unknown and renamed lints

Previously, clippy (and any other tool emitting lints) had to have their
own separate UNKNOWN_LINTS pass, because the compiler assumed any tool
lint could be valid. Now, as long as any lint starting with the tool
prefix exists, the compiler will warn when an unknown lint is present.

This may interact with the unstable `tool_lint` feature, which I don't entirely understand, but it will take the burden off those external tools to add their own lint pass, which seems like a step in the right direction to me.

- Don't mark `ineffective_unstable_trait_impl` as an internal lint
- Use clippy's more advanced lint suggestions
- Deprecate the `UNKNOWN_CLIPPY_LINTS` pass (and make it a no-op)
- Say 'unknown lint `clippy::x`' instead of 'unknown lint x'

This is tested by existing clippy tests. When https://github.com/rust-lang/rust/pull/80527 merges, it will also be tested in rustdoc tests. AFAIK there is no way to test this with rustc directly.
2021-01-17 17:52:01 +00:00
Eric Huss a938725ef7 Don't use posix_spawn_file_actions_addchdir_np on macOS. 2021-01-17 09:51:02 -08:00
oxalica d6dec1ebe3
Optimize Vec::retain 2021-01-18 01:48:50 +08:00
Marvin Huber 7276b6c328
Update cmp.rs
Fixed space
2021-01-17 16:11:48 +01:00
bors edeb631ad0 Auto merge of #81113 - m-ou-se:rollup-a1unz4x, r=m-ou-se
Rollup of 13 pull requests

Successful merges:

 - #79298 (correctly deal with late-bound lifetimes in anon consts)
 - #80031 (resolve: Reject ambiguity built-in attr vs different built-in attr)
 - #80201 (Add benchmark and fast path for BufReader::read_exact)
 - #80635 (Improve diagnostics when closure doesn't meet trait bound)
 - #80765 (resolve: Simplify collection of traits in scope)
 - #80932 (Allow downloading LLVM on Windows and MacOS)
 - #80983 (Remove is_dllimport_foreign_item definition from cg_ssa)
 - #81064 (Support non-stage0 check)
 - #81080 (Force vec![] to expression position only)
 - #81082 (BTreeMap: clean up a few more comments)
 - #81084 (Use Option::map instead of open-coding it)
 - #81095 (Use Option::unwrap_or instead of open-coding it)
 - #81107 (Add NonZeroUn::is_power_of_two)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-01-17 14:50:24 +00:00
Mara Bos 801684620b
Rollup merge of #81107 - scottmcm:nonzero-is_power_of_two, r=kennytm
Add NonZeroUn::is_power_of_two

This saves instructions on both new and old machines <https://rust.godbolt.org/z/4fjTMz>
- On the default x64 target (with no fancy instructions available) it saves a few instructions by not needing to also check for zero.
- On newer targets (with BMI1) it uses `BLSR` for super-short assembly.

This can be used for things like checks against alignments stored in `NonZeroUsize`.
2021-01-17 12:25:01 +00:00
Mara Bos 366f97bf8c
Rollup merge of #81082 - ssomers:btree_cleanup_comments, r=Mark-Simulacrum
BTreeMap: clean up a few more comments

And mark `pop` as unsafe.
r? ```@Mark-Simulacrum```
2021-01-17 12:24:56 +00:00
Mara Bos 19370a4860
Rollup merge of #81080 - bugadani:vec-diag, r=oli-obk,m-ou-se
Force vec![] to expression position only

r? `@oli-obk`

I went with the lazy way of only changing what broke. I moved the test to ui/macros because the diagnostics no longer give suggestions.

Closes #61933
2021-01-17 12:24:54 +00:00
Mara Bos 152f425dcb
Rollup merge of #80201 - saethlin:bufreader-read-exact, r=KodrAus
Add benchmark and fast path for BufReader::read_exact

At work, we have a wrapper type that implements this optimization. It would be nice if the standard library were faster.

Before:
```
test io::buffered::tests::bench_buffered_reader_small_reads       ... bench:       7,670 ns/iter (+/- 45)
```
After:
```
test io::buffered::tests::bench_buffered_reader_small_reads       ... bench:       4,457 ns/iter (+/- 41)
```
2021-01-17 12:24:42 +00:00
bors 7d3818152d Auto merge of #81058 - Smittyvb:wasm-num-tests, r=Mark-Simulacrum
Re-enable all num tests on WASM

This was partially done by #47365, but a few tests were missed in that PR.
2021-01-17 11:51:47 +00:00
Dániel Buga c127ed6e97 Force vec! to expressions only 2021-01-17 12:48:25 +01:00
Mara Bos ff5dcc2438 Remove unused alloc::std::ops re-export. 2021-01-17 12:08:38 +01:00
bors d51cf9601c Auto merge of #81083 - ssomers:btree_drainy_refactor_1, r=Mark-Simulacrum
BTreeMap: expose new_internal function and sanitize from_new_internal

`new_internal` is the functional core of the imperative `push_internal_level`, and `from_new_internal` can easily do a proper job instead of returning a half-baked node.

r? `@Mark-Simulacrum`
2021-01-17 08:44:12 +00:00
bors 49d7889da4 Auto merge of #78818 - scottmcm:as_rchunks, r=KodrAus
Add `as_rchunks` (and friends) to slices

`@est31` mentioned (https://github.com/rust-lang/rust/issues/76354#issuecomment-717027175) that, for completeness, there needed to be an `as_chunks`-like method that chunks from the end (with the remainder at the beginning) like `rchunks` does.

So here's a PR for `as_rchunks: &[T] -> (&[T], &[[T; N]])` and `as_rchunks_mut: &mut [T] -> (&mut [T], &mut [[T; N]])`.

But as I was doing this and copy-pasting `from_raw_parts` calls, I thought that I should extract that into an unsafe method.  It started out a private helper, but it seemed like `as_chunks_unchecked` could be reasonable as a "real" method, so I added docs and made it public.  Let me know if you think it doesn't pull its weight.
2021-01-17 05:43:55 +00:00
Scott McMurray 3e16e9211e Add NonZeroUn::is_power_of_two
This saves instructions on both new and old machines.
2021-01-16 19:27:51 -08:00
Ben Kimock 4e27ed3af1 Add benchmark and fast path for BufReader::read_exact 2021-01-17 12:10:39 +10:00
bors 8a6518427e Auto merge of #81089 - m-ou-se:rollup-z7iac6i, r=m-ou-se
Rollup of 17 pull requests

Successful merges:

 - #78455 (Introduce {Ref, RefMut}::try_map for optional projections in RefCell)
 - #80144 (Remove giant badge in README)
 - #80614 (Explain why borrows can't be held across yield point in async blocks)
 - #80670 (TrustedRandomAaccess specialization composes incorrectly for nested iter::Zips)
 - #80681 (Clarify what the effects of a 'logic error' are)
 - #80764 (Re-stabilize Weak::as_ptr and friends for unsized T)
 - #80901 (Make `x.py --color always` apply to logging too)
 - #80902 (Add a regression test for #76281)
 - #80941 (Do not suggest invalid code in pattern with loop)
 - #80968 (Stabilize the poll_map feature)
 - #80971 (Put all feature gate tests under `feature-gates/`)
 - #81021 (Remove doctree::Import)
 - #81040 (doctest: Reset errors before dropping the parse session)
 - #81060 (Add a regression test for #50041)
 - #81065 (codegen_cranelift: Fix redundant semicolon warn)
 - #81069 (Add sample code for Rc::new_cyclic)
 - #81081 (Add test for #34792)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-01-16 20:26:20 +00:00
Stein Somers bb61cc48b3 BTreeMap: offer merge in variants with more clarity 2021-01-16 18:56:03 +01:00
Mara Bos dd86fc6228
Rollup merge of #81069 - ogoffart:rc_new_cyclic_doc, r=Mark-Simulacrum
Add sample code for Rc::new_cyclic
2021-01-16 17:30:15 +00:00
Mara Bos dba6c9c6d1
Rollup merge of #80968 - KodrAus:stabilize/poll_map, r=Mark-Simulacrum
Stabilize the poll_map feature

Stabilizes the `poll_map` feature as tracked by #63514 (with a completed FCP).
2021-01-16 17:30:04 +00:00
Mara Bos 5702cfa255
Rollup merge of #80764 - CAD97:weak-unsized-as-ptr-again, r=RalfJung
Re-stabilize Weak::as_ptr and friends for unsized T

As per [T-lang consensus](https://hackmd.io/7r3_is6uTz-163fsOV8Vfg), this uses a branch to handle the dangling case. The discussed optimization of only doing the branch in the T: ?Sized case is left for a followup patch, as doing so is not trivial (as it requires specialization) and not _obviously_ better (as it requires using `wrapping_offset` rather than `offset` more).

<details><summary>Basically said optimization</summary>

Specialize on `T: Sized`:

```rust
fn as_ptr(&self) -> *const T {
    if [ T is Sized ] || !is_dangling(ptr) {
        (ptr as *mut T).set_ptr_value( (ptr as *mut u8).wrapping_offset(data_offset) )
    } else {
        ptr::null()
    }
}

fn from_raw(*const T) -> Self {
    if [ T is Sized ] || !ptr.is_null() {
        let ptr = (ptr as *mut RcBox).set_ptr_value( (ptr as *mut u8).wrapping_offset(-data_offset) );
        Weak { ptr }
    } else {
        Weak::new()
    }
}
```

(but with more `set_ptr_value` to avoid `Sized` restrictions and maintain metadata.)

Written in this fashion, this is not a correctness-critical specialization (i.e. so long as `[ T is Sized ]` is false for unsized `T`, it can be `rand()` for sized `T` without breaking correctness), but it's still touchy, so I'd rather do it in another PR with separate review.

---
</details>

This effectively reverts #80422 and re-establishes #74160. T-libs [previously signed off](https://github.com/rust-lang/rust/pull/74160#issuecomment-660539373) on this stable API change in #74160.
2021-01-16 17:29:56 +00:00
Mara Bos 40d2506cab
Rollup merge of #80681 - ChrisJefferson:logic-error-doc, r=m-ou-se
Clarify what the effects of a 'logic error' are

This clarifies what a 'logic error' is (which is a term used to describe what happens if you put things in a hash table or btree and then use something like a refcell to break the internal ordering). This tries to be as vague as possible, as we don't really want to promise what happens, except "bad things, but not UB". This was discussed in #80657
2021-01-16 17:29:53 +00:00
Mara Bos d8843d9d82
Rollup merge of #80670 - the8472:fix-zip-trusted-random-access-composition, r=m-ou-se
TrustedRandomAaccess specialization composes incorrectly for nested iter::Zips

I found this while working on improvements for TRA.

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

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

Included test fails on nightly, [playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=24fa1edf8a104ff31f5a24830593b01f)
2021-01-16 17:29:51 +00:00
Mara Bos 6bb06f4f23
Rollup merge of #78455 - udoprog:refcell-opt-map, r=KodrAus
Introduce {Ref, RefMut}::try_map for optional projections in RefCell

This fills a usability gap of `RefCell` I've personally encountered to perform optional projections, mostly into collections such as `RefCell<Vec<T>>` or `RefCell<HashMap<U, T>>`:

> This kind of API was briefly featured under Open questions in #10514 back in 2013 (!)

```rust
let values = RefCell::new(vec![1, 2, 3, 4]);
let b = Ref::opt_map(values.borrow(), |vec| vec.get(2));
```

It primarily avoids this alternative approach to accomplish the same kind of projection which is both rather noisy and panicky:
```rust
let values = RefCell::new(vec![1, 2, 3, 4]);

let b = if values.get(2).is_some() {
    Some(Ref::map(values.borrow(), |vec| vec.get(2).unwrap()))
} else {
    None
};
```

### Open questions

The naming `opt_map` is preliminary. I'm not aware of prior art in std to lean on here, but this name should probably be improved if this functionality is desirable.

Since `opt_map` consumes the guard, and alternative syntax might be more appropriate which instead *tries* to perform the projection, allowing the original borrow to be recovered in case it fails:

```rust
pub fn try_map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Result<Ref<'b, U>, Self>
where
    F: FnOnce(&T) -> Option<&U>;
```

This would be more in line with the `try_map` method [provided by parking lot](https://docs.rs/lock_api/0/lock_api/struct.RwLockWriteGuard.html#method.try_map).
2021-01-16 17:29:45 +00:00
bors 492b83c697 Auto merge of #80290 - RalfJung:less-intrinsic-write, r=lcnr
implement ptr::write without dedicated intrinsic

This makes `ptr::write` more consistent with `ptr::write_unaligned`, `ptr::read`, `ptr::read_unaligned`, all of which are implemented in terms of `copy_nonoverlapping`.

This means we can also remove `move_val_init` implementations in codegen and Miri, and its special handling in the borrow checker.

Also see [this Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/ptr.3A.3Aread.20vs.20ptr.3A.3Awrite).
2021-01-16 17:28:32 +00:00
Stein Somers d199c5b020 BTreeMap: expose new_internal function and sanitize from_new_internal 2021-01-16 17:07:38 +01:00
Stein Somers 50ee0b2986 BTreeMap: clean up a few more comments 2021-01-16 16:20:00 +01:00
bors 410a546fc5 Auto merge of #77435 - hanmertens:binary_heap_append, r=scottmcm
Always use extend in BinaryHeap::append

This is faster, see #77433.

Fixes #77433
2021-01-16 11:10:13 +00:00
Chris Jefferson 78d919280d Clarify what the effects of a 'logic error' are 2021-01-16 09:36:28 +00:00
Olivier Goffart 9952632a2f Add sample code for Rc::new_cyclic 2021-01-16 10:29:21 +01:00
bors efdb859dcd Auto merge of #80873 - ssomers:btree_cleanup_slices_4, r=Mark-Simulacrum
BTreeMap: tougher checks on code using raw into_kv_pointers

r? `@Mark-Simulacrum`
2021-01-16 07:12:12 +00:00
Scott McMurray 132307c685 Rename as_chunks_mut_unchecked -> as_chunks_unchecked_mut 2021-01-15 21:25:30 -08:00
Scott McMurray ae4b5a21e6 Add `as_rchunks` (and friends) to slices 2021-01-15 21:24:38 -08:00
Ashley Mannix c625b979ae
add tracking issue to cell_filter_map 2021-01-16 10:40:36 +10:00
Joshua Nelson c819a4c025 Don't mark `ineffective_unstable_trait_impl` as an internal lint
It's not an internal lint:
- It's not in the rustc::internal lint group
- It's on unconditionally, because it actually lints `staged_api`, not
  the compiler

This fixes a bug where `#[deny(rustc::internal)]` would warn that
`rustc::internal` was an unknown lint.
2021-01-15 17:31:10 -05:00
Smitty e10555c658 Re-enable all num tests on WASM
This was partially done by #47365, but a few tests
were missed in that PR.
2021-01-15 16:58:44 -05:00
James Wright bb2a27ba4f
Update library/std/src/thread/mod.rs
Fix link reference

Co-authored-by: Joshua Nelson <joshua@yottadb.com>
2021-01-15 21:41:26 +00:00
James Wright 8a85a85cea Clarify difference between unix/windows behaviour
Updated to specify the underlying syscalls
2021-01-15 21:18:44 +00:00
Han Mertens 32a20f4433 Change rebuild heuristic in BinaryHeap::append
See #77433 for why the new heuristic was chosen.

Fixes #77433
2021-01-15 21:50:05 +01:00
Yoshua Wuyts b50df6d31c Stabilize `core::slice::fill_with` 2021-01-15 18:51:09 +01:00
John-John Tedro e8757af311 Use Result and rename to filter_map
The use of Result allows for making use of a reconstructed original value on failed
projections.
2021-01-15 17:52:48 +01:00
John-John Tedro 0660b8b5a5 Introduce {Ref, RefMut}::try_map for optional projections 2021-01-15 13:47:00 +01:00
Yuki Okushi 1b8fd02daa
Rollup merge of #80834 - bugadani:vecdeque, r=oli-obk
Remove unreachable panics from VecDeque::{front/back}[_mut]

`VecDeque`'s `front`, `front_mut`, `back` and `back_mut` methods are implemented in terms of the index operator, which causes these functions to contain [unreachable panic calls](https://rust.godbolt.org/z/MTnq1o).

This PR reimplements these methods in terms of `get[_mut]` instead.
2021-01-15 18:26:11 +09:00
Jacob Pratt f55029ab04
Stabilize intrinsics as const 2021-01-14 18:55:37 -05:00
Alex Crichton 5756bd7f2d std: Update wasi-libc commit of the wasm32-wasi target
This brings in an implementation of `current_dir` and `set_current_dir`
(emulation in `wasi-libc`) as well as an updated version of finding
relative paths. This also additionally updates clang to the latest
release to build wasi-libc with.
2021-01-14 10:40:10 -08:00
Dániel Buga 744f885e2a Remove unreachable panics from VecDeque 2021-01-14 19:31:56 +01:00
Mara Bos 9c75ee6b3b
Rollup merge of #80991 - calebsander:fix/fmt-link, r=m-ou-se
Fix formatting specifiers doc links

d36e3e23a8 seems to have inadvertently changed many of these links to point to `core::fmt` instead of `std::fmt`. The information about formatting specifiers is only documented in [`std::fmt`](https://doc.rust-lang.org/std/fmt/); [`core::fmt`](https://doc.rust-lang.org/core/fmt/) is empty. 3baf6a4a74 seems to have already fixed a couple of these links to point back to `std::fmt`.
2021-01-14 18:00:31 +00:00
Mara Bos c504e89bc7
Rollup merge of #80985 - ijackson:slice-strip-fix, r=jyn514
Fix stabilisation version of slice_strip

See https://github.com/rust-lang/rust/pull/77853#pullrequestreview-564921079

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-14 18:00:27 +00:00
Mara Bos d5e55cee99
Rollup merge of #80980 - trevarj:patch-1, r=nagisa
Fixed incorrect doc comment

">" is right alignment, not left
2021-01-14 18:00:22 +00:00
Mara Bos 9bfe6f1b2c
Rollup merge of #80972 - KodrAus:deprecate/remove_item, r=nagisa
Remove unstable deprecated Vec::remove_item

Closes #40062

The `Vec::remove_item` method was deprecated in `1.46.0` (in August of 2020). This PR now removes that unstable method entirely.
2021-01-14 18:00:18 +00:00
Mara Bos 7855a730b9
Rollup merge of #80966 - KodrAus:deprecate/spin_loop_hint, r=m-ou-se
Deprecate atomic::spin_loop_hint in favour of hint::spin_loop

For https://github.com/rust-lang/rust/issues/55002

We wanted to leave `atomic::spin_loop_hint` alone when stabilizing `hint::spin_loop` so folks had some time to migrate. This now deprecates `atomic_spin_loop_hint`.
2021-01-14 18:00:14 +00:00
Mara Bos ce48709405
Rollup merge of #80895 - sfackler:read-to-end-ub, r=m-ou-se
Fix handling of malicious Readers in read_to_end

A malicious `Read` impl could return overly large values from `read`, which would result in the guard's drop impl setting the buffer's length to greater than its capacity! ~~To fix this, the drop impl now uses the safe `truncate` function instead of `set_len` which ensures that this will not happen. The result of calling the function will be nonsensical, but that's fine given the contract violation of the `Read` impl.~~

~~The `Guard` type is also used by `append_to_string` which does not pass untrusted values into the length field, so I've copied the guard type into each function and only modified the one used by `read_to_end`. We could just keep a single one and modify it, but it seems a bit cleaner to keep the guard code close to the functions and related specifically to them.~~

To fix this, we now assert that the returned length is not larger than the buffer passed to the method.

For reference, this bug has been present for ~2.5 years since 1.20: ecbb896b9e.

Closes #80894.
2021-01-14 18:00:11 +00:00
Mara Bos 446ed77124
Rollup merge of #80567 - lukaslueg:intersperse_with, r=m-ou-se
Add Iterator::intersperse_with

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

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

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

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

Happy New Year!

r? ``@m-ou-se``
2021-01-14 18:00:06 +00:00
Mara Bos 3308b43ba1
Rollup merge of #80444 - glittershark:bound-as-ref, r=dtolnay
Add as_ref and as_mut methods for Bound

Add as_ref and as_mut method for std::ops::range::Bound, patterned off
of the methods of the same name on Option.

I'm not quite sure what the process is for introducing new feature gates (this is my first contribution) so I've left these ungated, but happy to do whatever is necessary to gate them.
2021-01-14 18:00:02 +00:00
Mara Bos 9fc298ca89
Rollup merge of #80217 - camelid:io-read_to_string, r=m-ou-se
Add a `std::io::read_to_string` function

I recognize that you're usually supposed to open an issue first, but the
implementation is very small so it's okay if this is closed and it was 'wasted
work' :)

-----

The equivalent of `std::fs::read_to_string`, but generalized to all
`Read` impls.

As the documentation on `std::io::read_to_string` says, the advantage of
this function is that it means you don't have to create a variable first
and it provides more type safety since you can only get the buffer out
if there were no errors. If you use `Read::read_to_string`, you have to
remember to check whether the read succeeded because otherwise your
buffer will be empty.

It's friendlier to newcomers and better in most cases to use an explicit
return value instead of an out parameter.
2021-01-14 18:00:00 +00:00
Mara Bos 930371b3ae
Rollup merge of #80169 - frewsxcv:frewsxcv-docs-fix, r=jyn514
Recommend panic::resume_unwind instead of panicking.

Fixes https://github.com/rust-lang/rust/issues/79950.
2021-01-14 17:59:57 +00:00
Mara Bos 8ac21fb201
Rollup merge of #79982 - ijackson:exit-status, r=dtolnay
Add missing methods to unix ExitStatusExt

These are the methods corresponding to the remaining exit status examination macros from `wait.h`.  `WCOREDUMP` isn't in SuS but is it is very standard.  I have not done portability testing to see if this builds everywhere, so I may need to Do Something if it doesn't.

There is also a bugfix and doc improvement to `.signal()`, and an `.into_raw()` accessor.

This would fix #73128 and fix #73129.  Please let me know if you like this direction, and if so I will open the tracking issue and so on.

If this MR goes well, I may tackle #73125 next - I have an idea for how to do it.
2021-01-14 17:59:53 +00:00
David Tolnay a8d0161960
Fix typos in Fuchsia unix_process_wait_more 2021-01-13 22:13:45 -08:00
Philippe Laflamme 64d695b753
Adds tests to ensure some base op traits exist.
These tests invoke the various op traits using all accepted types they
are implemented for as well as for references to those types.

This fixes #49660 and ensures the following implementations exist:

* `Add`, `Sub`, `Mul`, `Div`, `Rem`
  * `T op T`, `T op &T`, `&T op T` and `&T op &T`
  * for all integer and floating point types
* `AddAssign`, `SubAssign`, `MulAssign`, `DivAssign`, `RemAssign`
  * `&mut T op T` and `&mut T op &T`
  * for all integer and floating point types
* `Neg`
  * `op T` and `op &T`
  * for all signed integer and floating point types
* `Not`
  * `op T` and `op &T`
  * for `bool`
* `BitAnd`, `BitOr`, `BitXor`
  * `T op T`, `T op &T`, `&T op T` and `&T op &T`
  * for all integer types and bool
* `BitAndAssign`, `BitOrAssign`, `BitXorAssign`
  * `&mut T op T` and `&mut T op &T`
  * for all integer types and bool
* `Shl`, `Shr`
  * `L op R`, `L op &R`, `&L op R` and `&L op &R`
  * for all pairs of integer types
* `ShlAssign`, `ShrAssign`
  * `&mut L op R`, `&mut L op &R`
  * for all pairs of integer types
2021-01-13 23:14:00 -05:00
Philippe Laflamme 8ddad18283
Avoid ident concatenation in macro.
AFAIK it isn't currently possible to do this. It is also more in line with other tests in the surrounding modules.
2021-01-13 23:13:55 -05:00
Philippe Laflamme 872dc60ed2
Fix missing mod declaration for Wrapping tests. 2021-01-13 23:13:49 -05:00
Griffin Smith eb72dc5d40 Add as_ref and as_mut methods for Bound
Add as_ref and as_mut method for std::ops::range::Bound, patterned off
of the methods of the same name on Option.
2021-01-13 21:16:26 -05:00
Jacob Pratt edf2e3725e
Use unsigned_abs throughout repository 2021-01-13 17:58:08 -05:00
Christopher Durham c14e919f1e
Apply suggestions from code review
Co-authored-by: Ralf Jung <post@ralfj.de>
2021-01-13 17:21:23 -05:00
bors a62a76047e Auto merge of #77524 - Patryk27:fixes/66228, r=estebank
Rework diagnostics for wrong number of generic args (fixes #66228 and #71924)

This PR reworks the `wrong number of {} arguments` message, so that it provides more details and contextual hints.
2021-01-13 20:35:58 +00:00
Lukas Lueg 9b2f085110 Improve Iterator::intersperse_ docs 2021-01-13 21:07:59 +01:00
Caleb Sander 391b4cc378 Fix formatting specifiers doc link
Was incorrectly linked to `core::fmt`, which is empty, in d36e3e23a8
Some of the links were fixed already in 3baf6a4a74
2021-01-13 15:05:39 -05:00
Lukas Lueg 95289889fe Add doc intralinks 2021-01-13 19:47:41 +01:00
Ian Jackson b59fa3d634 Fix stabilisation version of slice_strip
See https://github.com/rust-lang/rust/pull/77853#pullrequestreview-564921079

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 14:21:18 +00:00
bors fd2df74902 Auto merge of #76219 - Mark-Simulacrum:extern-require-abi, r=estebank
Add allow-by-default lint on implicit ABI in extern function pointers and items

This adds a new lint, missing_abi, which lints on omitted ABIs on extern blocks, function declarations, and function pointers.

It is currently not emitting the best possible diagnostics -- we need to track the span of "extern" at least or do some heuristic searching based on the available spans -- but seems good enough for an initial pass than can be expanded in future PRs.

This is a pretty large PR, but mostly due to updating a large number of tests to include ABIs; I can split that into a separate PR if it would be helpful, but test updates are already in dedicated commits.
2021-01-13 13:56:15 +00:00
Ian Jackson 05a88aabc1 ExitStatusExt: Fix build on Fuchsia
This is not particularly pretty but the current situation is a mess
and I don't think I'm making it significantly worse.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 13:27:30 +00:00
David Tolnay efddf5949f Fix typo saeled -> sealed 2021-01-13 12:50:29 +00:00
Ian Jackson f3e7199a79 ExitStatusExt windows: Retrospectively seal this trait
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson 70121941ff ExitStatusExt unix: Retrospectively seal this trait
As discussed in #79982.

I think the "new interfaces", ie the new trait and impl, must be
insta-stable.  This seems OK because we are, in fact, adding a new
restriction to the stable API.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson fa68567a1f unix ExitStatus: Add tracking issue to new methods
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson 06a405c49c Replace `Ie` with `In other words`
Co-authored-by: Joshua Nelson <joshua@yottadb.com>
2021-01-13 12:50:29 +00:00
Ian Jackson 29c851aef6 Replace `Ie` with `In other words`
Co-authored-by: Joshua Nelson <joshua@yottadb.com>
2021-01-13 12:50:29 +00:00
Ian Jackson 42ea8f6434 unix ExitStatus: Provide .continued()
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson f060b9e0d9 unix ExitStatus: Provide .stopped_signal()
Necessary to handle WIFSTOPPED.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson 3f05051d6b unix ExitStatus: Provide .core_dumped
This is essential for proper reporting of child process status on Unix.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson 530270f94a unix ExitStatus: Provide .into_raw()
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00
Ian Jackson 12d62aa436 unix ExitStatus: Clarify docs for .signal()
We need to be clear that this never returns WSTOPSIG.  That is, if
WIFSTOPPED, the return value is None.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-01-13 12:50:29 +00:00