Commit Graph

1969 Commits

Author SHA1 Message Date
Sky
3e23d60a32
Add tracking issue for string_extend_from_within 2022-10-31 12:01:20 -04:00
Ralf Jung
99a74afa5f ptr::eq: clarify that comparing dyn Trait is fragile 2022-10-26 11:15:14 +02:00
Nixon Enraght-Moony
674cd6125d Clairify Vec::capacity docs
Fixes #103326
2022-10-24 15:01:58 +01:00
Yuki Okushi
fbb3650c89
Rollup merge of #99578 - steffahn:remove_redundant_bound, r=thomcc
Remove redundant lifetime bound from `impl Borrow for Cow`

The lifetime bound `B::Owned: 'a` is redundant and doesn't make a difference,
because `Cow<'a, B>` comes with an implicit `B: 'a`, and associated types
will outlive lifetimes outlived by the `Self` type (and all the trait's
generic parameters, of which there are none in this case), so the implicit `B: 'a`
implies `B::Owned: 'a` anyway.

The explicit lifetime bound here does however [end up in documentation](https://doc.rust-lang.org/std/borrow/enum.Cow.html#impl-Borrow%3CB%3E),
and that's confusing in my opinion, so let's remove it ^^

_(Documentation right now, compare to `AsRef`, too:)_
![Screenshot_20220722_014055](https://user-images.githubusercontent.com/3986214/180332665-424d0c05-afb3-40d8-a330-a57a2c9a494b.png)
2022-10-24 19:32:24 +09:00
Finn Bear
9f0503e4a6 Fix typo in docs of String::leak. 2022-10-22 12:26:47 -07:00
Dylan DPC
b22559f547
Rollup merge of #103346 - HeroicKatora:metadata_of_const_pointer_argument, r=dtolnay
Adjust argument type for mutable with_metadata_of (#75091)

The method takes two pointer arguments: one `self` supplying the pointer value, and a second pointer supplying the metadata.

The new parameter type more clearly reflects the actual requirements. The provenance of the metadata parameter is disregarded completely. Using a mutable pointer in the call site can be coerced to a const pointer while the reverse is not true.

In some cases, the current parameter type can thus lead to a very slightly confusing additional cast. [Example](cad93775eb).

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = val as *const _ as *mut T;
let ptr = uninit.as_ptr().with_metadata_of(ptr);
```

This could then instead be simplified to:

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = uninit.as_ptr().with_metadata_of(&**val);
```

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

``@dtolnay`` you're reviewed #95249, would you mind chiming in?
2022-10-22 16:28:09 +05:30
Dylan DPC
141478b40f
Rollup merge of #103280 - finnbear:impl_string_leak_2, r=joshtriplett
(#102929) Implement `String::leak` (attempt 2)

Implementation of `String::leak` (#102929)

ACP: https://github.com/rust-lang/libs-team/issues/109

Supersedes #102941 (see previous reviews there)

```@rustbot``` label +T-libs-api -T-libs
2022-10-22 16:28:08 +05:30
Matthias Krüger
1b2f594f48
Rollup merge of #103359 - WaffleLapkin:drain_no_mut_qqq, r=scottmcm
Remove incorrect comment in `Vec::drain`

r? ``@scottmcm``

Turns out this comment wasn't correct for 6 years, since #34951, which switched from using `slice::IterMut` into using `slice::Iter`.
2022-10-22 00:14:03 +02:00
Maybe Waffle
e97d295d00 Remove incorrect comment in Vec::drain 2022-10-21 15:29:02 +00:00
Andreas Molzer
e3606b2b02 Reduce mutability in std-use of with_metadata_of 2022-10-21 14:49:29 +02:00
Finn Bear
4f44d6253d Put fn in the right place. 2022-10-19 19:15:58 -07:00
Finn Bear
f81cd87eea Copy of #102941. 2022-10-19 19:07:45 -07:00
Dylan DPC
d056ea8828
Rollup merge of #103153 - ChrisDenton:leak-oom, r=m-ou-se
Allow `Vec::leak` when using `no_global_oom_handling`

As [the documentation notes](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.leak), `Vec::leak` hasn't allocated since 1.57.

cc `@Ericson2314` in case I'm missing something.
2022-10-19 14:05:53 +05:30
Yuki Okushi
b411b8861c
Rollup merge of #103163 - SUPERCILEX:uninit-array-assume2, r=scottmcm
Remove all uses of array_assume_init

See https://github.com/rust-lang/rust/pull/103134#discussion_r997462733

r? `@scottmcm`
2022-10-18 21:21:32 +09:00
Alex Saveau
55d71c61b8
Remove all uses of array_assume_init
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17 13:03:54 -07:00
bors
06f049a355 Auto merge of #101837 - scottmcm:box-array-from-vec, r=m-ou-se
Add `Box<[T; N]>: TryFrom<Vec<T>>`

We have `[T; N]: TryFrom<Vec<T>>` (#76310) and `Box<[T; N]>: TryFrom<Box<[T]>>`, but not this combination.

`vec.into_boxed_slice().try_into()` isn't quite a replacement for this, as that'll reallocate unnecessarily in the error case.

**Insta-stable, so needs an FCP**

(I tried to make this work with `, A`, but that's disallowed because of `#[fundamental]` https://github.com/rust-lang/rust/issues/29635#issuecomment-1247598385)
2022-10-17 19:46:04 +00:00
Chris Denton
913393a0f7
Allow Vec::leak with no_global_oom_handling 2022-10-17 17:12:32 +01:00
philipp
4854e37dbc Documentation BTreeMap::append's behavior for already existing keys 2022-10-15 17:47:07 +02:00
bors
ee1c3b385b Auto merge of #102529 - colinba:master, r=joshtriplett
Detect and reject out-of-range integers in format string literals

Until now out-of-range integers in format string literals were silently ignored. They wrapped around to zero at usize::MAX, producing unexpected results.

When using debug builds of rustc, such integers in format string literals even cause an 'attempt to add with overflow' panic in rustc.

Fix this by producing an error diagnostic for integers in format string literals which do not fit into usize.

Fixes #102528
2022-10-14 13:41:40 +00:00
Rageking8
7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
Ralf Jung
2b50cd1877 rename rustc_allocator_nounwind to rustc_nounwind 2022-10-11 22:47:31 +02:00
Matthias Krüger
cadb37a8c7
Rollup merge of #101727 - est31:stabilize_map_first_last, r=m-ou-se
Stabilize map_first_last

Stabilizes the following functions:

```Rust
impl<T> BTreeSet<T> {
    pub fn first(&self) -> Option<&T> where T: Ord;
    pub fn last(&self) -> Option<&T> where T: Ord;
    pub fn pop_first(&mut self) -> Option<T> where T: Ord;
    pub fn pop_last(&mut self) -> Option<T> where T: Ord;
}

impl<K, V> BTreeMap<K, V> {
    pub fn first_key_value(&self) -> Option<(&K, &V)> where K: Ord;
    pub fn last_key_value(&self) -> Option<(&K, &V)> where K: Ord;
    pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
    pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V>> where K: Ord;
    pub fn pop_first(&mut self) -> Option<(K, V)> where K: Ord;
    pub fn pop_last(&mut self) -> Option<(K, V)> where K: Ord;
}
```

Closes #62924

~~Blocked on the [FCP](https://github.com/rust-lang/rust/issues/62924#issuecomment-1179489929) finishing.~~ Edit: It finished!
2022-10-11 18:59:46 +02:00
bors
a6b7274a46 Auto merge of #102596 - scottmcm:option-bool-calloc, r=Mark-Simulacrum
Do the `calloc` optimization for `Option<bool>`

Inspired by <https://old.reddit.com/r/rust/comments/xtiqj8/why_is_this_functional_version_faster_than_my_for/iqqy37b/>.
2022-10-10 18:42:40 +00:00
bors
1a7c203e7f Auto merge of #89123 - the8472:push_in_capacity, r=amanieu
add Vec::push_within_capacity - fallible, does not allocate

This method can serve several purposes. It

* is fallible
* guarantees that items in Vec aren't moved
* allows loops that do `reserve` and `push` separately to avoid pulling in the allocation machinery a second time in the `push` part which should make things easier on the optimizer
* eases the path towards `ArrayVec` a bit since - compared to `push()` - there are fewer questions around how it should be implemented

I haven't named it `try_push` because that should probably occupy a middle ground that will still try to reserve and only return an error in the unlikely OOM case.

resolves #84649
2022-10-09 21:02:33 +00:00
David Tolnay
4fdd0d9675
Fix overconstrained Send impls in btree internals 2022-10-05 12:16:32 -07:00
David Tolnay
fa863414fe
Add regression test for lifetimes in alloc internals autotraits
Currently pretty much all of the btree_map and btree_set ones fail, as
well as linked_list::DrainFilter.

    error: higher-ranked lifetime error
      --> library/alloc/tests/autotraits.rs:38:5
       |
    38 | /     require_send_sync(async {
    39 | |         let _v = None::<alloc::collections::btree_map::Iter<'_, &u32, &u32>>;
    40 | |         async {}.await;
    41 | |     });
       | |______^
       |
       = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:56:5
       |
    56 | /     require_send_sync(async {
    57 | |         let _v = None::<
    58 | |             alloc::collections::btree_map::DrainFilter<
    59 | |                 '_,
    ...  |
    65 | |         async {}.await;
    66 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:68:5
       |
    68 | /     require_send_sync(async {
    69 | |         let _v = None::<alloc::collections::btree_map::Entry<'_, &u32, &u32>>;
    70 | |         async {}.await;
    71 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
      --> library/alloc/tests/autotraits.rs:88:5
       |
    88 | /     require_send_sync(async {
    89 | |         let _v = None::<alloc::collections::btree_map::Iter<'_, &u32, &u32>>;
    90 | |         async {}.await;
    91 | |     });
       | |______^
       |
       = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
      --> library/alloc/tests/autotraits.rs:93:5
       |
    93 | /     require_send_sync(async {
    94 | |         let _v = None::<alloc::collections::btree_map::IterMut<'_, &u32, &u32>>;
    95 | |         async {}.await;
    96 | |     });
       | |______^ implementation of `Send` is not general enough
       |
       = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
       = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:98:5
        |
    98  | /     require_send_sync(async {
    99  | |         let _v = None::<alloc::collections::btree_map::Keys<'_, &u32, &u32>>;
    100 | |         async {}.await;
    101 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:103:5
        |
    103 | /     require_send_sync(async {
    104 | |         let _v = None::<alloc::collections::btree_map::OccupiedEntry<'_, &u32, &u32>>;
    105 | |         async {}.await;
    106 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:108:5
        |
    108 | /     require_send_sync(async {
    109 | |         let _v = None::<alloc::collections::btree_map::OccupiedError<'_, &u32, &u32>>;
    110 | |         async {}.await;
    111 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:113:5
        |
    113 | /     require_send_sync(async {
    114 | |         let _v = None::<alloc::collections::btree_map::Range<'_, &u32, &u32>>;
    115 | |         async {}.await;
    116 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:118:5
        |
    118 | /     require_send_sync(async {
    119 | |         let _v = None::<alloc::collections::btree_map::RangeMut<'_, &u32, &u32>>;
    120 | |         async {}.await;
    121 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:123:5
        |
    123 | /     require_send_sync(async {
    124 | |         let _v = None::<alloc::collections::btree_map::VacantEntry<'_, &u32, &u32>>;
    125 | |         async {}.await;
    126 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:128:5
        |
    128 | /     require_send_sync(async {
    129 | |         let _v = None::<alloc::collections::btree_map::Values<'_, &u32, &u32>>;
    130 | |         async {}.await;
    131 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:133:5
        |
    133 | /     require_send_sync(async {
    134 | |         let _v = None::<alloc::collections::btree_map::ValuesMut<'_, &u32, &u32>>;
    135 | |         async {}.await;
    136 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:146:5
        |
    146 | /     require_send_sync(async {
    147 | |         let _v = None::<alloc::collections::btree_set::Difference<'_, &u32>>;
    148 | |         async {}.await;
    149 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: implementation of `Send` is not general enough
       --> library/alloc/tests/autotraits.rs:151:5
        |
    151 | /     require_send_sync(async {
    152 | |         let _v = None::<alloc::collections::btree_set::DrainFilter<'_, &u32, fn(&&u32) -> bool>>;
    153 | |         async {}.await;
    154 | |     });
        | |______^ implementation of `Send` is not general enough
        |
        = note: `Send` would have to be implemented for the type `&'0 u32`, for any lifetime `'0`...
        = note: ...but `Send` is actually implemented for the type `&'1 u32`, for some specific lifetime `'1`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:156:5
        |
    156 | /     require_send_sync(async {
    157 | |         let _v = None::<alloc::collections::btree_set::Intersection<'_, &u32>>;
    158 | |         async {}.await;
    159 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:166:5
        |
    166 | /     require_send_sync(async {
    167 | |         let _v = None::<alloc::collections::btree_set::Iter<'_, &u32>>;
    168 | |         async {}.await;
    169 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:171:5
        |
    171 | /     require_send_sync(async {
    172 | |         let _v = None::<alloc::collections::btree_set::Range<'_, &u32>>;
    173 | |         async {}.await;
    174 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:176:5
        |
    176 | /     require_send_sync(async {
    177 | |         let _v = None::<alloc::collections::btree_set::SymmetricDifference<'_, &u32>>;
    178 | |         async {}.await;
    179 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: higher-ranked lifetime error
       --> library/alloc/tests/autotraits.rs:181:5
        |
    181 | /     require_send_sync(async {
    182 | |         let _v = None::<alloc::collections::btree_set::Union<'_, &u32>>;
    183 | |         async {}.await;
    184 | |     });
        | |______^
        |
        = note: could not prove `impl Future<Output = ()>: Send`

    error: future cannot be sent between threads safely
       --> library/alloc/tests/autotraits.rs:243:23
        |
    243 |       require_send_sync(async {
        |  _______________________^
    244 | |         let _v =
    245 | |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 | |         async {}.await;
    247 | |     });
        | |_____^ future created by async block is not `Send`
        |
        = help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `NonNull<std::collections::linked_list::Node<&u32>>`
    note: future is not `Send` as this value is used across an await
       --> library/alloc/tests/autotraits.rs:246:17
        |
    244 |         let _v =
        |             -- has type `Option<std::collections::linked_list::DrainFilter<'_, &u32, for<'a, 'b> fn(&'a mut &'b u32) -> bool>>` which is not `Send`
    245 |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 |         async {}.await;
        |                 ^^^^^^ await occurs here, with `_v` maybe used later
    247 |     });
        |     - `_v` is later dropped here
    note: required by a bound in `require_send_sync`
       --> library/alloc/tests/autotraits.rs:3:25
        |
    3   | fn require_send_sync<T: Send + Sync>(_: T) {}
        |                         ^^^^ required by this bound in `require_send_sync`

    error: future cannot be shared between threads safely
       --> library/alloc/tests/autotraits.rs:243:23
        |
    243 |       require_send_sync(async {
        |  _______________________^
    244 | |         let _v =
    245 | |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 | |         async {}.await;
    247 | |     });
        | |_____^ future created by async block is not `Sync`
        |
        = help: within `impl Future<Output = ()>`, the trait `Sync` is not implemented for `NonNull<std::collections::linked_list::Node<&u32>>`
    note: future is not `Sync` as this value is used across an await
       --> library/alloc/tests/autotraits.rs:246:17
        |
    244 |         let _v =
        |             -- has type `Option<std::collections::linked_list::DrainFilter<'_, &u32, for<'a, 'b> fn(&'a mut &'b u32) -> bool>>` which is not `Sync`
    245 |             None::<alloc::collections::linked_list::DrainFilter<'_, &u32, fn(&mut &u32) -> bool>>;
    246 |         async {}.await;
        |                 ^^^^^^ await occurs here, with `_v` maybe used later
    247 |     });
        |     - `_v` is later dropped here
    note: required by a bound in `require_send_sync`
       --> library/alloc/tests/autotraits.rs:3:32
        |
    3   | fn require_send_sync<T: Send + Sync>(_: T) {}
        |                                ^^^^ required by this bound in `require_send_sync`
2022-10-05 12:15:17 -07:00
Dylan DPC
f24d00d8b3
Rollup merge of #101642 - SkiFire13:fix-inplace-collection-leak, r=the8472
Fix in-place collection leak when remaining element destructor panic

Fixes #101628

cc `@the8472`

I went for the drop guard route, placing it immediately before the `forget_allocation_drop_remaining` call and after the comment, as to signal they are closely related.

I also updated the test to check for the leak, though the only change really needed was removing the leak clean up for miri since now that's no longer leaked.
2022-10-04 16:11:01 +05:30
Matthias Krüger
2110d2de5a
Rollup merge of #99216 - duarten:master, r=joshtriplett
docs: be less harsh in wording for Vec::from_raw_parts

In particular, be clear that it is sound to specify memory not
originating from a previous `Vec` allocation. That is already suggested
in other parts of the documentation about zero-alloc conversions to Box<[T]>.

Incorporate a constraint from `slice::from_raw_parts` that was missing
but needs to be fulfilled, since a `Vec` can be converted into a slice.

Fixes https://github.com/rust-lang/rust/issues/98780.
2022-10-03 20:58:53 +02:00
Matthias Krüger
098e8b7357
Rollup merge of #98218 - kpreid:nostdarc, r=joshtriplett
Document the conditional existence of `alloc::sync` and `alloc::task`.

`alloc` declares

```rust
#[cfg(target_has_atomic = "ptr")]
pub mod sync;
```

but there is no public documentation of this condition. This PR fixes that, so that users of `alloc` can understand how to make their code compile everywhere `alloc` does, if they are writing a library with impls for `Arc`.

The wording is copied from `std::sync::atomic::AtomicPtr`, with additional advice on how to `#[cfg]` for it.

I feel quite uncertain about whether the paragraph I added to `Arc`'s documentation should actually be there, as it is a distraction for anyone using `std`. On the other hand, maybe more reminders that no_std exists would benefit the ecosystem.

Note: `target_has_atomic` is [stabilized](https://github.com/rust-lang/rust/issues/32976) but [not yet documented in the reference](https://github.com/rust-lang/reference/pull/1171).
2022-10-03 20:58:53 +02:00
Giacomo Stevanato
1750c7bdd3 Clarify documentation 2022-10-03 20:23:54 +02:00
Scott McMurray
31cd0aa823 Do the calloc optimization for Option<bool>
Inspired by <https://old.reddit.com/r/rust/comments/xtiqj8/why_is_this_functional_version_faster_than_my_for/iqqy37b/>.
2022-10-02 12:26:58 -07:00
Dylan DPC
890a327c86
Rollup merge of #102556 - WaffleLapkin:implied_by_btree_new, r=Mark-Simulacrum
Make `feature(const_btree_len)` implied by `feature(const_btree_new)`

...this should fix code that used the old feature that was changed in #102197

cc ```@davidtwco``` it seems like tidy doesn't check `implied_by`, should it?
2022-10-02 20:42:22 +05:30
Dylan DPC
ed9740846b
Rollup merge of #102098 - xfix:weak-upgrade-fetch-update, r=Mark-Simulacrum
Use fetch_update in sync::Weak::upgrade

Using `fetch_update` makes it more clear that it's CAS loop then manually implementing one.
2022-10-02 20:42:21 +05:30
Maybe Waffle
da78c1fd43 Make feature(const_btree_len) implied by feature(const_btree_new) 2022-10-01 22:40:04 +00:00
Colin Baumgarten
b9e85bf60a Detect and reject out-of-range integers in format string literals
Until now out-of-range integers in format string literals
were silently ignored. They wrapped around to zero at
usize::MAX, producing unexpected results.

When using debug builds of rustc, such integers in format string
literals even cause an 'attempt to add with overflow' panic in
rustc.

Fix this by producing an error diagnostic for integers in format
string literals which do not fit into usize.

Fixes #102528
2022-10-01 01:05:01 +02:00
est31
2c72ea7748 Stabilize map_first_last 2022-09-30 17:00:07 +02:00
Yuki Okushi
07bb2e6527
Rollup merge of #102232 - Urgau:stabilize-bench_black_box, r=TaKO8Ki
Stabilize bench_black_box

This PR stabilize `feature(bench_black_box)`.

```rust
pub fn black_box<T>(dummy: T) -> T;
```

The FCP was completed in https://github.com/rust-lang/rust/issues/64102.

`@rustbot` label +T-libs-api -T-libs
2022-09-28 13:07:17 +09:00
Urgau
9ad2f00f6a Stabilize bench_black_box 2022-09-27 17:38:51 +02:00
Pietro Albini
3975d55d98
remove cfg(bootstrap) 2022-09-26 10:14:45 +02:00
fee1-dead
804c2c1ed9
Rollup merge of #102197 - Nilstrieb:const-new-🌲, r=Mark-Simulacrum
Stabilize const `BTree{Map,Set}::new`

The FCP was completed in #71835.

Since `len` and `is_empty` are not const stable yet, this also creates a new feature for them since they previously used the same `const_btree_new` feature.
2022-09-26 13:09:42 +08:00
bors
e58621a4a3 Auto merge of #102169 - scottmcm:constify-some-conditions, r=thomcc
Make ZST checks in core/alloc more readable

There's a bunch of these checks because of special handing for ZSTs in various unsafe implementations of stuff.

This lets them be `T::IS_ZST` instead of `mem::size_of::<T>() == 0` every time, making them both more readable and more terse.

*Not* proposed for stabilization.  Would be `pub(crate)` except `alloc` wants to use it too.

(And while it doesn't matter now, if we ever get something like #85836 making it a const can help codegen be simpler.)
2022-09-25 01:20:11 +00:00
Scott McMurray
f0dc35927b Put back one of the uses for intra-doc mentions 2022-09-23 21:47:23 -07:00
Nilstrieb
aa35ab81ea Stabilize const BTree{Map,Set}::new
Since `len` and `is_empty` are not const stable yet, this also
creates a new feature for them since they previously used the same
`const_btree_new` feature.
2022-09-23 20:55:37 +02:00
Scott McMurray
44b4ce1d61 Make ZST checks in core/alloc more readable
There's a bunch of these checks because of special handing for ZSTs in various unsafe implementations of stuff.

This lets them be `T::IS_ZST` instead of `mem::size_of::<T>() == 0` every time, making them both more readable and more terse.

*Not* proposed for stabilization at this time.  Would be `pub(crate)` except `alloc` wants to use it too.

(And while it doesn't matter now, if we ever get something like 85836 making it a const can help codegen be simpler.)
2022-09-22 23:12:29 -07:00
bors
7a8636c843 Auto merge of #100982 - fee1-dead-contrib:const-impl-requires-const-trait, r=oli-obk
Require `#[const_trait]` on `Trait` for `impl const Trait`

r? `@oli-obk`
2022-09-22 04:22:24 +00:00
Konrad Borowski
80c8680a0c Use fetch_update in sync::Weak::upgrade 2022-09-21 14:06:20 +00:00
Dylan DPC
5377c31122
Rollup merge of #89891 - ojeda:modular-alloc, r=Mark-Simulacrum
`alloc`: add unstable cfg features `no_rc` and `no_sync`

In Rust for Linux we are using these to make `alloc` a bit more modular.

See https://github.com/rust-lang/rust/pull/86048 and https://github.com/rust-lang/rust/pull/84266 for similar requests.

Of course, the particular names are not important.
2022-09-21 19:01:06 +05:30
Matthias Krüger
ea076a4f9f
Rollup merge of #101798 - y86-dev:const_waker, r=lcnr
Make `from_waker`, `waker` and `from_raw` unstably `const`

Make
- `Context::from_waker`
- `Context::waker`
- `Waker::from_raw`

`const`.

Also added a small test.
2022-09-19 17:55:19 +02:00
bors
4c2e500788 Auto merge of #101816 - raldone01:cleanup/select_nth_unstable, r=Mark-Simulacrum
Cleanup slice sort related closures in core and alloc
2022-09-18 06:03:22 +00:00
Scott McMurray
4d3a31caf0 Add Box<[T; N]>: TryFrom<Vec<T>>
We have `[T; N]: TryFrom<Vec<T>>` and `Box<[T; N]>: TryFrom<Box<[T]>>`, but not the combination.

`vec.into_boxed_slice().try_into()` isn't quite a replacement for this, as that'll reallocate unnecessarily in the error case.

**Insta-stable, so needs an FCP**
2022-09-17 14:15:37 -07:00
Dylan DPC
80cceb8f77
Rollup merge of #101931 - msakuta:master, r=thomcc
doc: Fix a typo in `Rc::make_mut` docstring

A very minor typo fix.
2022-09-17 15:31:09 +05:30
msakuta
673c43b6e1 Fix a typo in docstring 2022-09-17 13:58:53 +09:00
Deadbeef
5a6273e263 Do not implement Unpin as const 2022-09-16 11:48:42 +08:00
est31
173eb6f407 Only enable the let_else feature on bootstrap
On later stages, the feature is already stable.

Result of running:

rg -l "feature.let_else" compiler/ src/librustdoc/ library/ | xargs sed -s -i "s#\\[feature.let_else#\\[cfg_attr\\(bootstrap, feature\\(let_else\\)#"
2022-09-15 21:06:45 +02:00
raldone01
59fe291cec Cleanup closures. 2022-09-14 20:11:45 +02:00
y86-dev
9a78faba71 Made from_waker, waker, from_raw const 2022-09-14 14:53:16 +02:00
Ben Kimock
54684c438f Alternate approach; just modify Drain 2022-09-10 17:52:34 -04:00
Ben Kimock
25f4cb59d3 Remove &[T] from vec_deque::Drain 2022-09-10 17:52:34 -04:00
Stefan Schindler
f613bd6d3a Make the one-liner more descriptive 2022-09-10 16:24:05 +02:00
Giacomo Stevanato
dad049cb5c Update test 2022-09-10 13:13:54 +02:00
Giacomo Stevanato
f52082f543 Update documentation 2022-09-10 13:13:54 +02:00
Giacomo Stevanato
f81b07e947 Adapt inplace collection leak test to check for no leaks 2022-09-10 11:34:23 +02:00
Giacomo Stevanato
fa61678a7d Fix leaking in inplace collection when destructor panics 2022-09-10 11:34:22 +02:00
bors
289279de11 Auto merge of #93455 - asquared31415:vec-zero-opts, r=thomcc
Implement internal `IsZero` for Wrapping and Saturating for `Vec` optimizations

This implements the `IsZero` trait for the `Wrapping` and `Saturating` types so that users of these types can get the improved performance from the specialization of creating a `Vec` from a single element repeated when it has a zero bit pattern (example `vec![0_i32; 500]`, or after this PR `vec![Wrapping(0_i32); 500]`)

CC #60978
2022-09-04 20:33:50 +00:00
asquared31415
80e035c9e4 implement IsZero for Saturating and Wrapping 2022-09-02 19:55:01 -04:00
Chris Denton
3fee843ebb
Fix internal doc link
The doc link from `DedupSortedIter` to `BTreeMap::bulk_build_from_sorted_iter` was broken when building internal documentation,
2022-09-02 13:32:16 +01:00
bors
b32223fec1 Auto merge of #100707 - dzvon:fix-typo, r=davidtwco
Fix a bunch of typo

This PR will fix some typos detected by [typos].

I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.

[typos]: https://github.com/crate-ci/typos
2022-09-01 05:39:58 +00:00
Ralf Jung
fe29ac9a44 fix into_iter on ZST 2022-08-31 14:21:35 +02:00
Dezhi Wu
b1430fb7ca Fix a bunch of typo
This PR will fix some typos detected by [typos].

I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.

[typos]: https://github.com/crate-ci/typos
2022-08-31 18:24:55 +08:00
Dylan DPC
c731157395
Rollup merge of #95376 - WaffleLapkin:drain_keep_rest, r=dtolnay
Add `vec::Drain{,Filter}::keep_rest`

This PR adds `keep_rest` methods to `vec::Drain` and `vec::DrainFilter` under `drain_keep_rest` feature gate:
```rust
// mod alloc::vec

impl<T, A: Allocator> Drain<'_, T, A> {
    pub fn keep_rest(self);
}

impl<T, F, A: Allocator> DrainFilter<'_, T, F, A>
where
    F: FnMut(&mut T) -> bool,
{
    pub fn keep_rest(self);
}
```

Both these methods cancel draining of elements that were not yet yielded from the iterators. While this needs more testing & documentation, I want at least start the discussion. This may be a potential way out of the "should `DrainFilter` exhaust itself on drop?" argument.
2022-08-30 11:26:47 +05:30
Dylan DPC
395ce34a95
Rollup merge of #100819 - WaffleLapkin:use_ptr_byte_methods, r=scottmcm
Make use of `[wrapping_]byte_{add,sub}`

These new methods trivially replace old `.cast().wrapping_offset().cast()` & similar code.
Note that [`arith_offset`](https://doc.rust-lang.org/std/intrinsics/fn.arith_offset.html) and `wrapping_offset` are the same thing.

r? ``@scottmcm``

_split off from #100746_
2022-08-29 16:49:43 +05:30
Maybe Waffle
7a433e4d00 fill-in tracking issue for feature(drain_keep_rest) 2022-08-28 17:02:37 +04:00
Maybe Waffle
8c4e0d42b2 add examples to vec::Drain{,Filter}::keep_rest docs 2022-08-28 16:58:06 +04:00
Matthias Krüger
65820098b9
Rollup merge of #99570 - XrXr:box-from-slice-docs, r=thomcc
Box::from(slice): Clarify that contents are copied

A colleague mentioned that they interpreted the old text
as saying that only the pointer and the length are copied.
Add a clause so it is more clear that the pointed to contents
are also copied.
2022-08-28 09:35:13 +02:00
Miguel Ojeda
614c2e404a alloc: add unstable cfg features no_rc and no_sync
In Rust for Linux we are using these to make `alloc` a bit
more modular.

A `run-make-fulldeps` test is added for each of them, so that
enabling each of them independently is kept in a compilable state.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-08-26 16:44:32 +02:00
Guillaume Gomez
e3148dc7c4
Rollup merge of #95005 - ssomers:btree_static_assert, r=thomcc
BTree: evaluate static type-related check at compile time

`assert`s like the ones replaced here would only go off when you run the right test cases, if the code were ever incorrectly changed such that rhey would trigger. But [inspired on a nice forum question](https://users.rust-lang.org/t/compile-time-const-generic-parameter-check/69202), they can be checked at compile time.
2022-08-26 14:08:43 +02:00
Matthias Krüger
e802df9e8b
Rollup merge of #100855 - IsaacCloos:master, r=joshtriplett
Extra documentation for new formatting feature

Documentation of this feature was added in #90473 and released in Rust 1.58. However, high traffic macros did not receive new examples. Namely `println!()` and `format!()`.

The doc comments included in Rust are super important to the community- especially newcomers. I have met several other newbies like myself who are unaware of this recent (well about 7 months old now) update to the language allowing for convenient intra-string identifiers.

Bringing small examples of this feature to the doc comments of `println!()` and `format!()` would be helpful to everyone learning the language.

[Blog Post Announcing Feature](https://blog.rust-lang.org/2022/01/13/Rust-1.58.0.html)
[Feature PR](https://github.com/rust-lang/rust/pull/90473) - includes several instances of documentation of the feature- minus the macros in question for this PR

*This is my first time contributing to a project this large. Feedback would mean the world to me 😄*

---

*Recreated; I violated the [No-Merge Policy](https://rustc-dev-guide.rust-lang.org/git.html#no-merge-policy)*
2022-08-24 18:20:10 +02:00
bors
060e47f74a Auto merge of #99917 - yaahc:error-in-core-move, r=thomcc
Move Error trait into core

This PR moves the error trait from the standard library into a new unstable `error` module within the core library. The goal of this PR is to help unify error reporting across the std and no_std ecosystems, as well as open the door to integrating the error trait into the panic reporting system when reporting panics whose source is an errors (such as via `expect`).

This PR is a rewrite of https://github.com/rust-lang/rust/pull/90328 using new compiler features that have been added to support error in core.
2022-08-23 19:48:55 +00:00
Maybe Waffle
53565b23ac Make use of [wrapping_]byte_{add,sub}
...replacing `.cast().wrapping_offset().cast()` & similar code.
2022-08-23 19:32:37 +04:00
Jane Losare-Lusby
bf7611d55e Move error trait into core 2022-08-22 13:28:25 -07:00
Dylan DPC
4ed8fa4759
Rollup merge of #100872 - JanBeh:PR_vec_default_alloc_doc, r=fee1-dead
Add guarantee that Vec::default() does not alloc

Currently `Vec::new()` is guaranteed to not allocate until elements are pushed onto the `Vec`, but such a guarantee is missing for `Vec`'s implementation of `Default::default`.

This adds such a guarantee for `Vec::default()` to the API reference.

See also [this discussion on URLO](https://users.rust-lang.org/t/guarantee-that-vec-default-does-not-allocate/79903).
2022-08-22 20:34:16 +05:30
Dylan DPC
58d23737a6
Rollup merge of #100820 - WaffleLapkin:use_ptr_is_aligned_methods, r=scottmcm
Use pointer `is_aligned*` methods

This PR replaces some manual alignment checks with calls to `pointer::{is_aligned, is_aligned_to}` and removes a useless pointer cast.

r? `@scottmcm`

_split off from #100746_
2022-08-22 20:34:15 +05:30
Dylan DPC
382ba73062
Rollup merge of #100331 - lo48576:try-reserve-preserve-on-failure, r=thomcc
Guarantee `try_reserve` preserves the contents on error

Update doc comments to make the guarantee explicit. However, some
implementations does not have the statement though.

* `HashMap`, `HashSet`: require guarantees on hashbrown side.
* `PathBuf`: simply redirecting to `OsString`.

Fixes #99606.
2022-08-22 20:34:12 +05:30
Jan Behrens
0227b71865 Add guarantee that Vec::default() does not alloc
Currently `Vec::new()` is guaranteed to not allocate until elements are
pushed onto the `Vec`, but such a guarantee is missing for `Vec`'s
implementation of `Default::default`. This adds such a guarantee for
`Vec::default()` to the API reference.
2022-08-22 12:36:44 +02:00
Dylan DPC
33b5ce6433
Rollup merge of #99386 - AngelicosPhosphoros:add_retain_test_maybeuninit, r=JohnTitor
Add tests that check `Vec::retain` predicate execution order.

This behaviour is documented for `Vec::retain` which means that there is code that rely on that but there weren't tests about that.
2022-08-22 11:45:41 +05:30
Dylan DPC
a4950ef7eb
Rollup merge of #93162 - camsteffen:std-prim-docs, r=Mark-Simulacrum
Std module docs improvements

My primary goal is to create a cleaner separation between primitive types and primitive type helper modules (fixes #92777). I also changed a few header lines in other top-level std modules (seen at https://doc.rust-lang.org/std/) for consistency.

Some conventions used/established:

 * "The \`Box\<T>` type for heap allocation." - if a module mainly provides a single type, name it and summarize its purpose in the module header
 * "Utilities for the _ primitive type." - this wording is used for the header of helper modules
 * Documentation for primitive types themselves are removed from helper modules
 * provided-by-core functionality of primitive types is documented in the primitive type instead of the helper module (such as the "Iteration" section in the slice docs)

I wonder if some content in `std::ptr` should be in `pointer` but I did not address this.
2022-08-22 11:45:40 +05:30
Isaac Cloos
acca4b8f86 Extra documentation for new formatting feature
High traffic macros should detail this helpful addition.
2022-08-21 15:28:27 -04:00
Matthias Krüger
a45f69f27d
Rollup merge of #100822 - WaffleLapkin:no_offset_question_mark, r=scottmcm
Replace most uses of `pointer::offset` with `add` and `sub`

As PR title says, it replaces `pointer::offset` in compiler and standard library with `pointer::add` and `pointer::sub`. This generally makes code cleaner, easier to grasp and removes (or, well, hides) integer casts.

This is generally trivially correct, `.offset(-constant)` is just `.sub(constant)`, `.offset(usized as isize)` is just `.add(usized)`, etc. However in some cases we need to be careful with signs of things.

r? ````@scottmcm````

_split off from #100746_
2022-08-21 16:54:07 +02:00
Matthias Krüger
fd403f5d17
Rollup merge of #100821 - WaffleLapkin:ptr_add_docs, r=scottmcm
Make some docs nicer wrt pointer offsets

This PR replaces `pointer::offset` with `pointer::add` and similarly `.cast().wrapping_add().cast()` with `.wrapping_byte_add()` **in docs**.

r? ``````@scottmcm``````

_split off from #100746_
2022-08-21 16:54:06 +02:00
Maybe Waffle
efef211876 Make use of pointer::is_aligned[_to] 2022-08-21 15:46:03 +04:00
Maybe Waffle
3ba393465f Make some docs nicer wrt pointer offsets 2022-08-21 02:22:20 +04:00
Maybe Waffle
e4720e1cf2 Replace most uses of pointer::offset with add and sub 2022-08-21 02:21:41 +04:00
Cameron Steffen
17ddcb434b Improve primitive/std docs separation and headers 2022-08-20 16:50:29 -05:00
Maybe Waffle
ed084ba292 Remove useless pointer cast 2022-08-21 01:32:40 +04:00
bors
878aef79dc Auto merge of #100810 - matthiaskrgr:rollup-xep778s, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #97963 (net listen backlog set to negative on Linux.)
 - #99935 (Reenable disabled early syntax gates as future-incompatibility lints)
 - #100129 (add miri-test-libstd support to libstd)
 - #100500 (Ban references to `Self` in trait object substs for projection predicates too.)
 - #100636 (Revert "Revert "Allow dynamic linking for iOS/tvOS targets."")
 - #100718 ([rustdoc] Fix item info display)
 - #100769 (Suggest adding a reference to a trait assoc item)
 - #100777 (elaborate how revisions work with FileCheck stuff in src/test/codegen)
 - #100796 (Refactor: remove unnecessary string searchings)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-08-20 20:08:26 +00:00
Matthias Krüger
d49906519b
Rollup merge of #99544 - dylni:expose-utf8lossy, r=Mark-Simulacrum
Expose `Utf8Lossy` as `Utf8Chunks`

This PR changes the feature for `Utf8Lossy` from `str_internals` to `utf8_lossy` and improves the API. This is done to eventually expose the API as stable.

Proposal: rust-lang/libs-team#54
Tracking Issue: #99543
2022-08-20 19:32:07 +02:00
dylni
e8ee0b7b2b Expose Utf8Lossy as Utf8Chunks 2022-08-20 12:49:20 -04:00
Ralf Jung
fbcdf2a383 clarify lib.rs attribute structure 2022-08-18 18:07:39 -04:00
Ralf Jung
27b0444333 add some Miri-only tests 2022-08-18 18:07:39 -04:00
Ralf Jung
ac66baad1a add miri-test-libstd support to libstd 2022-08-18 18:07:39 -04:00
The 8472
bb74f97445 address review comments, add tracking issue 2022-08-13 12:58:17 +02:00
The8472
46396e847d add Vec::push_within_capacity - fallible, does not allocate 2022-08-13 10:57:22 +02:00
Mark Rousskov
154a09dd91 Adjust cfgs 2022-08-12 16:28:15 -04:00
YOSHIOKA Takuma
2bb7e1e6ed
Guarantee try_reserve preserves the contents on error
Update doc comments to make the guarantee explicit. However, some
implementations does not have the statement though.

* `HashMap`, `HashSet`: require guarantees on hashbrown side.
* `PathBuf`: simply redirecting to `OsString`.

Fixes #99606.
2022-08-10 01:51:38 +09:00
bors
b573e10d21 Auto merge of #98553 - the8472:next_chunk_opt, r=Mark-Simulacrum
Optimized vec::IntoIter::next_chunk impl

```
x86_64v1, default
test vec::bench_next_chunk                               ... bench:         696 ns/iter (+/- 22)
x86_64v1, pr
test vec::bench_next_chunk                               ... bench:         309 ns/iter (+/- 4)

znver2, default
test vec::bench_next_chunk                               ... bench:      17,272 ns/iter (+/- 117)
znver2, pr
test vec::bench_next_chunk                               ... bench:         211 ns/iter (+/- 3)
```

On znver2 the default impl seems to be slow due to different inlining decisions. It goes through `core::array::iter_next_chunk`
which has a deep call tree.
2022-07-27 01:12:30 +00:00
The 8472
4ba7cac359 add test for vec::IntoIter::next_chunk() impl
an adaption of the default impl's doctest
2022-07-26 21:43:25 +02:00
bors
4d6d601c8a Auto merge of #99574 - durin42:allocator-patch-redux, r=nikic
codegen: use new {re,de,}allocator annotations in llvm

This obviates the patch that teaches LLVM internals about
_rust_{re,de}alloc functions by putting annotations directly in the IR
for the optimizer.

The sole test change is required to anchor FileCheck to the body of the
`box_uninitialized` method, so it doesn't see the `allocalign` on
`__rust_alloc` and get mad about the string `alloca` showing up. Since I
was there anyway, I added some checks on the attributes to prove the
right attributes got set.

r? `@nikic`
2022-07-26 19:35:57 +00:00
The 8472
2f9f2e507e Optimized vec::IntoIter::next_chunk impl
```
test vec::bench_next_chunk                               ... bench:         696 ns/iter (+/- 22)
x86_64v1, pr
test vec::bench_next_chunk                               ... bench:         309 ns/iter (+/- 4)

znver2, default
test vec::bench_next_chunk                               ... bench:      17,272 ns/iter (+/- 117)
znver2, pr
test vec::bench_next_chunk                               ... bench:         211 ns/iter (+/- 3)
```

The znver2 default impl seems to be slow due to inlining decisions. It goes through `core::array::iter_next_chunk`
which has a deeper call tree.
2022-07-26 20:31:43 +02:00
Augie Fackler
130a1df71e codegen: use new {re,de,}allocator annotations in llvm
This obviates the patch that teaches LLVM internals about
_rust_{re,de}alloc functions by putting annotations directly in the IR
for the optimizer.

The sole test change is required to anchor FileCheck to the body of the
`box_uninitialized` method, so it doesn't see the `allocalign` on
`__rust_alloc` and get mad about the string `alloca` showing up. Since I
was there anyway, I added some checks on the attributes to prove the
right attributes got set.

While we're here, we also emit allocator attributes on
__rust_alloc_zeroed. This should allow LLVM to perform more
optimizations for zeroed blocks, and probably fixes #90032. [This
comment](https://github.com/rust-lang/rust/issues/24194#issuecomment-308791157)
mentions "weird UB-like behaviour with bitvec iterators in
rustc_data_structures" so we may need to back this change out if things
go wrong.

The new test cases require LLVM 15, so we copy them into LLVM
14-supporting versions, which we can delete when we drop LLVM 14.
2022-07-26 09:43:28 -04:00
Yuki Okushi
b8aab9781a
Rollup merge of #98710 - mojave2:string, r=JohnTitor
correct the output of a `capacity` method example

The output of this example in std::alloc is different from which shown in the comment. I have tested it on both Linux and Windows.
2022-07-26 07:14:45 +09:00
AngelicosPhosphoros
86d445eda8 Support vec zero-alloc optimization for tuples and byte arrays
* Implement IsZero trait for tuples up to 8 IsZero elements;
* Implement IsZero for u8/i8, leading to implementation of it for arrays of them too;
* Add more codegen tests for this optimization.
* Lower size of array for IsZero trait because it fails to inline checks
2022-07-24 15:56:39 -04:00
Frank Steffahn
c03d10c326 Remove redundant lifetime bound from impl Borrow for Cow
The lifetime bound `B::Owned: 'a` is redundant and doesn't make a difference,
because `Cow<'a, B>` comes with an implicit `B: 'a`, and associated types
will outlive lifetimes outlived by the `Self` type (and all the trait's
generic parameters, of which there are none in this case), so the implicit `B: 'a`
implies `B::Owned: 'a` anyway.

The explicit lifetime bound here does however end up in documentation,
and that's confusing in my opinion, so let's remove it ^^
2022-07-22 01:35:39 +02:00
Alan Wu
321419ec42
Box::from(slice): Clarify that contents are copied
A colleague mentioned that they interpreted the old text
as saying that only the pointer and the length are copied.
Add a clause so it is more clear that the pointed to contents
are also copied.
2022-07-21 13:15:29 -04:00
Matthias Krüger
43783b80ee
Rollup merge of #99413 - steffahn:btree_dropck, r=m-ou-se
Add `PhantomData` marker for dropck to `BTreeMap`

closes #99408
2022-07-21 18:42:02 +02:00
Dylan DPC
e423a6f5f0
Rollup merge of #99198 - RalfJung:alloc-null-ptr, r=JohnTitor
add missing null ptr check in alloc example

`alloc` can return null on OOM, if I understood correctly. So we should never just deref a pointer we get from `alloc`.
2022-07-18 21:14:45 +05:30
Frank Steffahn
110fdb642a Add PhantomData marker for dropck to BTreeMap
closes #99408
2022-07-18 13:03:54 +02:00
AngelicosPhosphoros
85a9c74158 Add tests that check Vec::retain predicate execution order. 2022-07-17 23:34:42 +03:00
Matthias Krüger
ddc32d1633
Rollup merge of #99317 - yanchith:borrow-vec-ta-as-slice-t, r=Mark-Simulacrum
Borrow Vec<T, A> as [T]

Hello all,

When `Vec` was parametrized with `A`, the `Borrow` impls were omitted and currently `Vec<T, A>` can't be borrowed as `[T]`. This PR fixes that.

This was probably missed, because the `Borrow` impls are in a different file - `src/alloc/slice.rs`.

We briefly discussed this here: https://github.com/rust-lang/wg-allocators/issues/96 and I was told to go ahead and make a PR :)

I tested this by building the toolchain and building my code that needed the `Borrow` impl against it, but let me know if I should add any tests to this PR.
2022-07-16 22:30:54 +02:00
yanchith
aeb949753e Borrow Vec<T, A> as [T] 2022-07-16 11:58:26 +02:00
Yuki Okushi
083a253e53
Rollup merge of #99277 - joshtriplett:stabilize-core-cstr-alloc-cstring, r=Mark-Simulacrum
Stabilize `core::ffi::CStr`, `alloc::ffi::CString`, and friends

Stabilize the `core_c_str` and `alloc_c_string` feature gates.

Change `std::ffi` to re-export these types rather than creating type
aliases, since they now have matching stability.
2022-07-16 17:53:04 +09:00
Yuki Okushi
96474a718b
Rollup merge of #99270 - rhysd:issue-99269, r=Mark-Simulacrum
Add `#[must_use]` to `Box::from_raw`

Fixes #99269
2022-07-16 17:53:03 +09:00
Josh Triplett
d6b7480c2a Stabilize core::ffi::CStr, alloc::ffi::CString, and friends
Stabilize the `core_c_str` and `alloc_c_string` feature gates.

Change `std::ffi` to re-export these types rather than creating type
aliases, since they now have matching stability.
2022-07-15 03:10:35 -07:00
rhysd
fa3156ec42 add #[must_use] to Box::from_raw 2022-07-15 17:05:50 +09:00
Dylan DPC
99f3132cd7
Rollup merge of #99113 - WaffleLapkin:arc_simplify, r=Mark-Simulacrum
Simplify [a]rc code a little

Nothing interesting, just make [a]rc code a little nicer by using `byte_sub` and `let`-`else`.
2022-07-15 10:39:41 +05:30
Ralf Jung
080a53a953 add missing null ptr check in alloc example 2022-07-14 11:37:22 -04:00
Duarte Nunes
a85ee3ed91 add code examples 2022-07-14 11:47:06 -03:00
Dylan DPC
103b8602b7
Rollup merge of #98315 - joshtriplett:stabilize-core-ffi-c, r=Mark-Simulacrum
Stabilize `core::ffi:c_*` and rexport in `std::ffi`

This only stabilizes the base types, not the non-zero variants, since
those have their own separate tracking issue and have not gone through
FCP to stabilize.
2022-07-14 14:14:20 +05:30
Josh Triplett
d431338b25 Stabilize core::ffi:c_* and rexport in std::ffi
This only stabilizes the base types, not the non-zero variants, since
those have their own separate tracking issue and have not gone through
FCP to stabilize.
2022-07-13 19:28:20 -07:00
Duarte Nunes
8d35ab3806 rustdoc 2022-07-13 22:04:15 -03:00
Duarte Nunes
050115c0d4 typo 2022-07-13 21:49:31 -03:00
Duarte Nunes
c9ec7aa0d7 changes to wording 2022-07-13 21:48:18 -03:00
Duarte Nunes
9cd66be235 docs: be less harsh in wording for Vec::from_raw_parts
In particular, be clear that it is sound to specify memory not
originating from a previous `Vec` allocation. That is already suggested
in other parts of the documentation about zero-alloc conversions to Box<[T]>.

Incorporate a constraint from `slice::from_raw_parts` that was missing
but needs to be fulfilled, since a `Vec` can be converted into a slice.
2022-07-13 14:29:35 -03:00
Maybe Waffle
69f8eb17c6 Use byte_sub in [a]rc impl 2022-07-10 15:16:51 +04:00
bors
4ec97d991b Auto merge of #95295 - CAD97:layout-isize, r=scottmcm
Enforce that layout size fits in isize in Layout

As it turns out, enforcing this _in APIs that already enforce `usize` overflow_ is fairly trivial. `Layout::from_size_align_unchecked` continues to "allow" sizes which (when rounded up) would overflow `isize`, but these are now declared as library UB for `Layout`, meaning that consumers of `Layout` no longer have to check this before making an allocation.

(Note that this is "immediate library UB;" IOW it is valid for a future release to make this immediate "language UB," and there is an extant patch to do so, to allow Miri to catch this misuse.)

See also #95252, [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Layout.20Isn't.20Enforcing.20The.20isize.3A.3AMAX.20Rule).
Fixes https://github.com/rust-lang/rust/issues/95334

Some relevant quotes:

`@eddyb,` https://github.com/rust-lang/rust/pull/95252#issuecomment-1078513769

> [B]ecause of the non-trivial presence of both of these among code published on e.g. crates.io:
>
>   1. **`Layout` "producers" / `GlobalAlloc` "users"**: smart pointers (including `alloc::rc` copies with small tweaks), collections, etc.
>   2. **`Layout` "consumers" / `GlobalAlloc` "providers"**: perhaps fewer of these, but anything built on top of OS APIs like `mmap` will expose `> isize::MAX` allocations (on 32-bit hosts) if they lack extra checks
>
> IMO the only responsible option is to enforce the `isize::MAX` limit in `Layout`, which:
>
>   * makes `Layout` _sound_ in terms of only ever allowing allocations where `(alloc_base_ptr: *mut u8).offset(size)` is never UB
>   * frees both "producers" and "consumers" of `Layout` from manually reimplementing the checks
>     * manual checks can be risky, e.g. if the final size passed to the allocator isn't the one being checked
>     * this applies retroactively, fixing the overall soundness of existing code with zero transition period or _any_ changes required from users (as long as going through `Layout` is mandatory, making a "choke point")
>
>
> Feel free to quote this comment onto any relevant issue, I might not be able to keep track of developments.

`@Gankra,` https://github.com/rust-lang/rust/pull/95252#issuecomment-1078556371

> As someone who spent way too much time optimizing libcollections checks for this stuff and tried to splatter docs about it everywhere on the belief that it was a reasonable thing for people to manually take care of: I concede the point, it is not reasonable. I am wholy spiritually defeated by the fact that _liballoc_ of all places is getting this stuff wrong. This isn't throwing shade at the folks who implemented these Rc features, but rather a statement of how impractical it is to expect anyone out in the wider ecosystem to enforce them if _some of the most audited rust code in the library that defines the very notion of allocating memory_ can't even reliably do it.
>
> We need the nuclear option of Layout enforcing this rule. Code that breaks this rule is _deeply_ broken and any "regressions" from changing Layout's contract is a _correctness_ fix. Anyone who disagrees and is sufficiently motivated can go around our backs but the standard library should 100% refuse to enable them.

cc also `@RalfJung` `@rust-lang/wg-allocators.` Even though this technically supersedes #95252, those potential failure points should almost certainly still get nicer panics than just "unwrap failed" (which they would get by this PR).

It might additionally be worth recommending to users of the `Layout` API that they should ideally use `.and_then`/`?` to complete the entire layout calculation, and then `panic!` from a single location at the end of `Layout` manipulation, to reduce the overhead of the checks and optimizations preserving the exact location of each `panic` which are conceptually just one failure: allocation too big.

Probably deserves a T-lang and/or T-libs-api FCP (this technically solidifies the [objects must be no larger than `isize::MAX`](https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#isize-and-usize) rule further, and the UCG document says this hasn't been RFCd) and a crater run. Ideally, no code exists that will start failing with this addition; if it does, it was _likely_ (but not certainly) causing UB.

Changes the raw_vec allocation path, thus deserves a perf run as well.

I suggest hiding whitespace-only changes in the diff view.
2022-07-10 08:54:32 +00:00
est31
bdf1d22515 Intra-doc-link-ify reference to Clone::clone_from 2022-07-08 22:47:07 +02:00
bors
f99f9e48ed Auto merge of #98755 - nnethercote:faster-vec-insert, r=cuviper
Optimize `Vec::insert` for the case where `index == len`.

By skipping the call to `copy` with a zero length. This makes it closer
to `push`.

I did this recently for `SmallVec`
(https://github.com/servo/rust-smallvec/pull/282) and it was a big perf win in
one case. Although I don't have a specific use case in mind, it seems
worth doing it for `Vec` as well.

Things to note:
- In the `index < len` case, the number of conditions checked is
  unchanged.
- In the `index == len` case, the number of conditions checked increases
  by one, but the more expensive zero-length copy is avoided.
- In the `index > len` case the code now reserves space for the extra
  element before panicking. This seems like an unimportant change.

r? `@cuviper`
2022-07-03 09:36:37 +00:00
bors
ada8c80bed Auto merge of #98673 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bump bootstrap compiler

r? `@Mark-Simulacrum`
2022-07-03 06:55:50 +00:00
Dylan DPC
9dd3288557
Rollup merge of #98585 - cuviper:covariant-thinbox, r=thomcc
Make `ThinBox<T>` covariant in `T`

Just like `Box<T>`, we want `ThinBox<T>` to be covariant in `T`, but the
projection in `WithHeader<<T as Pointee>::Metadata>` was making it
invariant. This is now hidden as `WithOpaqueHeader`, which we type-cast
whenever the real `WithHeader<H>` type is needed.

Fixes the problem noted in <https://github.com/rust-lang/rust/issues/92791#issuecomment-1104636249>.
2022-07-01 20:19:17 +05:30
Pietro Albini
6b2d3d5f3c
update cfg(bootstrap)s 2022-07-01 15:48:23 +02:00
Nicholas Nethercote
679c5ee244 Optimize Vec::insert for the case where index == len.
By skipping the call to `copy` with a zero length. This makes it closer
to `push`.

I did this recently for `SmallVec`
(https://github.com/servo/rust-smallvec/pull/282) and it was a big perf win in
one case. Although I don't have a specific use case in mind, it seems
worth doing it for `Vec` as well.

Things to note:
- In the `index < len` case, the number of conditions checked is
  unchanged.
- In the `index == len` case, the number of conditions checked increases
  by one, but the more expensive zero-length copy is avoided.
- In the `index > len` case the code now reserves space for the extra
  element before panicking. This seems like an unimportant change.
2022-07-01 06:46:30 +10:00
mojave2
6c3ca7e418 correct the output of a capacity method example 2022-06-30 21:10:28 +08:00
Miguel Ojeda
83addf2540 alloc: fix no_global_oom_handling warnings
Rust 1.62.0 introduced a couple new `unused_imports` warnings
in `no_global_oom_handling` builds, making a total of 5 warnings:

```txt
warning: unused import: `Unsize`
 --> library/alloc/src/boxed/thin.rs:6:33
  |
6 | use core::marker::{PhantomData, Unsize};
  |                                 ^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused import: `from_fn`
  --> library/alloc/src/string.rs:51:18
   |
51 | use core::iter::{from_fn, FusedIterator};
   |                  ^^^^^^^

warning: unused import: `core::ops::Deref`
  --> library/alloc/src/vec/into_iter.rs:12:5
   |
12 | use core::ops::Deref;
   |     ^^^^^^^^^^^^^^^^

warning: associated function `shrink` is never used
   --> library/alloc/src/raw_vec.rs:424:8
    |
424 |     fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> {
    |        ^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: associated function `forget_remaining_elements` is never used
   --> library/alloc/src/vec/into_iter.rs:126:19
    |
126 |     pub(crate) fn forget_remaining_elements(&mut self) {
    |                   ^^^^^^^^^^^^^^^^^^^^^^^^^
```

This patch cleans them so that projects compiling `alloc` without
infallible allocations do not see the warnings. It also enables
the use of `-Dwarnings`.

The couple `dead_code` ones may be reverted when some fallible
allocation support starts using them.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-06-29 04:44:23 +02:00
Dylan DPC
e5b82de04c
Rollup merge of #98595 - cuviper:send-sync-thinbox, r=m-ou-se
Implement `Send` and `Sync` for `ThinBox<T>`

Just like `Box<T>`, `ThinBox<T>` owns its data on the heap, so it should
implement `Send` and `Sync` when `T` does.

This extends tracking issue #92791.
2022-06-28 15:30:07 +05:30
Josh Stone
6400736142 Implement Send and Sync for ThinBox<T>
Just like `Box<T>`, `ThinBox<T>` owns its data on the heap, so it should
implement `Send` and `Sync` when `T` does.
2022-06-27 15:49:59 -07:00
Josh Stone
e67e165585 Make ThinBox<T> covariant in T
Just like `Box<T>`, we want `ThinBox<T>` to be covariant in `T`, but the
projection in `WithHeader<<T as Pointee>::Metadata>` was making it
invariant. This is now hidden as `WithOpaqueHeader`, which we type-cast
whenever the real `WithHeader<H>` type is needed.
2022-06-27 10:05:55 -07:00
Ralf Jung
9b497abb9a liballoc tests: avoid int2ptr cast 2022-06-27 10:50:56 -04:00
Yuki Okushi
6580d7e784
Rollup merge of #98039 - tnballo:master, r=thomcc
Fix `panic` message for `BTreeSet`'s `range` API and document `panic` cases

Currently, the `panic` cases for [`BTreeSet`'s `range` API](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.range) are undocumented and produce a slightly wrong `panic` message (says `BTreeMap` instead of `BTreeSet`).

Panic case 1 code:

```rust
use std::collections::BTreeSet;
use std::ops::Bound::Excluded;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(3);
    set.insert(5);
    set.insert(8);

    for &elem in set.range((Excluded(&3), Excluded(&3))) {
        println!("{elem}");
    }
}
```

Panic case 1 message:

```
thread 'main' panicked at 'range start and end are equal and excluded in BTreeMap', /rustc/fe5b13d681f25ee6474be29d748c65adcd91f69e/library/alloc/src/collections/btree/search.rs:105:17
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```

Panic case 2 code:

```rust
use std::collections::BTreeSet;
use std::ops::Bound::Included;

fn main() {
    let mut set = BTreeSet::new();
    set.insert(3);
    set.insert(5);
    set.insert(8);

    for &elem in set.range((Included(&8), Included(&3))) {
        println!("{elem}");
    }
}
```

Panic case 2:

```
thread 'main' panicked at 'range start is greater than range end in BTreeMap', /rustc/fe5b13d681f25ee6474be29d748c65adcd91f69e/library/alloc/src/collections/btree/search.rs:110:17
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```

This PR fixes the output messages to say `BTreeSet`, adds the relevant unit tests, and updates the documentation for the API.
2022-06-24 16:43:44 +09:00
tnballo
774e814b95
Fix BTreeSet's range API panic message, document 2022-06-23 19:12:24 -04:00
Michael Goulet
e749ba2061
Rollup merge of #98364 - RalfJung:arc-clone, r=Mark-Simulacrum
clarify Arc::clone overflow check comment

I had to read this twice to realize that this is explaining that the code is technically unsound, so move that into a dedicated paragraph and make the wording a bit more explicit.
2022-06-23 14:39:13 -07:00
Michael Goulet
262382ff37
Rollup merge of #96173 - jmaargh:jmaargh/with-capacity-doc-fix, r=Dylan-DPC
Fix documentation for  `with_capacity` and `reserve` families of methods

Fixes #95614

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.
2022-06-23 14:39:05 -07:00