Commit Graph

1543 Commits

Author SHA1 Message Date
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
David Tolnay
2ac9efbe95
Debug print char 0 as '\0' rather than '\u{0}' 2022-03-27 04:49:10 -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
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
The 8472
7549cfa599 rename internal helper trait AsIntoIter to AsVecIntoIter 2022-03-22 00:02:54 +01: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
Dylan DPC
13e889986d fix typos 2022-03-15 02:00:08 +01: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
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