Commit Graph

1969 Commits

Author SHA1 Message Date
Ralf Jung
46b2454bad clarify Arc::clone overflow check comment 2022-06-21 21:14:03 -07:00
Ralf Jung
1ca8b69e1c remove use of &Alloc in btree tests 2022-06-21 16:38:12 -07:00
Dylan DPC
7372bf88ee
Rollup merge of #96609 - ibraheemdev:arc-downcast-unchecked, r=m-ou-se
Add `{Arc, Rc}::downcast_unchecked`

Part of #90850.
2022-06-20 14:56:35 +02:00
jmaargh
95dc353006 Fix documentation for with_capacity and reserve families of methods
Documentation for the following methods

    with_capacity
    with_capacity_in
    with_capacity_and_hasher
    reserve
    reserve_exact
    try_reserve
    try_reserve_exact

was inconsistent and often not entirely correct where they existed on the following types

    Vec
    VecDeque
    String
    OsString
    PathBuf
    BinaryHeap
    HashSet
    HashMap
    BufWriter
    LineWriter

since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked BufReader, but there the docs appear to be accurate as it appears to actually allocate the exact capacity).

Some effort was made to make the documentation more consistent between types as well.

Fix with_capacity* methods for Vec

Fix *reserve*  methods for Vec

Fix docs for *reserve* methods of VecDeque

Fix docs for String::with_capacity

Fix docs for *reserve* methods of String

Fix docs for OsString::with_capacity

Fix docs for *reserve* methods on OsString

Fix docs for with_capacity* methods on HashSet

Fix docs for *reserve methods of HashSet

Fix docs for with_capacity* methods of HashMap

Fix docs for *reserve methods on HashMap

Fix expect messages about OOM in doctests

Fix docs for BinaryHeap::with_capacity

Fix docs for *reserve* methods of BinaryHeap

Fix typos

Fix docs for with_capacity on BufWriter and LineWriter

Fix consistent use of `hasher` between `HashMap` and `HashSet`

Fix warning in doc test

Add test for capacity of vec with ZST

Fix doc test error
2022-06-19 20:46:49 +01:00
Dylan DPC
6a2a56da45
Rollup merge of #98233 - RalfJung:ref-alloc, r=thomcc
Remove accidental uses of `&A: Allocator`

Cc https://github.com/rust-lang/rust/issues/98232

Fixes https://github.com/rust-lang/rust/issues/98176 (for real this time)
2022-06-19 15:26:31 +02:00
Ralf Jung
7952205bc8 make btree not use &A: Allocator instance 2022-06-18 07:37:41 -07:00
bors
2cec6874c0 Auto merge of #98004 - paolobarbolini:vecdeque-extend-trustedlen, r=the8472
Add VecDeque::extend from TrustedLen specialization

Continuation of #95904

Inspired by how [`VecDeque::copy_slice` works](c08b235a5c/library/alloc/src/collections/vec_deque/mod.rs (L437-L454)).

## Benchmarks

Before

```
test vec_deque::bench_extend_chained_bytes      ... bench:       1,026 ns/iter (+/- 17)
test vec_deque::bench_extend_chained_trustedlen ... bench:       1,024 ns/iter (+/- 40)
test vec_deque::bench_extend_trustedlen         ... bench:         637 ns/iter (+/- 693)
```

After

```
test vec_deque::bench_extend_chained_bytes      ... bench:         828 ns/iter (+/- 24)
test vec_deque::bench_extend_chained_trustedlen ... bench:          25 ns/iter (+/- 1)
test vec_deque::bench_extend_trustedlen         ... bench:          21 ns/iter (+/- 0)
```

## Why do it this way

https://rust.godbolt.org/z/15qY1fMYh

The Compiler Explorer example shows how "just" removing the capacity check, like the [`Vec` `TrustedLen` specialization](c08b235a5c/library/alloc/src/vec/spec_extend.rs (L22-L58)) does, wouldn't have been enough for `VecDeque`. `wrap_add` would still have greatly limited what LLVM could do while optimizing.

---

r? `@the8472`
2022-06-18 12:54:01 +00:00
bors
ff86b27e7b Auto merge of #98178 - RalfJung:btree-alloc, r=thomcc
btree: avoid forcing the allocator to be a reference

The previous code forces the actual allocator used to be some `&A`. This generalizes the code to allow any `A: Copy`. If people truly want to use a reference, they can use `&A` themselves.

Fixes https://github.com/rust-lang/rust/issues/98176
2022-06-18 05:12:40 +00:00
Kevin Reid
5dcc418f62 Document the conditional existence of alloc::sync and alloc::task.
The wording is copied from `std::sync::atomic::AtomicPtr`, with
additional advice on how to `#[cfg]` for it.
2022-06-17 20:03:23 -07:00
Ralf Jung
3a1e114120 comments explaining why we have and don't have ManuallyDrop 2022-06-17 16:23:51 -07:00
Paolo Barbolini
ce3b6f505e Expose iter::ByRefSized as unstable feature and use it 2022-06-18 00:03:54 +02:00
Paolo Barbolini
bc3fae4dc1 Add VecDeque::extend from TrustedLen specialization 2022-06-18 00:03:54 +02:00
Paolo Barbolini
ac2c21a623 Add VecDeque::extend TrustedLen benchmark 2022-06-17 23:41:03 +02:00
Dylan DPC
b516806774
Rollup merge of #95392 - Xuanwo:stablize_try_reserve_2, r=dtolnay
std: Stabilize feature try_reserve_2

This PR intends to stabilize feature `try_reserve_2`, closes https://github.com/rust-lang/rust/issues/91789

This PR will also replace the previous PR: https://github.com/rust-lang/rust/pull/95139
2022-06-17 12:21:46 +02:00
Ralf Jung
901cd3a844 btree: avoid forcing the allocator to be a reference 2022-06-16 22:07:10 -07:00
Matthias Krüger
f4297b06e8
Rollup merge of #98125 - KarlWithK:entry_add_modify_doc, r=Dylan-DPC
Entry and_modify doc

This PR modifies the documentation for [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html#) and [BTreeMap](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#) by introducing examples for `and_modify`. `and_modify` is a function that tends to give more idiomatic rust code when dealing with these data structures -- yet it lacked examples and was hidden away. This PR adds that and addresses #98122.

I've made some choices which I tried to explain in my commits. This is my first time contributing to rust, so hopefully, I made the right choices.
2022-06-16 09:10:21 +02:00
Xuanwo
324286f101
std: Stabilize feature try_reserve_2
Signed-off-by: Xuanwo <github@xuanwo.io>
2022-06-16 09:30:34 +08:00
KarlWithK
791923aacb
change "1" to "c" to pass test
Incorrectly wrote "1" twice when writing test.
2022-06-15 03:19:22 -05:00
KarlWithK
cec72acdca
Add examples using add_modify to btree
Updated the btree's documentation to include two references to
add_modify.

The first is when the `Entry` API is mentioned at the beginning. With
the same reasoning as HashMap's documentation, I thought it would best
to keep `attack`, but show the `mana` example.

The second is with the `entry` function that is used for the `Entry`
API. The code example was a perfect use for `add_modify`, which is why
it was changed to reflect that.
2022-06-15 02:04:18 -05:00
Jacob Hughes
417b20835d btreemap-alloc: fix clear impl 2022-06-14 13:54:10 -04:00
Jacob Hughes
dc5951a6e5 BTreeMap: Add alloc param 2022-06-14 13:54:03 -04:00
Dylan DPC
4b1d510e0c
Rollup merge of #97869 - ssomers:btree_comments, r=Dylan-DPC
BTree: tweak internal comments
2022-06-14 10:35:29 +02:00
bvanjoi
7c861cf0ad additional docs example for replace **all** of str 2022-06-10 00:28:46 +08:00
bors
be16c6166f Auto merge of #97868 - ssomers:btree_from_sorted_iter, r=the8472
BTreeSet: avoid intermediate sorting when collecting sorted iterators

As [pointed out by droundy](https://users.rust-lang.org/t/question-about-btreeset-implementation/76427), an obvious optimization is to skip the first step introduced by #88448 (creation of a vector and sorting) and it's easy to do so for btree's own iterators. Also, exploit `from` in the examples.
2022-06-09 10:17:04 +00:00
Yuki Okushi
2b58e6314a
Stabilize const_intrinsic_copy 2022-06-08 20:17:28 +09:00
Stein Somers
49ccb7519f BTreeSet: avoid intermediate sorting when collecting sorted iterators 2022-06-08 12:42:31 +02:00
Stein Somers
6f92f5ab66 BTree: tweak internal comments 2022-06-08 12:22:18 +02:00
bors
bb55bd449e Auto merge of #95565 - jackh726:remove-borrowck-mode, r=nikomatsakis
Remove migrate borrowck mode

Closes #58781
Closes #43234

# Stabilization proposal

This PR proposes the stabilization of `#![feature(nll)]` and the removal of `-Z borrowck`. Current borrow checking behavior of item bodies is currently done by first infering regions *lexically* and reporting any errors during HIR type checking. If there *are* any errors, then MIR borrowck (NLL) never occurs. If there *aren't* any errors, then MIR borrowck happens and any errors there would be reported. This PR removes the lexical region check of item bodies entirely and only uses MIR borrowck. Because MIR borrowck could never *not* be run for a compiled program, this should not break any programs. It does, however, change diagnostics significantly and allows a slightly larger set of programs to compile.

Tracking issue: #43234
RFC: https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md
Version: 1.63 (2022-06-30 => beta, 2022-08-11 => stable).

## Motivation

Over time, the Rust borrow checker has become "smarter" and thus allowed more programs to compile. There have been three different implementations: AST borrowck, MIR borrowck, and polonius (well, in progress). Additionally, there is the "lexical region resolver", which (roughly) solves the constraints generated through HIR typeck. It is not a full borrow checker, but does emit some errors.

The AST borrowck was the original implementation of the borrow checker and was part of the initially stabilized Rust 1.0. In mid 2017, work began to implement the current MIR borrow checker and that effort ompleted by the end of 2017, for the most part. During 2018, efforts were made to migrate away from the AST borrow checker to the MIR borrow checker - eventually culminating into "migrate" mode - where HIR typeck with lexical region resolving following by MIR borrow checking - being active by default in the 2018 edition.

In early 2019, migrate mode was turned on by default in the 2015 edition as well, but with MIR borrowck errors emitted as warnings. By late 2019, these warnings were upgraded to full errors. This was followed by the complete removal of the AST borrow checker.

In the period since, various errors emitted by the MIR borrow checker have been improved to the point that they are mostly the same or better than those emitted by the lexical region resolver.

While there do remain some degradations in errors (tracked under the [NLL-diagnostics tag](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-diagnostics), those are sufficiently small and rare enough that increased flexibility of MIR borrow check-only is now a worthwhile tradeoff.

## What is stabilized

As said previously, this does not fundamentally change the landscape of accepted programs. However, there are a [few](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3ANLL-fixed-by-NLL) cases where programs can compile under `feature(nll)`, but not otherwise.

There are two notable patterns that are "fixed" by this stabilization. First, the `scoped_threads` feature, which is a continutation of a pre-1.0 API, can sometimes emit a [weird lifetime error](https://github.com/rust-lang/rust/issues/95527) without NLL. Second, actually seen in the standard library. In the `Extend` impl for `HashMap`, there is an implied bound of `K: 'a` that is available with NLL on but not without - this is utilized in the impl.

As mentioned before, there are a large number of diagnostic differences. Most of them are better, but some are worse. None are serious or happen often enough to need to block this PR. The biggest change is the loss of error code for a number of lifetime errors in favor of more general "lifetime may not live long enough" error. While this may *seem* bad, the former error codes were just attempts to somewhat-arbitrarily bin together lifetime errors of the same type; however, on paper, they end up being roughly the same with roughly the same kinds of solutions.

## What isn't stabilized

This PR does not completely remove the lexical region resolver. In the future, it may be possible to remove that (while still keeping HIR typeck) or to remove it together with HIR typeck.

## Tests

Many test outputs get updated by this PR. However, there are number of tests specifically geared towards NLL under `src/test/ui/nll`

## History

* On 2017-07-14, [tracking issue opened](https://github.com/rust-lang/rust/issues/43234)
* On 2017-07-20, [initial empty MIR pass added](https://github.com/rust-lang/rust/pull/43271)
* On 2017-08-29, [RFC opened](https://github.com/rust-lang/rfcs/pull/2094)
* On 2017-11-16, [Integrate MIR type-checker with NLL](https://github.com/rust-lang/rust/pull/45825)
* On 2017-12-20, [NLL feature complete](https://github.com/rust-lang/rust/pull/46862)
* On 2018-07-07, [Don't run AST borrowck on mir mode](https://github.com/rust-lang/rust/pull/52083)
* On 2018-07-27, [Add migrate mode](https://github.com/rust-lang/rust/pull/52681)
* On 2019-04-22, [Enable migrate mode on 2015 edition](https://github.com/rust-lang/rust/pull/59114)
* On 2019-08-26, [Don't downgrade errors on 2015 edition](https://github.com/rust-lang/rust/pull/64221)
* On 2019-08-27, [Remove AST borrowck](https://github.com/rust-lang/rust/pull/64790)
2022-06-07 05:04:14 +00:00
Maybe Waffle
50c98a8c46 Add vec::Drain{,Filter}::keep_rest
These methods allow to cancel draining of unyielded elements.
2022-06-05 14:28:25 +04:00
Dylan DPC
07f586fe74
Rollup merge of #96642 - thomcc:thinbox-zst-ugh, r=yaahc
Avoid zero-sized allocs in ThinBox if T and H are both ZSTs.

This was surprisingly tricky, and took longer to get right than expected. `ThinBox` is a surprisingly subtle piece of code. That said, in the end, a lot of this was due to overthinking[^overthink] -- ultimately the fix ended up fairly clean and simple.

[^overthink]: Honestly, for a while I was convinced this couldn't be done without allocations or runtime branches in these cases, but that's obviously untrue.

Anyway, as a result of spending all that time debugging, I've extended the tests quite a bit, and also added more debug assertions. Many of these helped for subtle bugs I made in the middle (for example, the alloc/drop tracking is because I ended up double-dropping the value in the case where both were ZSTs), they're arguably a bit of overkill at this point, although I imagine they could help in the future too.

Anyway, these tests cover a wide range of size/align cases, nd fully pass under miri[^1]. They also do some smoke-check asserting that the value has the correct alignment, although in practice it's totally within the compiler's rights to delete these assertions since we'd have already done UB if they get hit. They have more boilerplate than they really need, but it's not *too* bad on a per-test basis.

A notable absence from testing is atypical header types, but at the moment it's impossible to manually implement `Pointee`. It would be really nice to have testing here, since it's not 100% obvious to me that the aligned read/write we use for `H` are correct in the face of arbitrary combinations of `size_of::<H>()`, `align_of::<H>()`, and `align_of::<T>()`. (That said, I spent a while thinking through it and am *pretty* sure it's fine -- I'd just feel... better if we could test some cases for non-ZST headers which have unequal and align).

[^1]: Or at least, they pass under miri if I copy the code and tests into a new crate and run miri on it (after making it less stdlibified).

Fixes #96485.

I'd request review ``@yaahc,`` but I believe you're taking some time away from reviews, so I'll request from the previous PR's reviewer (I think that the context helps, even if the actual change didn't end up being bad here).

r? ``@joshtriplett``
2022-06-04 11:06:39 +02:00
Jack Huey
410dcc9674 Fully stabilize NLL 2022-06-03 17:16:41 -04:00
Matthias Krüger
5b64aab2b6
Rollup merge of #97655 - steffahn:better-pin-box-construction-docs, r=thomcc
Improve documentation for constructors of pinned `Box`es

Adds a cross-references between `Box::pin` and `Box::into_pin` (and other related methods, i.e. the equivalent `From` implementation, and the unstable `pin_in` method), in particular now that `into_pin` [was stabilized](https://github.com/rust-lang/rust/pull/97397). The main goal is to further improve visibility of the fact that `Box<T> -> Pin<Box<T>>` conversion exits in the first place, and that `Box::pin(x)` is – essentially – just a convenience function for `Box::into_pin(Box::new(x))`

The motivating context why I think this is important is even experienced Rust users overlooking the existence this kind of conversion, [e.g. in this thread on IRLO](https://internals.rust-lang.org/t/pre-rfc-function-variants/16732/7?u=steffahn); and also the fact that that discussion brought up that there would be a bunch of Box-construction methods "missing" such as e.g. methods with fallible allocation a la "`Box::try_pin`", and similar; while those are in fact *not* necessary, because you can use `Box::into_pin(Box::try_new(x)?)` instead.

I have *not* included explicit mention of methods (e.g. `try_new`) in the docs of stable methods (e.g. `into_pin`). (Referring to unstable API in stable API docs would be bad style IMO.) Stable examples I have in mind with the statement "constructing a (pinned) Box in a different way than with `Box::new`" are things like cloning a `Box`, or `Box::from_raw`. If/when `try_new` would get stabilized, it would become a very good concrete example use-case of `Box::into_pin` IMO.
2022-06-02 23:39:07 +02:00
Frank Steffahn
6e2ac5df31 Improve documentation for constructors of pinned Boxes 2022-06-02 15:32:48 +02:00
bors
20976bae5c Auto merge of #97293 - est31:remove_box, r=oli-obk
Add #[rustc_box] and use it inside alloc

This commit adds an alternative content boxing syntax, and uses it inside alloc.

```Rust
#![feature(box_syntax)]

fn foo() {
    let foo = box bar;
}
```

is equivalent to

```Rust
#![feature(rustc_attrs)]

fn foo() {
    let foo = #[rustc_box] Box::new(bar);
}
```

The usage inside the very performance relevant code in
liballoc is the only remaining relevant usage of box syntax
in the compiler (outside of tests, which are comparatively easy to port).

box syntax was originally designed to be used by all Rust
developers. This introduces a replacement syntax more tailored
to only being used inside the Rust compiler, and with it,
lays the groundwork for eventually removing box syntax.

[Earlier work](https://github.com/rust-lang/rust/pull/87781#issuecomment-894714878) by `@nbdd0121` to lower `Box::new` to `box` during THIR -> MIR building ran into borrow checker problems, requiring the lowering to be adjusted in a way that led to [performance regressions](https://github.com/rust-lang/rust/pull/87781#issuecomment-894872367). The proposed change in this PR lowers `#[rustc_box] Box::new` -> `box` in the AST -> HIR lowering step, which is way earlier in the compiler, and thus should cause less issues both performance wise as well as regarding type inference/borrow checking/etc. Hopefully, future work can move the lowering further back in the compiler, as long as there are no performance regressions.
2022-06-02 13:20:19 +00:00
Dylan DPC
eb642d48ee
Rollup merge of #97603 - ximon18:arc-make-mut-spelling-correction, r=GuillaumeGomez
Arc make_mut doc comment spelling correction.
2022-06-02 11:13:25 +02:00
Yuki Okushi
572c39000b
Stabilize box_into_pin 2022-06-02 07:24:14 +09:00
Yuki Okushi
2c3a8cf0a4
Rollup merge of #97611 - azdavis:master, r=Dylan-DPC
Tweak insert docs

For `{Hash, BTree}Map::insert`, I always have to take a few extra seconds to think about the slight weirdness about the fact that if we "did not" insert (which "sounds" false), we return true, and if we "did" insert, (which "sounds" true), we return false.

This tweaks the doc comments for the `insert` methods of those types (as well as what looks like a rustc internal data structure that I found just by searching the codebase for "If the set did") to first use the "Returns whether _something_" pattern used in e.g. `remove`, where we say that `remove` "returns whether the value was present".
2022-06-01 23:36:52 +09:00
Dylan DPC
f81269f508
Update sync.rs 2022-06-01 14:12:36 +02:00
Dylan DPC
31ece0c850
Update sync.rs 2022-06-01 13:47:39 +02:00
Ariel Davis
b02146a370 Tweak insert docs 2022-05-31 22:08:14 -07:00
bors
395a09c3da Auto merge of #97553 - nbdd0121:lib, r=Mark-Simulacrum
Add `#[inline]` to `Vec`'s `Deref/DerefMut`

This should help #97552 (although I haven't verified).
2022-06-01 04:52:11 +00:00
est31
535e28b6c6 Use #[rustc_box] in alloc instead of box syntax 2022-06-01 02:28:34 +02:00
Ximon Eighteen
0b54b91496
Spelling correction. 2022-06-01 00:23:23 +02:00
Matthias Krüger
0d1e5465f3
Rollup merge of #97578 - ojeda:checkpatch, r=JohnTitor
alloc: remove repeated word in comment

Linux's `checkpatch.pl` reports:

```txt
#42544: FILE: rust/alloc/vec/mod.rs:2692:
WARNING: Possible repeated word: 'to'
+            // - Elements are :Copy so it's OK to to copy them, without doing
```

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-05-31 23:11:35 +02:00
Matthias Krüger
4f4a819fa9
Rollup merge of #97316 - CAD97:bound-misbehavior, r=dtolnay
Put a bound on collection misbehavior

As currently written, when a logic error occurs in a collection's trait parameters, this allows *completely arbitrary* misbehavior, so long as it does not cause undefined behavior in std. However, because the extent of misbehavior is not specified, it is allowed for *any* code in std to start misbehaving in arbitrary ways which are not formally UB; consider the theoretical example of a global which gets set on an observed logic error. Because the misbehavior is only bound by not resulting in UB from safe APIs and the crate-level encapsulation boundary of all of std, this makes writing user unsafe code that utilizes std theoretically impossible, as it now relies on undocumented QOI (quality of implementation) that unrelated parts of std cannot be caused to misbehave by a misuse of std::collections APIs.

In practice, this is a nonconcern, because std has reasonable QOI and an implementation that takes advantage of this freedom is essentially a malicious implementation and only compliant by the most langauage-lawyer reading of the documentation.

To close this hole, we just add a small clause to the existing logic error paragraph that ensures that any misbehavior is limited to the collection which observed the logic error, making it more plausible to prove the soundness of user unsafe code.

This is not meant to be formal; a formal refinement would likely need to mention that values derived from the collection can also misbehave after a logic error is observed, as well as define what it means to "observe" a logic error in the first place. This fix errs on the side of informality in order to close the hole without complicating a normal reading which can assume a reasonable nonmalicious QOI.

See also [discussion on IRLO][1].

[1]: https://internals.rust-lang.org/t/using-std-collections-and-unsafe-anything-can-happen/16640

r? rust-lang/libs-api ```@rustbot``` label +T-libs-api -T-libs

This technically adds a new guarantee to the documentation, though I argue as written it's one already implicitly provided.
2022-05-31 23:11:34 +02:00
bors
0a43923a86 Auto merge of #97419 - WaffleLapkin:const_from_ptr_range, r=oli-obk
Make `from{,_mut}_ptr_range` const

This PR makes the following APIs `const`:
```rust
// core::slice

pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T];
pub const unsafe fn from_mut_ptr_range<'a, T>(range: Range<*mut T>) -> &'a mut [T];
```

Tracking issue: #89792.
Feature for `from_ptr_range` as a `const fn`: `slice_from_ptr_range_const`.
Feature for `from_mut_ptr_range` as a `const fn`: `slice_from_mut_ptr_range_const`.

r? `@oli-obk`
2022-05-31 14:55:33 +00:00
bors
16a0d03698 Auto merge of #97521 - SkiFire13:clarify-vec-as-ptr, r=Dylan-DPC
Clarify the guarantees of Vec::as_ptr and Vec::as_mut_ptr when there's no allocation

Currently the documentation says they return a pointer to the vector's buffer, which has the implied precondition that the vector allocated some memory. However `Vec`'s documentation also specifies that it won't always allocate, so it's unclear whether the pointer returned is valid in that case. Of course you won't be able to read/write actual bytes to/from it since the capacity is 0, but there's an exception: zero sized read/writes. They are still valid as long as the pointer is not null and the memory it points to wasn't deallocated, but `Vec::as_ptr` and `Vec::as_mut_ptr` don't specify that's not the case. This PR thus specifies they are actually valid for zero sized reads since `Vec` is implemented to hold a dangling pointer in those cases, which is neither null nor was deallocated.
2022-05-31 12:14:51 +00:00
Miguel Ojeda
5dae6c1b96 alloc: remove repeated word in comment
Linux's `checkpatch.pl` reports:

```txt
#42544: FILE: rust/alloc/vec/mod.rs:2692:
WARNING: Possible repeated word: 'to'
+            // - Elements are :Copy so it's OK to to copy them, without doing
```

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-05-31 12:33:31 +02:00
Dylan DPC
bf248c82e8
Rollup merge of #97455 - JohnTitor:stabilize-toowned-clone-into, r=dtolnay
Stabilize `toowned_clone_into`

Closes #41263
FCP has been done: https://github.com/rust-lang/rust/issues/41263#issuecomment-1100760750
2022-05-31 07:57:35 +02:00
Dylan DPC
9c72f16b9f
Rollup merge of #97229 - Nilstrieb:doc-box-noalias, r=dtolnay
Document the current aliasing rules for `Box<T>`.

Currently, `Box<T>` gets `noalias`, meaning it has the same rules as `&mut T`. This is sparsely documented, even though it can have quite a big impact on unsafe code using box. Therefore, these rules are documented here, with a big warning that they are not normative and subject to change, since we have not yet committed to an aliasing model and the state of `Box<T>` is especially uncertain.

If you have any suggestions and improvements, make sure to leave them here. This is mostly intended to inform people about what is currently going on (to prevent misunderstandings such as [Jon Gjengset's Box aliasing](https://www.youtube.com/watch?v=EY7Wi9fV5bk)).

This is supposed to _only document current UB_ and not add any new guarantees or rules.
2022-05-31 07:57:33 +02:00
David Tolnay
e6b1003c95
BTreeSet->BTreeMap (fix copy/paste mistake in documentation)
Co-authored-by: lcnr <rust@lcnr.de>
2022-05-30 17:56:35 -07:00
David Tolnay
ffd7f5873e
Fix typo uniqeness -> uniqueness 2022-05-30 16:49:28 -07:00
Michael Goulet
3c0b9d50ae
Rollup merge of #89685 - DeveloperC286:iter_fields_to_private, r=oli-obk
refactor: VecDeques Iter fields to private

Made the fields of VecDeque's Iter private by creating a Iter::new(...) function to create a new instance of Iter and migrating usage to use Iter::new(...).
2022-05-30 15:57:27 -07:00
bors
4a8d2e3856 Auto merge of #97480 - conradludgate:faster-format-literals, r=joshtriplett
improve format impl for literals

The basic idea of this change can be seen here https://godbolt.org/z/MT37cWoe1.

Updates the format impl to have a fast path for string literals and the default path for regular format args.

This change will allow `format!("string literal")` to be used interchangably with `"string literal".to_owned()`.

This would be relevant in the case of `f!"string literal"` being legal (https://github.com/rust-lang/rfcs/pull/3267) in which case it would be the easiest way to create owned strings from literals, while also being just as efficient as any other impl
2022-05-30 17:39:58 +00:00
Gary Guo
0a7a0ff4d9 Add #[inline] to Vec's Deref/DerefMut 2022-05-30 15:11:53 +01:00
Dylan DPC
0ed320bdb9
Rollup merge of #97494 - est31:remove_box_alloc_tests, r=Dylan-DPC
Use Box::new() instead of box syntax in library tests

The tests inside `library/*` have no reason to use `box` syntax as they have 0 performance relevance. Therefore, we can safely remove them (instead of having to use alternatives like the one in #97293).
2022-05-30 14:33:48 +02:00
Maybe Waffle
ff9efd8a55 Add reexport of slice::from{,_mut}_ptr_range to alloc & std
At first I was confused why `std::slice::from_ptr_range` didn't work :D
2022-05-30 15:44:56 +04:00
Conrad Ludgate
5dd0fe301a remove useless cold 2022-05-29 20:40:56 +01:00
Conrad Ludgate
3f404bfa86 improve format impl for literals 2022-05-29 20:40:56 +01:00
bors
bef2b7cd1c Auto merge of #97214 - Mark-Simulacrum:stage0-bump, r=pietroalbini
Finish bumping stage0

It looks like the last time had left some remaining cfg's -- which made me think
that the stage0 bump was actually successful. This brings us to a released 1.62
beta though.

This now brings us to cfg-clean, with the exception of check-cfg-features in bootstrap;
I'd prefer to leave that for a separate PR at this time since it's likely to be more tricky.

cc https://github.com/rust-lang/rust/pull/97147#issuecomment-1132845061

r? `@pietroalbini`
2022-05-29 16:28:21 +00:00
Giacomo Stevanato
8ef2dd70e6 Clarify the guarantees of Vec::as_ptr and Vec::as_mut_ptr when there's no allocation 2022-05-29 17:43:35 +02:00
est31
7230a15c32 Use Box::new() instead of box syntax in alloc tests 2022-05-29 00:41:14 +02:00
Thom Chiovoloni
25164b4e51
Use pointer::is_aligned in ThinBox debug assert 2022-05-27 22:19:43 -07:00
Thom Chiovoloni
fc109bb6c6
Avoid zero-sized allocs in ThinBox if T and H are both ZSTs. 2022-05-27 22:12:20 -07:00
Matthias Krüger
4254f922db
Rollup merge of #95214 - tbu-:pr_vec_append_doc, r=Mark-Simulacrum
Remove impossible panic note from `Vec::append`

Neither the number of elements in a vector can overflow a `usize`, nor
can the amount of elements in two vectors.
2022-05-28 01:11:46 +02:00
Yuki Okushi
846f134cd3
Stabilize toowned_clone_into 2022-05-28 01:07:45 +09:00
Mark Rousskov
b454991ac4 Finish bumping stage0
It looks like the last time had left some remaining cfg's -- which made me think
that the stage0 bump was actually successful. This brings us to a released 1.62
beta though.
2022-05-27 07:36:17 -04:00
Nilstrieb
e7c468dc59 Document the current aliasing rules for Box<T>.
Currently, `Box<T>` gets `noalias`, meaning it has
the same rules as `&mut T`. This is
sparsely documented, even though it can have quite
a big impact on unsafe code using box. Therefore,
these rules are documented here, with a big warning
that they are not normative and subject to change,
since we have not yet committed to an aliasing model
and the state of `Box<T>` is especially uncertain.
2022-05-26 21:28:07 +02:00
bors
1851f0802e Auto merge of #97046 - conradludgate:faster-ascii-case-conv-path, r=thomcc
improve case conversion happy path

Someone shared the source code for [Go's string case conversion](19156a5474/src/strings/strings.go (L558-L616)).

It features a hot path for ascii-only strings (although I assume for reasons specific to go, they've opted for a read safe hot loop).

I've borrowed these ideas and also kept our existing code to provide a fast path + seamless utf-8 correct path fallback.

(Naive) Benchmarks can be found here https://github.com/conradludgate/case-conv

For the cases where non-ascii is found near the start, the performance of this algorithm does fall back to original speeds and has not had any measurable speed loss
2022-05-26 15:29:01 +00:00
Conrad Ludgate
d0f9930709 improve case conversion happy path 2022-05-26 13:18:57 +01:00
Christopher Durham
67aca498c6 Put a bound on collection misbehavior
As currently written, when a logic error occurs in a collection's trait
parameters, this allows *completely arbitrary* misbehavior, so long as
it does not cause undefined behavior in std. However, because the extent
of misbehavior is not specified, it is allowed for *any* code in std to
start misbehaving in arbitrary ways which are not formally UB; consider
the theoretical example of a global which gets set on an observed logic
error. Because the misbehavior is only bound by not resulting in UB from
safe APIs and the crate-level encapsulation boundary of all of std, this
makes writing user unsafe code that utilizes std theoretically
impossible, as it now relies on undocumented QOI that unrelated parts of
std cannot be caused to misbehave by a misuse of std::collections APIs.

In practice, this is a nonconcern, because std has reasonable QOI and an
implementation that takes advantage of this freedom is essentially a
malicious implementation and only compliant by the most langauage-lawyer
reading of the documentation.

To close this hole, we just add a small clause to the existing logic
error paragraph that ensures that any misbehavior is limited to the
collection which observed the logic error, making it more plausible to
prove the soundness of user unsafe code.

This is not meant to be formal; a formal refinement would likely need to
mention that values derived from the collection can also misbehave after a
logic error is observed, as well as define what it means to "observe" a
logic error in the first place. This fix errs on the side of informality
in order to close the hole without complicating a normal reading which
can assume a reasonable nonmalicious QOI.

See also [discussion on IRLO][1].

[1]: https://internals.rust-lang.org/t/using-std-collections-and-unsafe-anything-can-happen/16640
2022-05-23 09:20:57 -05:00
Dylan DPC
e5cf3cb97d
Rollup merge of #97087 - Nilstrieb:clarify-slice-iteration-order, r=dtolnay
Clarify slice and Vec iteration order

While already being inferable from the doc examples, it wasn't fully specified. This is the only logical way to do a slice iterator, so I think this should be uncontroversial. It also improves the `Vec::into_iter` example to better show the order and that the iterator returns owned values.
2022-05-23 07:43:49 +02:00
bors
4a86c7907b Auto merge of #96605 - Urgau:string-retain-codegen, r=thomcc
Improve codegen of String::retain method

This pull-request improve the codegen of the `String::retain` method.

Using `unwrap_unchecked` helps the optimizer to not generate a panicking path that will never be taken for valid UTF-8 like string.

Using `encode_utf8` saves us from an expensive call to `memcpy`, as the optimizer is unable to realize that `ch_len <= 4` and so can generate much better assembly code.

https://rust.godbolt.org/z/z73ohenfc
2022-05-21 01:56:51 +00:00
ajtribick
1a41a665cf
Reverse condition in Vec::retain_mut doctest 2022-05-19 20:54:16 +02:00
bors
50872bdb99 Auto merge of #97033 - nbdd0121:unwind3, r=Amanieu
Remove libstd's calls to `C-unwind` foreign functions

Remove all libstd and its dependencies' usage of `extern "C-unwind"`.

This is a prerequiste of a WIP PR which will forbid libraries calling `extern "C-unwind"` functions to be compiled in `-Cpanic=unwind` and linked against `panic_abort` (this restriction is necessary to address soundness bug #96926).
Cargo will ensure all crates are compiled with the same `-Cpanic` but the std is only compiled `-Cpanic=unwind` but needs the ability to be linked into `-Cpanic=abort`.

Currently there are two places where `C-unwind` is used in libstd:
* `__rust_start_panic` is used for interfacing to the panic runtime. This could be `extern "Rust"`
* `_{rdl,rg}_oom`: a shim `__rust_alloc_error_handler` will be generated by codegen to call into one of these; they can also be `extern "Rust"` (in fact, the generated shim is used as `extern "Rust"`, so I am not even sure why these are not, probably because they used to `extern "C"` and was changed to `extern "C-unwind"` when we allow alloc error hooks to unwind, but they really should just be using Rust ABI).

For dependencies, there is only one `extern "C-unwind"` function call, in `unwind` crate. This can be expressed as a re-export.

More dicussions can be seen in the Zulip thread: https://rust-lang.zulipchat.com/#narrow/stream/210922-project-ffi-unwind/topic/soundness.20in.20mixed.20panic.20mode

`@rustbot` label: T-libs F-c_unwind
2022-05-19 04:04:40 +00:00
Nilstrieb
4a2214885d Clarify slice and Vec iteration order
While already being inferable from the doc examples, it wasn't
fully specified. This is the only logical way to do a slice
iterator.
2022-05-16 19:29:45 +02:00
Yuki Okushi
6c6958b531
Rollup merge of #95365 - mkroening:hermit-alloc-error-handler, r=joshtriplett
Use default alloc_error_handler for hermit

Hermit now properly separates kernel from userspace.
Applications for hermit can now use Rust's default `alloc_error_handler` instead of calling the kernel's `__rg_oom`.

CC: ``@stlankes``
2022-05-14 13:42:49 +09:00
Gary Guo
68f063bf3f Use Rust ABI for __rust_start_panic and _{rdl,rg}_oom 2022-05-14 02:53:59 +01:00
Matthias Krüger
a56211a44e
Rollup merge of #97003 - nnethercote:rm-const_fn-attrs, r=fee1-dead
Remove some unnecessary `rustc_allow_const_fn_unstable` attributes.

r? `@fee1-dead`
2022-05-13 16:03:25 +02:00
Nicholas Nethercote
fd01fbc058 Remove some unnecessary rustc_allow_const_fn_unstable attributes. 2022-05-13 16:01:18 +10:00
bors
1d2ea98cff Auto merge of #95837 - scottmcm:ptr-offset-from-unsigned, r=oli-obk
Add `sub_ptr` on pointers (the `usize` version of `offset_from`)

We have `add`/`sub` which are the `usize` versions of `offset`, this adds the `usize` equivalent of `offset_from`.  Like how `.add(d)` replaced a whole bunch of `.offset(d as isize)`, you can see from the changes here that it's fairly common that code actually knows the order between the pointers and *wants* a `usize`, not an `isize`.

As a bonus, this can do `sub nuw`+`udiv exact`, rather than `sub`+`sdiv exact`, which can be optimized slightly better because it doesn't have to worry about negatives.  That's why the slice iterators weren't using `offset_from`, though I haven't updated that code in this PR because slices are so perf-critical that I'll do it as its own change.

This is an intrinsic, like `offset_from`, so that it can eventually be allowed in CTFE.  It also allows checking the extra safety condition -- see the test confirming that CTFE catches it if you pass the pointers in the wrong order.
2022-05-12 02:49:00 +00:00
Scott McMurray
003b954a43 Apply CR suggestions; add real tracking issue 2022-05-11 17:16:25 -07:00
Scott McMurray
e76b3f3b5b Rename unsigned_offset_from to sub_ptr 2022-05-11 17:16:25 -07:00
Scott McMurray
89a18cb600 Add unsigned_offset_from on pointers
Like we have `add`/`sub` which are the `usize` version of `offset`, this adds the `usize` equivalent of `offset_from`.  Like how `.add(d)` replaced a whole bunch of `.offset(d as isize)`, you can see from the changes here that it's fairly common that code actually knows the order between the pointers and *wants* a `usize`, not an `isize`.

As a bonus, this can do `sub nuw`+`udiv exact`, rather than `sub`+`sdiv exact`, which can be optimized slightly better because it doesn't have to worry about negatives.  That's why the slice iterators weren't using `offset_from`, though I haven't updated that code in this PR because slices are so perf-critical that I'll do it as its own change.

This is an intrinsic, like `offset_from`, so that it can eventually be allowed in CTFE.  It also allows checking the extra safety condition -- see the test confirming that CTFE catches it if you pass the pointers in the wrong order.
2022-05-11 17:16:25 -07:00
bors
0cd939e36c Auto merge of #96150 - est31:unused_macro_rules, r=petrochenkov
Implement a lint to warn about unused macro rules

This implements a new lint to warn about unused macro rules (arms/matchers), similar to the `unused_macros` lint added by #41907 that warns about entire macros.

```rust
macro_rules! unused_empty {
    (hello) => { println!("Hello, world!") };
    () => { println!("empty") }; //~ ERROR: 1st rule of macro `unused_empty` is never used
}

fn main() {
    unused_empty!(hello);
}
```

Builds upon #96149 and #96156.

Fixes #73576
2022-05-12 00:08:08 +00:00
Matthias Krüger
6c8001b85c
Rollup merge of #96008 - fmease:warn-on-useless-doc-hidden-on-assoc-impl-items, r=lcnr
Warn on unused `#[doc(hidden)]` attributes on trait impl items

[Zulip conversation](https://rust-lang.zulipchat.com/#narrow/stream/266220-rustdoc/topic/.E2.9C.94.20Validy.20checks.20for.20.60.23.5Bdoc.28hidden.29.5D.60).

Whether an associated item in a trait impl is shown or hidden in the documentation entirely depends on the corresponding item in the trait declaration. Rustdoc completely ignores `#[doc(hidden)]` attributes on impl items. No error or warning is emitted:

```rust
pub trait Tr { fn f(); }
pub struct Ty;
impl Tr for Ty { #[doc(hidden)] fn f() {} }
//               ^^^^^^^^^^^^^^ ignored by rustdoc and currently
//                              no error or warning issued
```

This may lead users to the wrong belief that the attribute has an effect. In fact, several such cases are found in the standard library (I've removed all of them in this PR).
There does not seem to exist any incentive to allow this in the future either: Impl'ing a trait for a type means the type *fully* conforms to its API. Users can add `#[doc(hidden)]` to the whole impl if they want to hide the implementation or add the attribute to the corresponding associated item in the trait declaration to hide the specific item. Hiding an implementation of an associated item does not make much sense: The associated item can still be found on the trait page.

This PR emits the warn-by-default lint `unused_attribute` for this case with a future-incompat warning.

`@rustbot` label T-compiler T-rustdoc A-lint
2022-05-09 18:45:36 +02:00
bors
8a2fe75d0e Auto merge of #95960 - jhpratt:remove-rustc_deprecated, r=compiler-errors
Remove `#[rustc_deprecated]`

This removes `#[rustc_deprecated]` and introduces diagnostics to help users to the right direction (that being `#[deprecated]`). All uses of `#[rustc_deprecated]` have been converted. CI is expected to fail initially; this requires #95958, which includes converting `stdarch`.

I plan on following up in a short while (maybe a bootstrap cycle?) removing the diagnostics, as they're only intended to be short-term.
2022-05-09 04:47:30 +00:00
León Orell Valerian Liehr
9d157ada35 Warn on unused doc(hidden) on trait impl items 2022-05-08 22:53:14 +02:00
bors
e209e85e39 Auto merge of #95183 - ibraheemdev:arc-count-acquire, r=Amanieu
Weaken needlessly restrictive orderings on `Arc::*_count`

There is no apparent reason for these to be `SeqCst`. For reference, [the Boost C++ implementation relies on acquire semantics](f2cc84a23c/include/boost/smart_ptr/detail/sp_counted_base_std_atomic.hpp (L137-L140)).
2022-05-06 14:53:24 +00:00
bors
8c4fc9d9a4 Auto merge of #94598 - scottmcm:prefix-free-hasher-methods, r=Amanieu
Add a dedicated length-prefixing method to `Hasher`

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

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

Fixes #94026

r? rust-lang/libs

---

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

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

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

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

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

---

Compatibility:

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

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.
2022-05-06 00:03:38 -07:00
est31
5646e9a172 Allow unused rules in some places in the compiler, library and tools 2022-05-05 19:13:00 +02:00
Matthias Krüger
3f07303efe
Rollup merge of #95843 - GuillaumeGomez:improve-new-cyclic-doc, r=m-ou-se
Improve Rc::new_cyclic and Arc::new_cyclic documentation

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

cc `@CAD97` (since I used your explanations)
2022-05-05 15:43:02 +02:00
bors
12d3f107c1 Auto merge of #96626 - thomcc:rand-bump, r=m-ou-se
Avoid using `rand::thread_rng` in the stdlib benchmarks.

This is kind of an anti-pattern because it introduces extra nondeterminism for no real reason. In thread_rng's case this comes both from the random seed and also from the reseeding operations it does, which occasionally does syscalls (which adds additional nondeterminism). The impact of this would be pretty small in most cases, but it's a good practice to avoid (particularly because avoiding it was not hard).

Anyway, several of our benchmarks already did the right thing here anyway, so the change was pretty easy and mostly just applying it more universally. That said, the stdlib benchmarks aren't particularly stable (nor is our benchmark framework particularly great), so arguably this doesn't matter that much in practice.

~~Anyway, this also bumps the `rand` dev-dependency to 0.8, since it had fallen somewhat out of date.~~ Nevermind, too much of a headache.
2022-05-05 05:08:44 +00:00
Guillaume Gomez
67d1e7b8ff Improve Rc::new_cyclic and Arc::new_cyclic documentation 2022-05-04 15:20:02 +02:00
bors
6b6c1ffacc Auto merge of #96596 - scottmcm:limited-calloc, r=Mark-Simulacrum
Tweak the vec-calloc runtime check to only apply to shortish-arrays

r? `@Mark-Simulacrum`

`@nbdd0121` pointed out in https://github.com/rust-lang/rust/pull/95362#issuecomment-1114085395 that LLVM currently doesn't constant-fold the `IsZero` check for long arrays, so that seems like a reasonable justification for limiting it.

It appears that it's based on length, not byte size, (https://godbolt.org/z/4s48Y81dP), so that's what I used in the PR.  Maybe it's a ["the number of inlining shall be three"](https://youtu.be/s4wnuiCwTGU?t=320) sort of situation.

Certainly there's more that could be done here -- that generated code that checks long arrays byte-by-byte is highly suboptimal, for example -- but this is an easy, low-risk tweak.
2022-05-02 09:05:22 +00:00
Stein Somers
a80e685e11 Test leaking of BinaryHeap Drain iterators 2022-05-02 10:07:51 +02:00
Stein Somers
204f854586 Slightly tighten leak-on-panic test cases 2022-05-02 10:07:51 +02:00
Stein Somers
321247deb3 Share testing utilities with non-btree test cases 2022-05-02 10:07:50 +02:00
Thom Chiovoloni
0812759840
Avoid use of rand::thread_rng in stdlib benchmarks 2022-05-02 00:08:21 -07:00
Scott McMurray
2830dbd64f Tweak the calloc optimization to only apply to shortish-arrays 2022-05-01 22:28:11 -07:00
Yuki Okushi
ab1ae48cce
Rollup merge of #96568 - EliasHolzmann:fmt_doc_fixes, r=joshtriplett
std::fmt: Various fixes and improvements to documentation

This PR contains the following changes:

- **Added argument index comments to examples for specifying precision**

  The examples for specifying the precision have comments explaining which
  argument the specifier is referring to. However, for implicit positional
  arguments, the examples simply refer to "next arg". To simplify following the
  comments, "next arg" was supplemented with the actual resulting argument index.

- **Fixed documentation for specifying precision via `.*`**

  The documentation stated that in case of the syntax `{<arg>:<spec>.*}`, "the
  `<arg>` part refers to the value to print, and the precision must come in the
  input preceding `<arg>`". This is not correct: the <arg> part does indeed refer
  to the value to print, but the precision does not come in the input preciding
  arg, but in the next implicit input (as if specified with {}).

  Fixes #96413.

- **Fix the grammar documentation**

  According to the grammar documented, the format specifier `{: }` should not be
  legal because of the whitespace it contains. However, in reality, this is
  perfectly fine because the actual implementation allows spaces before the
  closing brace. Fixes #71088.

  Also, the exact meaning of most of the terminal symbols was not specified, for
  example the meaning of `identifier`.

- **Removed reference to Formatter::buf and other private fields**

  Formatter::buf is not a public field and therefore isn't very helpful in user-
  facing documentation. Also, the other public fields of Formatter were removed
  during stabilization of std::fmt (4af3494bb0) and can only be accessed via
  getters.

- **Improved list of formatting macros**

  Two improvements:
  1. write! can not only receive a `io::Write`, but also a `fmt::Write` as first argument.
  2. The description texts now contain links to the actual macros for easier
     navigation.
2022-05-02 10:41:58 +09:00
Yuki Okushi
1785f1549c
Rollup merge of #96222 - jmaargh:john-mark/clarify-from-raw-parts-docs, r=JohnTitor
Clarify docs for `from_raw_parts` on `Vec` and `String`

Closes #95427

Original safety explanation for `from_raw_parts` was unclear on safety for consuming a C string. This clarifies when doing so is safe.
2022-05-02 10:41:55 +09:00
Yuki Okushi
ddfc65dae0
Rollup merge of #94126 - ssomers:alloc_prep_1, r=Mark-Simulacrum
Classify BinaryHeap & LinkedList unit tests as such

All but one of these so-called integration test case are unit tests, just like btree's were (#75531). In addition, reunite the unit tests of linked_list that were split off during #23104 because they needed to remain unit tests (they were later moved to the separate file they are in during #63207). The two sets could remain separate files, but I opted to merge them back together, more or less in the order they used to be, apart from one duplicate name `test_split_off` and one duplicate tiny function `list_from`.
2022-05-02 10:41:54 +09:00
Ibraheem Ahmed
1ac54401d1 add {Arc, Rc}::downcast_unchecked 2022-05-01 15:35:45 -04:00
Loïc BRANSTETT
a98abe83eb Improve codegen of String::retain method.
Using unwrap_unchecked helps the optimizer to not generate panicking
path, that will never be taken for valid UTF-8 like string.

Using encode_utf8 saves us a call to a memcpy, as the optimizer is
unable to realize that ch_len <= 4 and so can generate much better
assembly code.

https://rust.godbolt.org/z/z73ohenfc
2022-05-01 19:25:14 +02:00
Elias Holzmann
f3b86c37eb std::fmt: Improved list of formatting macros
Two improvements:
1. write! can not only receive a `io::Write`, but also a `fmt::Write` as first argument.
2. The description texts now contain links to the actual macros for easier
   navigation.
2022-05-01 15:27:41 +02:00
Elias Holzmann
c70f3ab5e5 std::fmt: Removed reference to Formatter::buf and other private fields
Formatter::buf is not a public field and therefore isn't very helpful in user-
facing documentation. Also, the other public fields of Formatter were made
private during stabilization of std::fmt (4af3494bb0) and can now only be read
via accessor methods.
2022-05-01 15:27:41 +02:00
Elias Holzmann
79d9afda13 std::fmt: Fix the grammar documentation
According to the grammar documented, the format specifier `{: }` should not be
legal because of the whitespace it contains. However, in reality, this is
perfectly fine because the actual implementation allows spaces before the
closing brace. Fixes #71088.

Also, the exact meaning of most of the terminal symbols was not specified, for
example the meaning of `identifier`.
2022-05-01 15:27:41 +02:00
Elias Holzmann
afd80a21b0 std::fmt: Added argument index comments to examples for specifying precision
The examples for specifying the precision have comments explaining which
argument the specifier is referring to. However, for implicit positional
arguments, the examples simply talk about "next arg". To make it easier for
readers to follow the comments, "next arg" was supplemented with the actual
resulting argument index.
2022-05-01 15:27:40 +02:00
Elias Holzmann
1288883932 std::fmt: Fixed documentation for specifying precision via .*
The documentation stated that in case of the syntax `{<arg>:<spec>.*}`, "the
`<arg>` part refers to the value to print, and the precision must come in the
input preceding `<arg>`". This is not correct: the <arg> part does indeed refer
to the value to print, but the precision does not come in the input preciding
arg, but in the next implicit input (as if specified with {}).

Fixes #96413.
2022-05-01 15:26:15 +02:00
bors
f75d884046 Auto merge of #96078 - udoprog:refcounted-str-to-u8, r=dtolnay
Implement str to [u8] conversion for refcounted containers

This seems motivated to complete the APIs for shared containers since we already have similar allocation-free conversions for strings like `From<Box<[u8]>> for Box<str>`.

Insta-stable since it's a new trait impl?
2022-05-01 06:41:59 +00:00
David Tolnay
100006bec9
Bump shared_from_str to Rust 1.62.0 2022-04-30 23:40:35 -07:00
bors
bf611439e3 Auto merge of #95362 - scottmcm:calloc-arrays, r=Mark-Simulacrum
Support arrays of zeros in Vec's __rust_alloc_zeroed optimization

I happened to notice in https://users.rust-lang.org/t/any-advantage-of-box-u64-16-16-16-over-vec-u64/73500/3?u=scottmcm that the calloc optimization wasn't applying to vectors-of-arrays, so here's the easy fix for that.
2022-05-01 00:50:46 +00:00
bors
f1d8a7d662 Auto merge of #96489 - shepmaster:revert-vec-from-array-ref, r=yaahc
Revert "impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>"

This reverts commit 5dd702763a.
2022-04-29 14:39:14 +00:00
Dylan DPC
cd5dc49379
Rollup merge of #96492 - joshtriplett:revert-std-ffi-re-export, r=yaahc
Revert "Re-export core::ffi types from std::ffi"

This reverts commit 9aed829fe6.

Fixes https://github.com/rust-lang/rust/issues/96435 , a regression
in crates doing `use std::ffi::*;` and `use std::os::raw::*;`.

We can re-add this re-export once the `core::ffi` types
are stable, and thus the `std::os::raw` types can become re-exports as
well, which will avoid the conflict. (Type aliases to the same type
still conflict, but re-exports of the same type don't.)
2022-04-29 11:23:14 +02:00
Paolo Barbolini
c126f7fc8b Add VecDeque::extend from vec::IntoIter and slice::Iter specializations 2022-04-28 06:13:54 +02:00
Josh Triplett
42d96bb2f6 Remove use of reverted std::ffi::c_char 2022-04-27 14:01:04 -07:00
Jake Goulding
762bb1f506 Revert "impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>"
This reverts commit 5dd702763a.
2022-04-27 15:56:29 -04:00
Paolo Barbolini
84b8898d63 Add VecDeque::extend benchmark 2022-04-27 21:10:20 +02:00
Guillaume Gomez
eaf8beb3f3
Rollup merge of #94022 - jongiddy:cow-into-owned-docs, r=Dylan-DPC
Clarify that `Cow::into_owned` returns owned data

Two sections of the `Cow::into_owned` docs imply that `into_owned` returns a `Cow`. Clarify that it returns the underlying owned object, either cloned or extracted from the `Cow`.
2022-04-26 13:22:26 +02:00
Dylan DPC
51b86848ff
Rollup merge of #90312 - r00ster91:search, r=Dylan-DPC
Fix some confusing wording and improve slice-search-related docs

This adds more links between `contains` and `binary_search` because I do think they have some relevant connections. If your (big) slice happens to be sorted and you know it, surely you should be using `[3; 100].binary_search(&5).is_ok()` over `[3; 100].contains(&5)`?
This also fixes the confusing "searches this sorted X" wording which just sounds really weird because it doesn't know whether it's actually sorted. It should be but it may not be. The new wording should make it clearer that you will probably want to sort it and in the same sentence it also mentions the related function `contains`.
Similarly, this mentions `binary_search` on `contains`' docs.
This also fixes some other minor stuff and inconsistencies.
2022-04-26 01:21:20 +02:00
Matthias Krüger
b7e67a6ad9
Rollup merge of #96107 - Gumichocopengin8:test/vec-deque, r=Mark-Simulacrum
[test] Add test cases for untested functions for VecDeque

Added test cases of the following functions
- get
- get_mut
- swap
- reserve_exact
- try_reserve_exact
- try_reserve
- contains
- rotate_left
- rotate_right
- binary_search
- binary_search_by
- binary_search_by_key
2022-04-25 00:11:00 +02:00
Keita Nonaka
a40cd2aa8b test: add test cases for VecDeque 2022-04-24 11:43:07 -07:00
jmaargh
4dda047de3 Clarify docs for from_raw_parts
Original safety explanation for from_raw_parts was
unclear on safety for consuming a C string. This
clarifies when doing so is safe.
2022-04-19 21:12:55 +01:00
Dylan DPC
35188440b5
Rollup merge of #96089 - ojeda:no-vec-no_global_oom_handling, r=Mark-Simulacrum
`alloc`: make `vec!` unavailable under `no_global_oom_handling`

`alloc`: make `vec!` unavailable under `no_global_oom_handling`

The `vec!` macro has 3 rules, but two are not usable under
`no_global_oom_handling` builds of the standard library
(even with a zero size):

```rust
let _ = vec![42];    // Error: requires `exchange_malloc` lang_item.
let _ = vec![42; 0]; // Error: cannot find function `from_elem`.
```

Thus those two rules should not be available to begin with.

The remaining one, with an empty matcher, is just a shorthand for
`new()` and may not make as much sense to have alone, since the
idea behind `vec!` is to enable `Vec`s to be defined with the same
syntax as array expressions. Furthermore, the documentation can be
confusing since it shows the other rules.

Thus perhaps it is better and simpler to disable `vec!` entirely
under `no_global_oom_handling` environments, and let users call
`new()` instead:

```rust
let _: Vec<i32> = vec![];
let _: Vec<i32> = Vec::new();
```

Notwithstanding this, a `try_vec!` macro would be useful, such as
the one introduced in https://github.com/rust-lang/rust/pull/95051.

If the shorthand for `new()` is deemed worth keeping on its own,
then it may be interesting to have a separate `vec!` macro with
a single rule and different, simpler documentation.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-04-19 14:43:19 +02:00
bors
43a71dc732 Auto merge of #96002 - nnethercote:speed-up-Vec-clear-2, r=m-ou-se
Speed up Vec::clear().

Currently it just calls `truncate(0)`. `truncate()` is (a) not marked as
`#[inline]`, and (b) more general than needed for `clear()`.

This commit changes `clear()` to do the work itself. This modest change
was first proposed in rust-lang#74172, where the reviewer rejected it because
there was insufficient evidence that `Vec::clear()`'s performance
mattered enough to justify the change. Recent changes within rustc have
made `Vec::clear()` hot within `macro_parser.rs`, so the change is now
clearly worthwhile.

Although it doesn't show wins on CI perf runs, this seems to be because they
use PGO. But not all platforms currently use PGO. Also, local builds don't use
PGO, and `truncate` sometimes shows up in an over-represented fashion in local
profiles. So local profiling will be made easier by this change.

Note that this will also benefit `String::clear()`, because it just
calls `Vec::clear()`.

Finally, the commit removes the `vec-clear.rs` codegen test. It was
added in #52908. From before then until now, `Vec::clear()` just called
`Vec::truncate()` with a zero length. The body of Vec::truncate() has
changed a lot since then. Now that `Vec::clear()` is doing actual work
itself, and not just calling `Vec::truncate()`, it's not surprising that
its generated code includes a load and an icmp. I think it's reasonable
to remove this test.

r? `@m-ou-se`
2022-04-17 03:08:45 +00:00
Dylan DPC
04ccba8728
Rollup merge of #96070 - Gumichocopengin8:test/btree-map, r=thomcc
[test] Add test cases for untested functions for BTreeMap

- add `pop_first()`, `pop_last()`, `get_key_value()` and `try_insert()` test cases
2022-04-16 07:12:48 +02:00
Miguel Ojeda
8cec88ba76 alloc: make vec! unavailable under no_global_oom_handling
The `vec!` macro has 3 rules, but two are not usable under
`no_global_oom_handling` builds of the standard library
(even with a zero size):

```rust
let _ = vec![42];    // Error: requires `exchange_malloc` lang_item.
let _ = vec![42; 0]; // Error: cannot find function `from_elem`.
```

Thus those two rules should not be available to begin with.

The remaining one, with an empty matcher, is just a shorthand for
`new()` and may not make as much sense to have alone, since the
idea behind `vec!` is to enable `Vec`s to be defined with the same
syntax as array expressions. Furthermore, the documentation can be
confusing since it shows the other rules.

Thus perhaps it is better and simpler to disable `vec!` entirely
under `no_global_oom_handling` environments, and let users call
`new()` instead:

```rust
let _: Vec<i32> = vec![];
let _: Vec<i32> = Vec::new();
```

Notwithstanding this, a `try_vec!` macro would be useful, such as
the one introduced in https://github.com/rust-lang/rust/pull/95051.

If the shorthand for `new()` is deemed worth keeping on its own,
then it may be interesting to have a separate `vec!` macro with
a single rule and different, simpler documentation.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-04-16 06:31:41 +02:00
bors
bb1a03c4fc Auto merge of #95224 - mjbshaw:patch-1, r=yaahc
Optimize RcInnerPtr::inc_strong()/inc_weak() instruction count

Inspired by this internals thread: https://internals.rust-lang.org/t/rc-optimization-on-64-bit-targets/16362

[The generated assembly is a bit smaller](https://rust.godbolt.org/z/TeTnf6144) and is a more efficient usage of the CPU's instruction cache. `unlikely` doesn't impact any of the small artificial tests I've done, but I've included it in case it might help more complex scenarios when this is inlined.
2022-04-15 23:15:51 +00:00
Dylan DPC
224afadb3b
Rollup merge of #96034 - Gumichocopengin8:test/btree-set, r=Dylan-DPC
[test] Add test cases of untested functions for BTreeSet

- add [`is_superset()`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.is_superset) and [`remove()`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.remove) test cases for BTreeSet since these functions has no test cases.
2022-04-15 20:50:49 +02:00
John-John Tedro
594be707c4 Implement str to [u8] conversion for refcounted containers 2022-04-15 15:38:37 +02:00
Keita Nonaka
3f46ba6028 chore: formatting 2022-04-15 01:30:05 -07:00
Keita Nonaka
3f2f4a35ed test: add try_insert() test cases for BTreeSet 2022-04-15 01:12:00 -07:00
Keita Nonaka
e1626020d3 test: add get_key_value() test cases for BTreeSet 2022-04-15 00:04:03 -07:00
Keita Nonaka
4117e8c2d3 test: add pop_first() pop_last() test cases for BTreeSet 2022-04-14 23:40:05 -07:00
Vadim Petrochenkov
afa2e6f2ff Fix targets not supporting target_has_atomic = "ptr" 2022-04-14 21:53:11 +03:00
Vadim Petrochenkov
7f3cc2fbbf library: Use type aliases to make CStr(ing) in libcore/liballoc unstable 2022-04-14 21:53:11 +03:00
Vadim Petrochenkov
5bee741a08 library: Move CStr to libcore, and CString to liballoc 2022-04-14 21:53:11 +03:00
Jacob Pratt
4fbe73e0b7
Remove use of #[rustc_deprecated] 2022-04-14 01:33:13 -04:00
Keita Nonaka
50c339e8f5 test: add remove() test cases for BTreeSet 2022-04-13 22:19:08 -07:00
Keita Nonaka
21d3f8444a test: add is_superset test cases for BTreeSet 2022-04-13 22:09:03 -07:00
Nicholas Nethercote
9c59d04d55 Speed up Vec::clear().
Currently it just calls `truncate(0)`. `truncate()` is (a) not marked as
`#[inline]`, and (b) more general than needed for `clear()`.

This commit changes `clear()` to do the work itself. This modest change
was first proposed in rust-lang#74172, where the reviewer rejected it because
there was insufficient evidence that `Vec::clear()`'s performance
mattered enough to justify the change. Recent changes within rustc have
made `Vec::clear()` hot within `macro_parser.rs`, so the change is now
clearly worthwhile.

Although it doesn't show wins on CI perf runs, this seems to be because they
use PGO. But not all platforms currently use PGO. Also, local builds don't use
PGO, and `truncate` sometimes shows up in an over-represented fashion in local
profiles. So local profiling will be made easier by this change.

Note that this will also benefit `String::clear()`, because it just
calls `Vec::clear()`.

Finally, the commit removes the `vec-clear.rs` codegen test. It was
added in #52908. From before then until now, `Vec::clear()` just called
`Vec::truncate()` with a zero length. The body of Vec::truncate() has
changed a lot since then. Now that `Vec::clear()` is doing actual work
itself, and not just calling `Vec::truncate()`, it's not surprising that
its generated code includes a load and an icmp. I think it's reasonable
to remove this test.
2022-04-13 15:39:35 +10:00
Josh Stone
a2902ebe57 impl const Default for Box<[T]> and Box<str> 2022-04-11 12:14:18 -07:00
Matthias Krüger
5b8e2ea520
Rollup merge of #95917 - RalfJung:thin-box-test, r=dtolnay
thin_box test: import from std, not alloc

Importing from `alloc` makes [Miri fail](https://github.com/rust-lang/miri-test-libstd/runs/5964922742?check_suite_focus=true), probably due to the hack that we used to resolve https://github.com/rust-lang/miri-test-libstd/issues/4. There might be better ways around this, but for now this is the easiest thing to do -- no other alloc integration test is importing from `alloc::`.
2022-04-11 12:06:58 +02:00
Matthias Krüger
e25bc303f1
Rollup merge of #95743 - yaahc:binary-search-clarification, r=Mark-Simulacrum
Update binary_search example to instead redirect to partition_point

Inspired by discussion in the tracking issue for `Result::into_ok_or_err`: https://github.com/rust-lang/rust/issues/82223#issuecomment-1067098167

People are surprised by us not providing a `Result<T, T> -> T` conversion, and the main culprit for this confusion seems to be the `binary_search` API. We should instead redirect people to the equivalent API that implicitly does that `Result<T, T> -> T` conversion internally which should obviate the need for the `into_ok_or_err` function and give us time to work towards a more general solution that applies to all enums rather than just `Result` such as making or_patterns usable for situations like this via postfix `match`.

I choose to duplicate the example rather than simply moving it from `binary_search` to partition point because most of the confusion seems to arise when people are looking at `binary_search`. It makes sense to me to have the example presented immediately rather than requiring people to click through to even realize there is an example. If I had to put it in only one place I'd leave it in `binary_search` and remove it from `partition_point` but it seems pretty obviously relevant to `partition_point` so I figured the best option would be to duplicate it.
2022-04-11 12:06:52 +02:00
Ralf Jung
dbc0afa215 thin_box test: import from std, not alloc 2022-04-10 22:59:51 -04:00
Dylan DPC
2464ea2510
Rollup merge of #95817 - oconnor663:doc_comment2, r=yaahc
hide another #[allow] directive from a docs example

This is a repeat for Rc of e0e64a8930,
which cleaned up the same thing for Arc.
2022-04-09 18:26:29 +02:00
Mark Lodato
9cf35a6c06 Rework String UTF-8 Documentation
**This Commit**
Adds some clarity around indexing into Strings and the constraints
driving various decisions there.

**Why?**
The [`String` documentation][0] mentions how `String`s can't be indexed
but `Range` has an implementation for `SliceIndex<str>`. This can be
confusing. There are also several statements to explain the lack of
`String` indexing:

- the inability to index into a `String` is an implication of UTF-8
  encoding
- indexing into a `String` could not be constant-time with UTF-8
  encoding
- indexing into a `String` does not have an obvious return type

This last statement made sense but the first two seemed contradictory to
the documentation around [`SliceIndex<str>`][1] which mention:

- one can index into a `String` with a `Range` (also called substring
  slicing but it uses the same syntax and the method name is `index`)
- `Range` indexing into a `String` is constant-time

To resolve this seeming contradiction the documentation is reworked to
more clearly explain what factors drive the decision to disallow
indexing into a `String` with a single number.

[0]: https://doc.rust-lang.org/stable/std/string/struct.String.html#utf-8
[1]: https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E
2022-04-09 09:27:32 -04:00
Jack O'Connor
c1023e9e5f hide another #[allow] directive from a docs example
This is a repeat for Rc of e0e64a8930,
which cleaned up the same thing for Arc.
2022-04-08 10:29:50 -07:00
Jane Lusby
a87a0d089e Add ThinBox type for 1 stack pointer sized heap allocated trait objects
Relevant commit messages from squashed history in order:

Add initial version of ThinBox

update test to actually capture failure

swap to middle ptr impl based on matthieu-m's design

Fix stack overflow in debug impl

The previous version would take a `&ThinBox<T>` and deref it once, which
resulted in a no-op and the same type, which it would then print causing
an endless recursion. I've switched to calling `deref` by name to let
method resolution handle deref the correct number of times.

I've also updated the Drop impl for good measure since it seemed like it
could be falling prey to the same bug, and I'll be adding some tests to
verify that the drop is happening correctly.

add test to verify drop is behaving

add doc examples and remove unnecessary Pointee bounds

ThinBox: use NonNull

ThinBox: tests for size

Apply suggestions from code review

Co-authored-by: Alphyr <47725341+a1phyr@users.noreply.github.com>

use handle_alloc_error and fix drop signature

update niche and size tests

add cfg for allocating APIs

check null before calculating offset

add test for zst and trial usage

prevent optimizer induced ub in drop and cleanup metadata gathering

account for arbitrary size and alignment metadata

Thank you nika and thomcc!

Update library/alloc/src/boxed/thin.rs

Co-authored-by: Josh Triplett <josh@joshtriplett.org>

Update library/alloc/src/boxed/thin.rs

Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-04-08 09:00:16 -07:00
Dylan DPC
7b285d09e9
Rollup merge of #95791 - oconnor663:doc_comment, r=thomcc
hide an #[allow] directive from the Arc::new_cyclic doc example

A minor docs cleanup.
2022-04-08 11:48:26 +02:00
Dylan DPC
d5232c6b93
Rollup merge of #95579 - Cyborus04:slice_flatten, r=scottmcm
Add `<[[T; N]]>::flatten{_mut}`

Adds `flatten` to convert `&[[T; N]]` to `&[T]` (and `flatten_mut` for `&mut [[T; N]]` to `&mut [T]`)
2022-04-08 11:48:21 +02:00
Cyborus04
06788fd7a4 add <[[T; N]]>::flatten, <[[T; N]]>::flatten_mut, and Vec::<[T; N]>::into_flattened 2022-04-08 00:54:39 -04:00
Jack O'Connor
e0e64a8930 hide an #[allow] directive from the Arc::new_cyclic doc example 2022-04-07 18:00:46 -07:00
bors
f565016edd Auto merge of #95678 - pietroalbini:pa-1.62.0-bootstrap, r=Mark-Simulacrum
Bump bootstrap compiler to 1.61.0 beta

This PR bumps the bootstrap compiler to the 1.61.0 beta. The first commit changes the stage0 compiler, the second commit applies the "mechanical" changes and the third and fourth commits apply changes explained in the relevant comments.

r? `@Mark-Simulacrum`
2022-04-07 07:34:04 +00:00
Jane Lusby
0eb0d891ad add necessary closure for partition_point 2022-04-06 18:18:09 -07:00
Jane Lusby
c957b809e9 Update binary_search example to instead redirect to partition_point 2022-04-06 14:23:57 -07:00
Pietro Albini
181d28bb61
trivial cfg(bootstrap) changes 2022-04-05 23:18:40 +02:00
SparkyPotato
83f659b4bb formatting 2022-04-06 01:36:46 +05:30
SparkyPotato
9e9881bcd8 cleanup 2022-04-06 01:36:24 +05:30
SparkyPotato
31e7990145 fix Vec leak with 0 capacity 2022-04-06 01:32:26 +05:30
bors
168a020900 Auto merge of #92686 - saethlin:unsafe-debug-asserts, r=Amanieu
Add debug assertions to some unsafe functions

As suggested by https://github.com/rust-lang/rust/issues/51713

~~Some similar code calls `abort()` instead of `panic!()` but aborting doesn't work in a `const fn`, and the intrinsic for doing dispatch based on whether execution is in a const is unstable.~~

This picked up some invalid uses of `get_unchecked` in the compiler, and fixes them.

I can confirm that they do in fact pick up invalid uses of `get_unchecked` in the wild, though the user experience is less-than-awesome:
```
     Running unittests (target/x86_64-unknown-linux-gnu/debug/deps/rle_decode_fast-04b7918da2001b50)

running 6 tests
error: test failed, to rerun pass '--lib'

Caused by:
  process didn't exit successfully: `/home/ben/rle-decode-helper/target/x86_64-unknown-linux-gnu/debug/deps/rle_decode_fast-04b7918da2001b50` (signal: 4, SIGILL: illegal instruction)
```

~~As best I can tell these changes produce a 6% regression in the runtime of `./x.py test` when `[rust] debug = true` is set.~~
Latest commit (6894d559bd) brings the additional overhead from this PR down to 0.5%, while also adding a few more assertions. I think this actually covers all the places in `core` that it is reasonable to check for safety requirements at runtime.

Thoughts?
2022-04-03 16:04:47 +00:00
Ralf Jung
85bfe2d99d make utf8_char_counts test faster in Miri 2022-03-31 13:11:44 -04:00
Dylan DPC
c90a94707f
Rollup merge of #95491 - faern:stabilize-vec_retain_mut, r=yaahc
Stabilize feature vec_retain_mut on Vec and VecDeque

Closes #90829
2022-03-31 04:57:27 +02:00
Dylan DPC
d6c959c680
Rollup merge of #95298 - jhorstmann:fix-double-drop-of-allocator-in-vec-into-iter, r=oli-obk
Fix double drop of allocator in IntoIter impl of Vec

Fixes #95269

The `drop` impl of `IntoIter` reconstructs a `RawVec` from `buf`, `cap` and `alloc`, when that `RawVec` is dropped it also drops the allocator. To avoid dropping the allocator twice we wrap it in `ManuallyDrop` in the `InttoIter` struct.

Note this is my first contribution to the standard library, so I might be missing some details or a better way to solve this.
2022-03-31 00:26:32 +02:00
Linus Färnstrand
796f385190 Stabilize feature vec_retain_mut on Vec and VecDeque 2022-03-30 20:28:50 +02:00
bors
3e7514670d Auto merge of #94963 - lcnr:inherent-impls-std, r=oli-obk,m-ou-se
allow arbitrary inherent impls for builtin types in core

Part of https://github.com/rust-lang/compiler-team/issues/487. Slightly adjusted after some talks with `@m-ou-se` about the requirements of `t-libs-api`.

This adds a crate attribute `#![rustc_coherence_is_core]` which allows arbitrary impls for builtin types in core.

For other library crates impls for builtin types should be avoided if possible. We do have to allow the existing stable impls however. To prevent us from accidentally adding more of these in the future, there is a second attribute `#[rustc_allow_incoherent_impl]` which has to be added to **all impl items**. This only supports impls for builtin types but can easily be extended to additional types in a future PR.

This implementation does not check for overlaps in these impls. Perfectly checking that requires us to check the coherence of these incoherent impls in every crate, as two distinct dependencies may add overlapping methods. It should be easy enough to detect if it goes wrong and the attribute is only intended for use inside of std.

The first two commits are mostly unrelated cleanups.
2022-03-30 12:28:50 +00:00
lcnr
afbecc0f68 remove now unnecessary lang items 2022-03-30 11:23:58 +02:00
lcnr
bef6f3e895 rework implementation for inherent impls for builtin types 2022-03-30 11:23:58 +02:00
Aria Beingessner
37d4753776 fixup feature position in liballoc 2022-03-29 20:18:29 -04:00
Aria Beingessner
7514d760b8 cleanup some of the less terrifying library code 2022-03-29 20:18:27 -04:00
Aria Beingessner
c7de289e1c Make the stdlib largely conform to strict provenance.
Some things like the unwinders and system APIs are not fully conformant,
this only covers a lot of low-hanging fruit.
2022-03-29 20:18:21 -04:00
Ben Kimock
6e6d0cbf83 Add debug assertions to some unsafe functions
These debug assertions are all implemented only at runtime using
`const_eval_select`, and in the error path they execute
`intrinsics::abort` instead of being a normal debug assertion to
minimize the impact of these assertions on code size, when enabled.

Of all these changes, the bounds checks for unchecked indexing are
expected to be most impactful (case in point, they found a problem in
rustc).
2022-03-29 11:05:24 -04:00
bors
c1230e137b Auto merge of #95249 - HeroicKatora:set-ptr-value, r=dtolnay
Refactor set_ptr_value as with_metadata_of

Replaces `set_ptr_value` (#75091) with methods of reversed argument order:

```rust
impl<T: ?Sized> *mut T {
    pub fn with_metadata_of<U: ?Sized>(self, val: *mut U) -> *mut U;
}

impl<T: ?Sized> *const T {
    pub fn with_metadata_of<U: ?Sized>(self, val: *const U) -> *const U;
}
```

By reversing the arguments we achieve several clarifications:

- The function closely resembles `cast` with an argument to
  initialize the metadata. This is easier to teach and answers a long
  outstanding question that had restricted cast to `Sized` pointee
  targets. See multiples reviews of
  <https://github.com/rust-lang/rust/pull/47631>
- The 'object identity', in the form of provenance, is now preserved
  from the receiver argument to the result. This helps explain the method as
  a builder-style, instead of some kind of setter that would modify
  something in-place. Ensuring that the result has the identity of the
  `self` argument is also beneficial for an intuition of effects.
- An outstanding concern, 'Correct argument type', is avoided by not
  committing to any specific argument type. This is consistent with cast
  which does not require its receiver to be a 'raw address'.

Hopefully the usage examples in `sync/rc.rs` serve as sufficient examples of the style to convince the reader of the readability improvements of this style, when compared to the previous order of arguments.

I want to take the opportunity to motivate inclusion of this method _separate_ from metadata API, separate from `feature(ptr_metadata)`. It does _not_ involve the `Pointee` trait in any form. This may be regarded as a very, very light form that does not commit to any details of the pointee trait, or its associated metadata. There are several use cases for which this is already sufficient and no further inspection of metadata is necessary.

- Storing the coercion of `*mut T` into `*mut dyn Trait` as a way to dynamically cast some an arbitrary instance of the same type to a dyn trait instance. In particular, one can have a field of type `Option<*mut dyn io::Seek>` to memorize if a particular writer is seekable. Then a method `fn(self: &T) -> Option<&dyn Seek>` can be provided, which does _not_ involve the static trait bound `T: Seek`. This makes it possible to create an API that is capable of utilizing seekable streams and non-seekable streams (instead of a possible less efficient manner such as more buffering) through the same entry-point.

- Enabling more generic forms of unsizing for no-`std` smart pointers. Using the stable APIs only few concrete cases are available. One can unsize arrays to `[T]` by `ptr::slice_from_raw_parts` but unsizing a custom smart pointer to, e.g., `dyn Iterator`, `dyn Future`, `dyn Debug`, can't easily be done generically. Exposing `with_metadata_of` would allow smart pointers to offer their own `unsafe` escape hatch with similar parameters where the caller provides the unsized metadata. This is particularly interesting for embedded where `dyn`-trait usage can drastically reduce code size.
2022-03-28 22:47:31 +00:00
Dylan DPC
8bfc03fde0
Rollup merge of #95098 - shepmaster:vec-from-array-ref, r=dtolnay
impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>

I really wanted to write:

```rust
fn example(a: impl Into<Vec<u8>>) {}

fn main() {
    example(b"raw");
}
```
2022-03-28 04:12:11 +02:00
Dylan DPC
d88c03c0f1
Rollup merge of #95016 - janpaul123:patch-1, r=dtolnay
Docs: make Vec::from_raw_parts documentation less strict

This is my first PR; be gentle!

In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters.

Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too.

Let me know what you think! :)
2022-03-28 04:12:10 +02:00
Dylan DPC
6ed1a67b38
Rollup merge of #93755 - ChayimFriedman2:allow-comparing-vecs-with-different-allocators, r=dtolnay
Allow comparing `Vec`s with different allocators using `==`

See https://stackoverflow.com/q/71021633/7884305.

I did not changed the `PartialOrd` impl too because it was not generic already (didn't support `Vec<T> <=> Vec<U> where T: PartialOrd<U>`).

Does it needs tests?

I don't think this will hurt type inference much because the default allocator is usually not inferred (`new()` specifies it directly, and even with other allocators, you pass the allocator to `new_in()` so the compiler usually knows the type).

I think this requires FCP since the impls are already stable.
2022-03-28 04:12:10 +02:00
Dylan DPC
eca2531155
Rollup merge of #95368 - lopopolo:lopopolo/string-try-reserve-exact-doc-typo, r=Dylan-DPC
Fix typo in `String::try_reserve_exact` docs

Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`,
it looks like this doc comment is intending to refer to the currently-being-documented
function.
2022-03-27 22:51:42 +02:00
Ryan Lopopolo
1ba885113a
Fix typo in String::try_reserve_exact docs
Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`,
it looks like this doc comment is intending to refer to the currently-being-documented
function.
2022-03-27 06:53:55 -07:00
Martin Kröning
8f47635254 Use default alloc_error_handler for hermit
Hermit now properly separates kernel from userspace.
Applications for hermit can now use Rust's default alloc_error_handler instead of calling the kernel's __rg_oom.
2022-03-27 14:14:34 +02:00
David Tolnay
2ac9efbe95
Debug print char 0 as '\0' rather than '\u{0}' 2022-03-27 04:49:10 -07:00
Scott McMurray
8034c45a07 Support arrays of zeros in Vec's __rust_alloc_zeroed optimization 2022-03-27 01:50:07 -07:00
Jörn Horstmann
d9a438dc73 Add another assertion without into_iter 2022-03-25 16:57:59 +01:00
Jörn Horstmann
4b53f563bd Add a test verifying the number of drop calls 2022-03-25 13:28:19 +01:00
Jörn Horstmann
d14c0d2acb
Use ManuallyDrop::take instead of into_inner
Co-authored-by: Daniel Henry-Mantilla <daniel.henry.mantilla@gmail.com>
2022-03-25 13:27:18 +01:00
Jörn Horstmann
0cf606177e Fix double drop of allocator in IntoIter impl of Vec 2022-03-25 11:39:11 +01:00
CAD97
7b58193f90 Adjust tests for isize::MAX allocation always being checked 2022-03-25 00:57:05 -05:00
bors
6970f88db3 Auto merge of #87667 - the8472:document-in-place-iter, r=yaahc
add module-level documentation for vec's in-place iteration

As requested in the last libs team meeting and during previous reviews.

Feel free to point out any gaps you encounter, after all non-obvious things may with hindsight seem obvious to me.

r? `@yaahc`

CC `@steffahn`
2022-03-24 01:43:21 +00:00
The 8472
29e29ce65d fix some links, clarify documentation based on review feedback 2022-03-23 20:57:49 +01:00
Andreas Molzer
d489ea777d Refactor set_ptr_value as with_metadata_of
By reversing the arguments we achieve several clarifications:

- The function closely resembles `cast` but with an argument to
  initialized the metadata. This is easier to teach and answers an long
  outstanding question that had restricted cast to `Sized` targets
  initially. See multiples reviews of
  <https://github.com/rust-lang/rust/pull/47631>
- The 'object identity', in the form or provenance, is now preserved
  from the call receiver to the result. This helps explain the method as
  a builder-style, instead of some kind of setter that would modify
  something in-place. Ensuring that the result has the identity of the
  `self` argument is also beneficial for an intuition of effects.
- An outstanding concern, 'Correct argument type', is avoided by not
  committing to any specific argument type. This is consistent with cast
  which does not require its receiver to be a raw address.
2022-03-23 19:59:37 +01:00
Michael Bradshaw
8d14c03568
Explicitly mention overflow is what we're checking 2022-03-23 08:14:53 -06:00
Jonathan Giddy
9f4934ec19 Clarify that Cow::into_owned returns owned data 2022-03-23 13:01:00 +00:00
Michael Bradshaw
f5dd42bce5
Format unsafe {} blocks 2022-03-22 20:42:03 -06:00
Michael Bradshaw
3f7f5e8a2e
Optimize RcInnerPtr::inc_strong instruction count
Inspired by this internals thread: https://internals.rust-lang.org/t/rc-optimization-on-64-bit-targets/16362

[The generated assembly is a bit smaller](https://rust.godbolt.org/z/TeTnf6144) and is a more efficient usage of the CPU's instruction cache. `unlikely` doesn't impact any of the small artificial tests I've done, but I've included it in case it might help more complex scenarios when this is inlined.
2022-03-22 20:21:56 -06:00
Tobias Bucher
4123d33fbd Remove impossible panic note from Vec::append
Neither the number of elements in a vector can overflow a `usize`, nor
can the amount of elements in two vectors.
2022-03-22 21:07:43 +01:00
The 8472
7549cfa599 rename internal helper trait AsIntoIter to AsVecIntoIter 2022-03-22 00:02:54 +01:00
Ibraheem Ahmed
7e93032726 weaken needlessly restrictive orderings on Arc::*_count 2022-03-21 17:32:00 -04:00
The8472
a1a602adde add module-level documentation for vec's in-place iteration 2022-03-21 22:29:38 +01:00
The8472
79b43b35be move AsIntoIter helper trait and mark it as unsafe 2022-03-21 22:29:38 +01:00
The8472
47a7a07a8b rename module to better reflect its purpose 2022-03-21 22:29:38 +01:00
Deadbeef
1f3ee7f32e
Rename ~const Drop to ~const Destruct 2022-03-21 17:04:03 +11:00
bors
c7ce69faf2 Auto merge of #92962 - frank-king:btree_entry_no_insert, r=Amanieu
BTreeMap::entry: Avoid allocating if no insertion

This PR allows the `VacantEntry` to borrow from an empty tree with no root, and to lazily allocate a new root node when the user calls `.insert(value)`.
2022-03-20 11:20:26 +00:00
Jake Goulding
5dd702763a impl From<&[T; N]> and From<&mut [T; N]> for Vec<T> 2022-03-18 20:31:53 -04:00
CAD97
a358ad2aff Make Weak::new const 2022-03-18 17:47:36 -05:00
JP Posma
80340f62fe
Docs: make Vec::from_raw_parts documentation less strict
This is my first PR; be gentle!

In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters.

Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too.

Let me know what you think! :)
2022-03-16 09:34:12 -07:00
Stein Somers
ea4e5c27a9 BTree: evaluate static type-related check at compile time 2022-03-16 13:51:31 +01:00
Dylan DPC
13e889986d fix typos 2022-03-15 02:00:08 +01:00
DeveloperC
cf30ac847d refactor: VecDeques Iter fields to private
Made the fields of VecDeque's Iter private by creating a Iter::new(...) function to create a new instance of Iter and migrating usage to use Iter::new(...).
2022-03-14 00:35:41 +00:00
bors
335ffbfa54 Auto merge of #94472 - JmPotato:use_maybeuninit_for_vecdeque, r=m-ou-se
Use MaybeUninit in VecDeque to remove the undefined behavior of slice

Signed-off-by: JmPotato <ghzpotato@gmail.com>

Ref https://github.com/rust-lang/rust/issues/74189. Adjust the code to follow the [doc.rust-lang.org/reference/behavior-considered-undefined.html](https://doc.rust-lang.org/reference/behavior-considered-undefined.html).

* Change the return type of `buffer_as_slice` from `&[T]` to `&[MaybeUninit<T>]`.
* Add some corresponding safety comments.

Benchmark results:

master 8d6f527530

```rust
test collections::vec_deque::tests::bench_pop_back_100       ... bench:          47 ns/iter (+/- 1)
test collections::vec_deque::tests::bench_pop_front_100      ... bench:          50 ns/iter (+/- 4)
test collections::vec_deque::tests::bench_push_back_100      ... bench:          69 ns/iter (+/- 10)
test collections::vec_deque::tests::bench_push_front_100     ... bench:          72 ns/iter (+/- 6)
test collections::vec_deque::tests::bench_retain_half_10000  ... bench:     145,891 ns/iter (+/- 7,975)
test collections::vec_deque::tests::bench_retain_odd_10000   ... bench:     141,647 ns/iter (+/- 3,711)
test collections::vec_deque::tests::bench_retain_whole_10000 ... bench:     120,132 ns/iter (+/- 4,078)
```

This PR

```rust
test collections::vec_deque::tests::bench_pop_back_100       ... bench:          48 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_pop_front_100      ... bench:          51 ns/iter (+/- 3)
test collections::vec_deque::tests::bench_push_back_100      ... bench:          73 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_push_front_100     ... bench:          73 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_retain_half_10000  ... bench:     131,796 ns/iter (+/- 5,440)
test collections::vec_deque::tests::bench_retain_odd_10000   ... bench:     137,563 ns/iter (+/- 3,349)
test collections::vec_deque::tests::bench_retain_whole_10000 ... bench:     128,815 ns/iter (+/- 3,289)
```
2022-03-11 19:23:55 +00:00
Stein Somers
a3a5d83e66 Classify BinaryHeap & LinkedList unit tests as such 2022-03-11 11:33:59 +01:00
Dylan DPC
f97a1c6909
Rollup merge of #94826 - allgoewer:fix-retain-documentation, r=yaahc
Improve doc wording for retain on some collections

I found the documentation wording on the various retain methods on many collections to be unusual.
I tried to invert the relation by switching `such that` with `for which` .
2022-03-11 03:32:06 +01:00
Maik Allgöwer
229e01d11f Improve doc wording for retain on some collections 2022-03-11 00:29:43 +01:00
Dylan DPC
5a7f09d9a3
Rollup merge of #93950 - T-O-R-U-S:use-modern-formatting-for-format!-macros, r=Mark-Simulacrum
Use modern formatting for format! macros

This updates the standard library's documentation to use the new format_args syntax.
The documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).

`eprintln!("{}", e)` becomes `eprintln!("{e}")`, but `eprintln!("{}", e.kind())` remains untouched.
2022-03-10 23:12:57 +01:00
T-O-R-U-S
72a25d05bf Use implicit capture syntax in format_args
This updates the standard library's documentation to use the new syntax. The
documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).
2022-03-10 10:23:40 -05:00
Oli Scherer
5f7ca55df6 Revert accidental stabilization 2022-03-10 14:36:51 +00:00
JmPotato
2f18fa801b Use MaybeUninit in VecDeque to remove the undefined behavior of slice
Signed-off-by: JmPotato <ghzpotato@gmail.com>
2022-03-10 14:14:25 +08:00
Frank King
2c3c891df0 BTreeMap::entry: Avoid allocating if no insertion 2022-03-09 22:29:05 +08:00
Dylan DPC
4de06d459f
Rollup merge of #94699 - ssomers:btree_prune_insert, r=Dylan-DPC
BTree: remove dead data needlessly complicating insert

Possibly needless instructions generated

r? rust-lang/libs
r? ``@Amanieu``
cc ``@frank-king``
2022-03-09 06:38:52 +01:00
Eric Holk
7723506d13 Stabilize const_fn_fn_ptr_basics and const_fn_trait_bound 2022-03-07 08:47:15 -08:00
Stein Somers
36bb53d497 BTree: remove dead data needlessly complicating insert 2022-03-07 13:57:56 +01:00
Matthias Krüger
9d23c320e4
Rollup merge of #92399 - Veeupup:fix_vec_typo, r=Dylan-DPC
fix typo in btree/vec doc: Self -> self

this pr fixes #92345
the documentation refers to the object the method is called for, not the type, so it should be using the lower case self.
2022-02-28 20:05:13 +01:00
Mark Rousskov
22c3a71de1 Switch bootstrap cfgs 2022-02-25 08:00:52 -05:00
Matthias Krüger
e5bd222c6b
Rollup merge of #94184 - ssomers:btree_tests, r=Dylan-DPC
BTree: simplify test code

Mostly, use `from` & `from_iter`.
2022-02-25 07:30:49 +01:00
bors
5bd1ec3283 Auto merge of #83706 - a1phyr:fix_vec_layout_calculation, r=JohnTitor
Fix a layout possible miscalculation in `alloc::RawVec`

A layout miscalculation could happen in `RawVec` when used with a type whose size isn't a multiple of its alignment. I don't know if such type can exist in Rust, but the Layout API provides ways to manipulate such types. Anyway, it is better to calculate memory size in a consistent way.
2022-02-22 20:50:38 +00:00
Stein Somers
7950ebcd8e BTree: simplify test code 2022-02-20 14:43:59 +01:00
r00ster91
c186460677 Fix some confusing wording and improve slice-search-related docs 2022-02-19 17:29:51 +01:00
Matthias Krüger
4fa71ed0f0
Rollup merge of #92902 - ssomers:docter_drain, r=yaahc
Improve the documentation of drain members

hopefully fixes #92765
2022-02-19 06:45:28 +01:00
Stein Somers
a677e60840 Collections: improve the documentation of drain members 2022-02-19 00:55:31 +01:00
Matthias Krüger
f1c918f1f3
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
Move `{core,std}::stream::Stream` to `{core,std}::async_iter::AsyncIterator`

Following amendments in https://github.com/rust-lang/rfcs/pull/3208/.

cc #79024
cc ``@yoshuawuyts`` ``@joshtriplett``
2022-02-18 16:23:32 +01:00
Matthias Krüger
1cc0ae4cbb
Rollup merge of #89869 - kpreid:from-doc, r=yaahc
Add documentation to more `From::from` implementations.

For users looking at documentation through IDE popups, this gives them relevant information rather than the generic trait documentation wording “Performs the conversion”. For users reading the documentation for a specific type for any reason, this informs them when the conversion may allocate or copy significant memory versus when it is always a move or cheap copy.

Notes on specific cases:
* The new documentation for `From<T> for T` explains that it is not a conversion at all.
* Also documented `impl<T, U> Into<U> for T where U: From<T>`, the other central blanket implementation of conversion.
* The new documentation for construction of maps and sets from arrays of keys mentions the handling of duplicates. Future work could be to do this for *all* code paths that convert an iterable to a map or set.
* I did not add documentation to conversions of a specific error type to a more general error type.
* I did not add documentation to unstable code.

This change was prepared by searching for the text "From<... for" and so may have missed some cases that for whatever reason did not match. I also looked for `Into` impls but did not find any worth documenting by the above criteria.
2022-02-17 06:29:57 +01:00
Stein Somers
5d5359759d Describe VecDeque with more consistent names 2022-02-14 11:17:27 +01:00
SaltyKitkat
3c142b0ffe
stabilize const_ptr_offset 2022-02-13 15:26:14 +08:00
ltdk
de6e973176 Stabilise inherent_ascii_escape (FCP in #77174) 2022-02-12 13:21:59 -05:00
Alphyr
fe7d7c2004 Fix typo
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-02-12 12:31:33 +01:00
Benoît du Garreau
d3e2ffcbc6 Fix shrink and capacity_from_bytes 2022-02-12 11:51:15 +01:00
Benoît du Garreau
6027182328 Fix a layout miscalculation in alloc::RawVec 2022-02-12 11:40:59 +01:00
Matthias Krüger
aa2095936a
Rollup merge of #93824 - Amanieu:stable_cfg_target_has_atomic, r=davidtwco
Stabilize cfg_target_has_atomic

`target_has_atomic_equal_alignment` is now tracked separately in #93822.

Closes #32976
2022-02-10 12:10:00 +01:00
Amanieu d'Antras
49d4823112 Stabilize cfg_target_has_atomic
Closes #32976
2022-02-09 18:45:44 +00:00
Titus
3d3318b406
Fix typo in std::fmt docs 2022-02-09 11:26:10 +01:00
Chayim Refael Friedman
ee23fd2ca3 Allow comparing Vecs with different allocators using == 2022-02-08 01:50:55 +00:00
ltdk
edd318c313 Add {floor,ceil}_char_boundary methods to str 2022-02-07 13:34:08 -05:00
bors
f624427f87 Auto merge of #90414 - thomcc:count-chars-faster, r=nagisa
Optimize `core::str::Chars::count`

I wrote this a while ago after seeing this function as a bottleneck in a profile, but never got around to contributing it. I saw it again, and so here it is. The implementation is fairly complex, but I tried to explain what's happening at both a high level (in the header comment for the file), and in line comments in the impl. Hopefully it's clear enough.

This implementation (`case00_cur_libcore` in the benchmarks below) is somewhat consistently around 4x to 5x faster than the old implementation (`case01_old_libcore` in the benchmarks below), for a wide variety of workloads, without regressing performance on any of the workload sizes I've tried.

I also improved the benchmarks for this code, so that they explicitly check text in different languages and of different sizes (err, the cross product of language x size). The results of the benchmarks are here:

<details>
<summary>Benchmark results</summary>
<pre>
test str::char_count::emoji_huge::case00_cur_libcore       ... bench:      20,216 ns/iter (+/- 3,673) = 17931 MB/s
test str::char_count::emoji_huge::case01_old_libcore       ... bench:     108,851 ns/iter (+/- 12,777) = 3330 MB/s
test str::char_count::emoji_huge::case02_iter_increment    ... bench:     329,502 ns/iter (+/- 4,163) = 1100 MB/s
test str::char_count::emoji_huge::case03_manual_char_len   ... bench:     223,333 ns/iter (+/- 14,167) = 1623 MB/s
test str::char_count::emoji_large::case00_cur_libcore      ... bench:         293 ns/iter (+/- 6) = 19331 MB/s
test str::char_count::emoji_large::case01_old_libcore      ... bench:       1,681 ns/iter (+/- 28) = 3369 MB/s
test str::char_count::emoji_large::case02_iter_increment   ... bench:       5,166 ns/iter (+/- 85) = 1096 MB/s
test str::char_count::emoji_large::case03_manual_char_len  ... bench:       3,476 ns/iter (+/- 62) = 1629 MB/s
test str::char_count::emoji_medium::case00_cur_libcore     ... bench:          48 ns/iter (+/- 0) = 14750 MB/s
test str::char_count::emoji_medium::case01_old_libcore     ... bench:         217 ns/iter (+/- 4) = 3262 MB/s
test str::char_count::emoji_medium::case02_iter_increment  ... bench:         642 ns/iter (+/- 7) = 1102 MB/s
test str::char_count::emoji_medium::case03_manual_char_len ... bench:         445 ns/iter (+/- 3) = 1591 MB/s
test str::char_count::emoji_small::case00_cur_libcore      ... bench:          18 ns/iter (+/- 0) = 3777 MB/s
test str::char_count::emoji_small::case01_old_libcore      ... bench:          23 ns/iter (+/- 0) = 2956 MB/s
test str::char_count::emoji_small::case02_iter_increment   ... bench:          66 ns/iter (+/- 2) = 1030 MB/s
test str::char_count::emoji_small::case03_manual_char_len  ... bench:          29 ns/iter (+/- 1) = 2344 MB/s
test str::char_count::en_huge::case00_cur_libcore          ... bench:      25,909 ns/iter (+/- 39,260) = 13299 MB/s
test str::char_count::en_huge::case01_old_libcore          ... bench:     102,887 ns/iter (+/- 3,257) = 3349 MB/s
test str::char_count::en_huge::case02_iter_increment       ... bench:     166,370 ns/iter (+/- 12,439) = 2071 MB/s
test str::char_count::en_huge::case03_manual_char_len      ... bench:     166,332 ns/iter (+/- 4,262) = 2071 MB/s
test str::char_count::en_large::case00_cur_libcore         ... bench:         281 ns/iter (+/- 6) = 19160 MB/s
test str::char_count::en_large::case01_old_libcore         ... bench:       1,598 ns/iter (+/- 19) = 3369 MB/s
test str::char_count::en_large::case02_iter_increment      ... bench:       2,598 ns/iter (+/- 167) = 2072 MB/s
test str::char_count::en_large::case03_manual_char_len     ... bench:       2,578 ns/iter (+/- 55) = 2088 MB/s
test str::char_count::en_medium::case00_cur_libcore        ... bench:          44 ns/iter (+/- 1) = 15295 MB/s
test str::char_count::en_medium::case01_old_libcore        ... bench:         201 ns/iter (+/- 51) = 3348 MB/s
test str::char_count::en_medium::case02_iter_increment     ... bench:         322 ns/iter (+/- 40) = 2090 MB/s
test str::char_count::en_medium::case03_manual_char_len    ... bench:         319 ns/iter (+/- 5) = 2109 MB/s
test str::char_count::en_small::case00_cur_libcore         ... bench:          15 ns/iter (+/- 0) = 2333 MB/s
test str::char_count::en_small::case01_old_libcore         ... bench:          14 ns/iter (+/- 0) = 2500 MB/s
test str::char_count::en_small::case02_iter_increment      ... bench:          30 ns/iter (+/- 1) = 1166 MB/s
test str::char_count::en_small::case03_manual_char_len     ... bench:          30 ns/iter (+/- 1) = 1166 MB/s
test str::char_count::ru_huge::case00_cur_libcore          ... bench:      16,439 ns/iter (+/- 3,105) = 19777 MB/s
test str::char_count::ru_huge::case01_old_libcore          ... bench:      89,480 ns/iter (+/- 2,555) = 3633 MB/s
test str::char_count::ru_huge::case02_iter_increment       ... bench:     217,703 ns/iter (+/- 22,185) = 1493 MB/s
test str::char_count::ru_huge::case03_manual_char_len      ... bench:     157,330 ns/iter (+/- 19,188) = 2066 MB/s
test str::char_count::ru_large::case00_cur_libcore         ... bench:         243 ns/iter (+/- 6) = 20905 MB/s
test str::char_count::ru_large::case01_old_libcore         ... bench:       1,384 ns/iter (+/- 51) = 3670 MB/s
test str::char_count::ru_large::case02_iter_increment      ... bench:       3,381 ns/iter (+/- 543) = 1502 MB/s
test str::char_count::ru_large::case03_manual_char_len     ... bench:       2,423 ns/iter (+/- 429) = 2096 MB/s
test str::char_count::ru_medium::case00_cur_libcore        ... bench:          42 ns/iter (+/- 1) = 15119 MB/s
test str::char_count::ru_medium::case01_old_libcore        ... bench:         180 ns/iter (+/- 4) = 3527 MB/s
test str::char_count::ru_medium::case02_iter_increment     ... bench:         402 ns/iter (+/- 45) = 1579 MB/s
test str::char_count::ru_medium::case03_manual_char_len    ... bench:         280 ns/iter (+/- 29) = 2267 MB/s
test str::char_count::ru_small::case00_cur_libcore         ... bench:          12 ns/iter (+/- 0) = 2666 MB/s
test str::char_count::ru_small::case01_old_libcore         ... bench:          12 ns/iter (+/- 0) = 2666 MB/s
test str::char_count::ru_small::case02_iter_increment      ... bench:          19 ns/iter (+/- 0) = 1684 MB/s
test str::char_count::ru_small::case03_manual_char_len     ... bench:          14 ns/iter (+/- 1) = 2285 MB/s
test str::char_count::zh_huge::case00_cur_libcore          ... bench:      15,053 ns/iter (+/- 2,640) = 20067 MB/s
test str::char_count::zh_huge::case01_old_libcore          ... bench:      82,622 ns/iter (+/- 3,602) = 3656 MB/s
test str::char_count::zh_huge::case02_iter_increment       ... bench:     230,456 ns/iter (+/- 7,246) = 1310 MB/s
test str::char_count::zh_huge::case03_manual_char_len      ... bench:     220,595 ns/iter (+/- 11,624) = 1369 MB/s
test str::char_count::zh_large::case00_cur_libcore         ... bench:         227 ns/iter (+/- 65) = 20792 MB/s
test str::char_count::zh_large::case01_old_libcore         ... bench:       1,136 ns/iter (+/- 144) = 4154 MB/s
test str::char_count::zh_large::case02_iter_increment      ... bench:       3,147 ns/iter (+/- 253) = 1499 MB/s
test str::char_count::zh_large::case03_manual_char_len     ... bench:       2,993 ns/iter (+/- 400) = 1577 MB/s
test str::char_count::zh_medium::case00_cur_libcore        ... bench:          36 ns/iter (+/- 5) = 16388 MB/s
test str::char_count::zh_medium::case01_old_libcore        ... bench:         142 ns/iter (+/- 18) = 4154 MB/s
test str::char_count::zh_medium::case02_iter_increment     ... bench:         379 ns/iter (+/- 37) = 1556 MB/s
test str::char_count::zh_medium::case03_manual_char_len    ... bench:         364 ns/iter (+/- 51) = 1620 MB/s
test str::char_count::zh_small::case00_cur_libcore         ... bench:          11 ns/iter (+/- 1) = 3000 MB/s
test str::char_count::zh_small::case01_old_libcore         ... bench:          11 ns/iter (+/- 1) = 3000 MB/s
test str::char_count::zh_small::case02_iter_increment      ... bench:          20 ns/iter (+/- 3) = 1650 MB/s
</pre>
</details>

I also added fairly thorough tests for different sizes and alignments. This completes on my machine in 0.02s, which is surprising given how thorough they are, but it seems to detect bugs in the implementation. (I haven't run the tests on a 32 bit machine yet since before I reworked the code a little though, so... hopefully I'm not about to embarrass myself).

This uses similar SWAR-style techniques to the `is_ascii` impl I contributed in https://github.com/rust-lang/rust/pull/74066, so I'm going to request review from the same person who reviewed that one. That said am not particularly picky, and might not have the correct syntax for requesting a review from someone (so it goes).

r? `@nagisa`
2022-02-06 08:34:48 +00:00
Amanieu d'Antras
915a16035d Mark __rgl_oom and __rd_oom as "C-unwind" 2022-02-05 20:58:04 +00:00
Amanieu d'Antras
b1b8810952 Allow handle_alloc_error to unwind 2022-02-05 20:58:04 +00:00
Thom Chiovoloni
002aaf2c65
Ensure non-power-of-two sizes are tested in the Chars::count test 2022-02-05 11:15:18 -08:00
Thom Chiovoloni
628b217326
Optimize core::str::Chars::count 2022-02-05 11:15:17 -08:00
Charles Lew
18130a21dc Move {core,std}::stream::Stream to {core,std}::async_iter::AsyncIterator. 2022-02-03 21:03:06 +08:00
Richard Dodd
f5e6d16d00 Add tracking issue and impl for Rc. 2022-02-03 10:40:31 +00:00
Richard Dodd
0602fb0c6e impl Arc::unwrap_or_clone
The function gets the inner value, cloning only if necessary.
2022-02-03 09:16:04 +00:00
Eric Huss
0610d4fa66
Rollup merge of #92887 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bootstrap compiler update

r? ``@Mark-Simulacrum``
2022-01-30 08:37:46 -08:00
Pietro Albini
5b3462c556
update cfg(bootstrap)s 2022-01-28 15:01:07 +01:00
Matthias Krüger
1dd0ac1f6a
Rollup merge of #91861 - juniorbassani:use-from-array-in-collections-examples, r=yaahc
Replace iterator-based construction of collections by `Into<T>`

Just a few quality of life improvements in the doc examples. I also removed some `Vec`s in favor of arrays.
2022-01-26 23:45:19 +01:00
Matthias Krüger
59d9ad98b6
Rollup merge of #90666 - bdbai:arc_new_cyclic, r=m-ou-se
Stabilize arc_new_cyclic

This stabilizes feature `arc_new_cyclic` as the implementation has been merged for one year and there is no unresolved questions. The FCP is not started yet.

Closes #75861 .

``@rustbot`` label +T-libs-api
2022-01-23 01:09:40 +01:00
Mara Bos
00e191c72d
Update stabilization version of arc_new_cyclic 2022-01-22 15:48:42 +00:00
Matthias Krüger
9474c74fb6
Rollup merge of #93109 - JakobDegen:arc-docs, r=m-ou-se
Improve `Arc` and `Rc` documentation

This makes two changes (I can split the PR if necessary, but the changes are pretty small):
 1. A bunch of trait implementations claimed to be zero cost; however, they use the `Arc<T>: From<Box<T>>` impl which is definitely not free, especially for large dynamically sized `T`.
 2.  The code in deferred initialization examples unnecessarily used excessive amounts of `unsafe`. This has been reduced.
2022-01-21 22:03:18 +01:00
Jakob Degen
4de76184aa Remove unnecessary unsafe code in Arc deferred initialization examples. 2022-01-20 06:21:51 -05:00
bors
74fbbefea8 Auto merge of #92138 - AngelicosPhosphoros:try_smarter_vec_from_iter_48994_2, r=Mark-Simulacrum
Improve capacity estimation in Vec::from_iter

Iterates on the attempt made in #53086.

Closes #48994
2022-01-20 06:50:14 +00:00
AngelicosPhosphoros
ea570c689c Improve estimation of capacity in Vec::from_iter
Closes #48994
2022-01-19 09:47:49 -05:00
Matthias Krüger
2a4381d8ea
Rollup merge of #89621 - digama0:patch-2, r=yaahc
doc: guarantee call order for sort_by_cached_key

`slice::sort_by_cached_key` takes a caching function `f: impl FnMut(&T) -> K`, which means that the order that calls to the caching function are made is user-visible. This adds a clause to the documentation to promise the current behavior, which is that `f` is called on all elements of the slice from left to right, unless the slice has len < 2 in which case `f` is not called.

For example, this can be used to ensure that the following code is a correct way to involve the index of the element in the sort key:
```rust
let mut index = 0;
slice.sort_by_cached_key(|x| (my_key(index, x), index += 1).0);
```
2022-01-19 10:42:13 +01:00
Júnior Bassani
8936659297
Replace iterator-based construction of collections by Into<T> 2022-01-18 12:18:02 -03:00
Matthias Krüger
83b1a9452a
Rollup merge of #93016 - Amanieu:vec_spare_capacity, r=Mark-Simulacrum
Stabilize vec_spare_capacity

Closes #75017
2022-01-18 04:42:11 +01:00
Amanieu d'Antras
e012b9a78d Stabilize vec_spare_capacity
Closes #75017
2022-01-17 21:07:02 +00:00
Matthias Krüger
7bdd978c24
Rollup merge of #92977 - kornelski:popdoc, r=dtolnay
Docs: recommend VecDeque instead of Vec::remove(0)

Suggestion based on a [discussion](https://internals.rust-lang.org/t/should-vec-have-a-try-remove-mut-self-usize-option-t-function/15964/9?u=kornel) where user needlessly struggled with `remove(0)` and accidentally created a quadratic cost.
2022-01-17 06:08:18 +01:00
Kornel
361ef2aadc Docs: recommend VecDeque instead of Vec::remove(0) 2022-01-16 17:53:05 +00:00
Matthias Krüger
039d6dc289
Rollup merge of #92706 - umanwizard:btree, r=dtolnay
Clarify explicitly that BTree{Map,Set} are ordered.

One of the main reasons one would want to use a BTree{Map,Set} rather than a Hash{Map,Set} is because they maintain their keys in sorted order; but this was never explicitly stated in the top-level docs (it was only indirectly alluded to there, and stated explicitly in the docs for `iter`, `values`, etc.)

This PR states the ordering guarantee more prominently.
2022-01-16 16:58:16 +01:00
Matthias Krüger
cf4549c920
Rollup merge of #92619 - Alexendoo:macro-diagnostic-items, r=matthewjasper
Add diagnostic items for macros

For use in Clippy, it adds diagnostic items to all the stable public macros

Clippy has lints that look for almost all of these (currently by name or path), but there are a few that aren't currently part of any lint, I could remove those if it's preferred to add them as needed rather than ahead of time
2022-01-16 16:58:14 +01:00
David Tolnay
ad6408dd7a
Tweak btree iterator wording to not use 'yield'
Yield means something else in the context of generators, which are
sufficiently close to iterators that it's better to avoid the
terminology collision here.
2022-01-15 19:28:21 -08:00
bors
a0984b4e4c Auto merge of #92598 - Badel2:panic-update-hook, r=yaahc
Implement `panic::update_hook`

Add a new function `panic::update_hook` to allow creating panic hooks that forward the call to the previously set panic hook, without race conditions. It works by taking a closure that transforms the old panic hook into a new one, while ensuring that during the execution of the closure no other thread can modify the panic hook. This is a small function so I hope it can be discussed here without a formal RFC, however if you prefer I can write one.

Consider the following example:

```rust
let prev = panic::take_hook();
panic::set_hook(Box::new(move |info| {
    println!("panic handler A");
    prev(info);
}));
```

This is a common pattern in libraries that need to do something in case of panic: log panic to a file, record code coverage, send panic message to a monitoring service, print custom message with link to github to open a new issue, etc. However it is impossible to avoid race conditions with the current API, because two threads can execute in this order:

* Thread A calls `panic::take_hook()`
* Thread B calls `panic::take_hook()`
* Thread A calls `panic::set_hook()`
* Thread B calls `panic::set_hook()`

And the result is that the original panic hook has been lost, as well as the panic hook set by thread A. The resulting panic hook will be the one set by thread B, which forwards to the default panic hook. This is not considered a big issue because the panic handler setup is usually run during initialization code, probably before spawning any other threads.

Using the new `panic::update_hook` function, this race condition is impossible, and the result will be either `A, B, original` or `B, A, original`.

```rust
panic::update_hook(|prev| {
    Box::new(move |info| {
        println!("panic handler A");
        prev(info);
    })
});
```

I found one real world use case here: 988cf403e7/src/detection.rs (L32) the workaround is to detect the race condition and panic in that case.

The pattern of `take_hook` + `set_hook` is very common, you can see some examples in this pull request, so I think it's natural to have a function that combines them both. Also using `update_hook` instead of `take_hook` + `set_hook` reduces the number of calls to `HOOK_LOCK.write()` from 2 to 1, but I don't expect this to make any difference in performance.

### Unresolved questions:

* `panic::update_hook` takes a closure, if that closure panics the error message is "panicked while processing panic" which is not nice. This is a consequence of holding the `HOOK_LOCK` while executing the closure. Could be avoided using `catch_unwind`?

* Reimplement `panic::set_hook` as `panic::update_hook(|_prev| hook)`?
2022-01-16 02:18:42 +00:00
Matthias Krüger
784e4ba9a4
Rollup merge of #92879 - compiler-errors:into_iter_unsound, r=dtolnay
Add Sync bound to allocator parameter in vec::IntoIter

The `A: Sync` bound was forgotten in 8725e4c337 (diff-b78c3ab6d37f4ede32195707528f8a76c49d4557cc9d3a7a09417b5157729b9fR3132)

Similar `unsafe impl Sync` in that commit _do_ include the `A: Sync` bound (and around the alloc lib), so I think this was just an honest mistake.

Here's an example of the unsoundness:  https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=16cbfeff7c934ae72ab632c1476fdd8b

`@steffahn` found this, I'm just putting up the fix cause nobody else did :^)

Fixes #92633
2022-01-15 11:28:27 +01:00
Matthias Krüger
558da934c1
Rollup merge of #92768 - ojeda:stabilize-maybe_uninit_extra, r=Mark-Simulacrum
Partially stabilize `maybe_uninit_extra`

This covers:

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

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

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

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-01-14 07:47:33 +01:00
Michael Goulet
7debb5c785 Add Sync bound to allocator parameter in vec::IntoIter 2022-01-13 20:55:21 -08:00
Brennan Vincent
65d47347ad Address review comments 2022-01-11 12:08:46 -07:00
Miguel Ojeda
8680a44c0f Partially stabilize maybe_uninit_extra
This covers:

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

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

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

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-01-11 17:01:13 +01:00
bors
2e2c86eba2 Auto merge of #92070 - rukai:replace_vec_into_iter_with_array_into_iter, r=Mark-Simulacrum
Replace usages of vec![].into_iter with [].into_iter

`[].into_iter` is idiomatic over `vec![].into_iter` because its simpler and faster (unless the vec is optimized away in which case it would be the same)

So we should change all the implementation, documentation and tests to use it.

I skipped:
* `src/tools` - Those are copied in from upstream
* `src/test/ui` - Hard to tell if `vec![].into_iter` was used intentionally or not here and not much benefit to changing it.
*  any case where `vec![].into_iter` was used because we specifically needed a `Vec::IntoIter<T>`
*  any case where it looked like we were intentionally using `vec![].into_iter` to test it.
2022-01-11 14:23:24 +00:00
Brennan Vincent
9057a6d66a Clarify explicitly that BTree{Map,Set} are ordered. 2022-01-09 18:01:44 -05:00
Lamb
3a77bb86ff Compute most of Public/Exported access level in rustc_resolve
Mak DefId to AccessLevel map in resolve for export

hir_id to accesslevel in resolve and applied in privacy
using local def id
removing tracing probes
making function not recursive and adding comments

Move most of Exported/Public res to rustc_resolve

moving public/export res to resolve

fix missing stability attributes in core, std and alloc

move code to access_levels.rs

return for some kinds instead of going through them

Export correctness, macro changes, comments

add comment for import binding

add comment for import binding

renmae to access level visitor, remove comments, move fn as closure, remove new_key

fmt

fix rebase

fix rebase

fmt

fmt

fix: move macro def to rustc_resolve

fix: reachable AccessLevel for enum variants

fmt

fix: missing stability attributes for other architectures

allow unreachable pub in rustfmt

fix: missing impl access level + renaming export to reexport

Missing impl access level was found thanks to a test in clippy
2022-01-09 21:33:14 +00:00
Lucas Kent
08829853d3 eplace usages of vec![].into_iter with [].into_iter 2022-01-09 14:09:25 +11:00
bors
23ce5fc465 Auto merge of #92068 - fee1-dead:libcore2021, r=m-ou-se
Switch all libraries to the 2021 edition

The fix for https://github.com/rust-lang/rust/issues/88638#issuecomment-996620107 is to simply add const-stability for these functions.

r? `@m-ou-se`

Closes #88638.
2022-01-08 21:41:48 +00:00
Badel2
8ef3ce866e Change panic::update_hook to simplify usage
And to remove possibility of panics while changing the panic handler,
because that resulted in a double panic.
2022-01-08 00:57:59 +01:00
Badel2
8bdf5c3de6 Implement panic::update_hook 2022-01-07 17:28:20 +01:00
Frank Steffahn
d5d752ab1e remove unused ExtendDefault struct 2022-01-06 18:49:55 +01:00
Alex Macleod
7ea03db04a Add diagnostic items for macros 2022-01-06 14:59:33 +00:00
Matthias Krüger
84e48a41d3
Rollup merge of #92388 - SpriteOvO:master, r=Mark-Simulacrum
Fix a minor mistake in `String::try_reserve_exact` examples

The examples of `String::try_reserve_exact` didn't actually use `try_reserve_exact`, which was probably a minor mistake, and this PR fixed it.
2022-01-05 15:05:45 +01:00
Matthias Krüger
56d11a446b
Rollup merge of #92092 - saethlin:fix-sort-guards-sb, r=danielhenrymantilla
Drop guards in slice sorting derive src pointers from &mut T, which is invalidated by interior mutation in comparison

I tried to run https://github.com/rust-lang/miri-test-libstd on `alloc` with `-Zmiri-track-raw-pointers`, and got a failure on the test `slice::panic_safe`. The test failure has nothing to do with panic safety, it's from how the test tests for panic safety.

I minimized the test failure into this very silly program:
```rust
use std::cell::Cell;
use std::cmp::Ordering;

#[derive(Clone)]
struct Evil(Cell<usize>);

fn main() {
    let mut input = vec![Evil(Cell::new(0)); 3];

    // Hits the bug pattern via CopyOnDrop in core
    input.sort_unstable_by(|a, _b| {
        a.0.set(0);
        Ordering::Less
    });

    // Hits the bug pattern via InsertionHole in alloc
    input.sort_by(|_a, b| {
        b.0.set(0);
        Ordering::Less
    });
}
```

To fix this, I'm just removing the mutability/uniqueness where it wasn't required.
2022-01-05 15:05:44 +01:00
Mario Carneiro
06b17a2181
Clarify that ordering is unspecified 2022-01-04 21:32:20 -08:00
Mario Carneiro
b9f008b1ee
Update wording 2022-01-04 12:18:54 -08:00
Matthias Krüger
c7125ba0fa
Rollup merge of #91884 - woppopo:const_box, r=oli-obk
Constify `Box<T, A>` methods

Tracking issue: none yet

Most of the methods bounded on `~const`. `intrinsics::const_eval_select` is used for handling an allocation error.

<details><summary>Constified API</summary>

```rust
impl<T, A: Allocator> Box<T, A> {
    pub const fn new_in(x: T, alloc: A) -> Self
    where
        A: ~const Allocator + ~const Drop;
    pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
    where
        T: ~const Drop,
        A: ~const Allocator + ~const Drop;
    pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
    where
        A: ~const Allocator + ~const Drop;
    pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
    where
        A: ~const Allocator + ~const Drop;
    pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
    where
        A: ~const Allocator + ~const Drop;
    pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
    where
        A: ~const Allocator + ~const Drop;
    pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
    where
        A: 'static,
        A: 'static + ~const Allocator + ~const Drop,
    pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A>;
    pub const fn into_inner(boxed: Self) -> T
    where
        Self: ~const Drop,
}

impl<T, A: Allocator> Box<MaybeUninit<T>, A> {
    pub const unsafe fn assume_init(self) -> Box<T, A>;
    pub const fn write(mut boxed: Self, value: T) -> Box<T, A>;
    pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self;
    pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A);
    pub const fn into_unique(b: Self) -> (Unique<T>, A);
    pub const fn allocator(b: &Self) -> &A;
    pub const fn leak<'a>(b: Self) -> &'a mut T
    where
        A: 'a;
    pub const fn into_pin(boxed: Self) -> Pin<Self>
    where
        A: 'static;
}

unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> const Drop for Box<T, A>;
impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
where
    A: 'static;
impl<T: ?Sized, A: Allocator> const Deref for Box<T, A>;
impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A>;
impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static;
```

</details>

<details><summary>Example</summary>

```rust
pub struct ConstAllocator;

unsafe impl const Allocator for ConstAllocator {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        unsafe {
            let ptr = core::intrinsics::const_allocate(layout.size(), layout.align());
            Ok(NonNull::new_unchecked(ptr as *mut [u8; 0] as *mut [u8]))
        }
    }

    unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {
        /* do nothing */
    }

    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.allocate(layout)
    }

    unsafe fn grow(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unimplemented!()
    }

    unsafe fn grow_zeroed(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unimplemented!()
    }

    unsafe fn shrink(
        &self,
        _ptr: NonNull<u8>,
        _old_layout: Layout,
        _new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        unimplemented!()
    }

    fn by_ref(&self) -> &Self
    where
        Self: Sized,
    {
        self
    }
}

#[test]
fn const_box() {
    const VALUE: u32 = {
        let mut boxed = Box::new_in(1u32, ConstAllocator);
        assert!(*boxed == 1);

        *boxed = 42;
        assert!(*boxed == 42);

        *boxed
    };

    assert!(VALUE == 42);
}
```

</details>
2022-01-04 16:34:14 +01:00
woppopo
51e4291f2b Fix a compile error when no_global_oom_handling 2022-01-04 01:37:53 +09:00
woppopo
c9d2d3cc66 Add tracking issues (const_box, const_alloc_error) 2022-01-04 00:35:53 +09:00
Matthias Krüger
aa31c9726d
Rollup merge of #92463 - thomcc:thats-not-how-its-pronounced, r=joshtriplett
Remove pronunciation guide from Vec<T>

I performed an extremely scientific poll on twitter, and determined this is not how it's pronounced: https://twitter.com/at_tcsc/status/1476643344285581315
2022-01-01 22:49:52 +01:00
Matthias Krüger
a6e4d684aa
Rollup merge of #92097 - saethlin:split-without-deref, r=the8472
Implement split_at_spare_mut without Deref to a slice so that the spare slice is valid

~I'm not sure I understand what's going on here correctly. And I'm pretty sure this safety comment needs to be changed. I'm just referring to the same thing that `as_mut_ptr_range` does.~ (Thanks `@RalfJung` for the guidance and clearing things up)

I tried to run https://github.com/rust-lang/miri-test-libstd on alloc with -Zmiri-track-raw-pointers, and got a failure on the test `vec::test_extend_from_within`.

I minimized the test failure into this program:
```rust
#![feature(vec_split_at_spare)]
fn main() {
    Vec::<i32>::with_capacity(1).split_at_spare_mut();
}
```

The problem is that the existing implementation is actually getting a pointer range where both pointers are derived from the initialized region of the Vec's allocation, but we need the second one to be valid for the region between len and capacity. (thanks Ralf for clearing this up)
2022-01-01 10:48:54 +01:00
Ben Kimock
777c853b4a Clarify safety comment 2021-12-31 18:03:07 -05:00
Thom Chiovoloni
51a1681b69 Remove pronunciation guide from Vec<T> 2021-12-31 16:04:13 -05:00
bdbai
ce31cbc7a3 use generic params for arc_new_cyclic 2021-12-30 21:55:18 +08:00
Veeupup
249eb1c589 fix typo in btree/vec doc: Self -> self 2021-12-29 18:01:17 +08:00
Sprite
a877b64717 Fix a minor mistake in String::try_reserve_exact examples 2021-12-29 13:22:35 +08:00
Shadlock0133
584e88d41d
Remove maybe_uninit_extra feature from Vec docs
In `Vec`, two doc tests are using `MaybeUninit::write` , stabilized in 1.55. This makes docs' usage of `maybe_uninit_extra` feature unnecessary.
2021-12-24 23:04:10 +01:00
bors
e6f1f04e52 Auto merge of #92220 - nnethercote:RawVec-dont-recompute-capacity, r=joshtriplett
RawVec: don't recompute capacity after allocating.

Currently it sets the capacity to `ptr.len() / mem::size_of::<T>()`
after any buffer allocation/reallocation. This would be useful if
allocators ever returned a `NonNull<[u8]>` with a size larger than
requested. But this never happens, so it's not useful.

Removing this slightly reduces the size of generated LLVM IR, and
slightly speeds up the hot path of `RawVec` growth.

r? `@ghost`
2021-12-24 01:54:56 +00:00
Deadbeef
3ae0dabddb
Bless a few tests 2021-12-23 21:26:05 +08:00