Add #[must_use] to alloc functions that would leak memory
As [requested](https://github.com/rust-lang/rust/pull/89899#issuecomment-955600779) by `@joshtriplett.`
> Please do go ahead and add the ones whose only legitimate use for ignoring the return value is leaking memory. (In a separate PR please.) I think it's sufficiently error-prone to call something like alloc and ignore the result that it's legitimate to require `let _ =` for that.
I added `realloc` myself. Clippy ignored it because of its `mut` argument.
```rust
alloc/src/alloc.rs:123:1 alloc unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8;
```
Parent issue: #89692
r? `@joshtriplett`
Add #[must_use] to remaining core functions
I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `core` crate.
Ignored by clippy for reasons unknown:
```rust
core::alloc::Layout unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self;
core::any const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str;
```
Ignored by clippy because of `mut`:
```rust
str fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
```
<del>
Ignored by clippy presumably because a caller might want `f` called for side effects. That seems like a bad usage of `map` to me.
```rust
core::cell::Ref<'b, T> fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, T>;
core::cell::Ref<'b, T> fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>);
```
</del>
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to expensive computations
The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work.
Given the grab bag nature of this commit, the messages I used vary quite a bit. I'm open to wording changes.
For some reason clippy flagged four `BTreeSet` methods but didn't say boo about equivalent ones on `HashSet`. I stared at them for a while but I can't figure out the difference so I added the `HashSet` ones in.
```rust
// Flagged by clippy.
alloc::collections::btree_set::BTreeSet<T> fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>;
alloc::collections::btree_set::BTreeSet<T> fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
alloc::collections::btree_set::BTreeSet<T> fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>;
alloc::collections::btree_set::BTreeSet<T> fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>;
// Ignored by clippy, but not by me.
std::collections::HashSet<T, S> fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>;
std::collections::HashSet<T, S> fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S>
std::collections::HashSet<T, S> fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>;
std::collections::HashSet<T, S> fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>;
```
Parent issue: #89692
r? ```@joshtriplett```
Previously, it wasn't clear whether "This could include" was referring
to logic errors, or undefined behaviour. Tweak wording to clarify this
sentence does not relate to UB.
Fix MIRI UB in `Vec::swap_remove`
Fixes#90055
I find it weird that `Vec::swap_remove` read the last element to the stack just to immediately put it back in the `Vec` in place of the one at index `index`. It seems much more natural to me to just read the element at position `index` and then move the last element in its place. I guess this might also slightly improve codegen.
Avoid overflow in `VecDeque::with_capacity_in()`.
The overflow only happens if alloc is compiled with overflow checks enabled and the passed capacity is greater or equal 2^(usize::BITS-1). The overflow shadows the expected "capacity overflow" panic leading to a test failure if overflow checks are enabled for std in the CI.
Unblocks [CI: Enable overflow checks for test (non-dist) builds #89776](https://github.com/rust-lang/rust/pull/89776).
For some reason the overflow is only observable with optimization turned off, but that is a separate issue.
Avoid allocations and copying in Vec::leak
The [`Vec::leak`] method (#62195) is currently implemented by calling `Vec::into_boxed_slice` and `Box::leak`. This shrinks the vector before leaking it, which potentially causes a reallocation and copies the vector's contents.
By avoiding the conversion to `Box`, we can instead leak the vector without any expensive operations, just by returning a slice reference and forgetting the `Vec`. Users who *want* to shrink the vector first can still do so by calling `shrink_to_fit` explicitly.
**Note:** This could break code that uses `Box::from_raw` to “un-leak” the slice returned by `Vec::leak`. However, the `Vec::leak` docs explicitly forbid this, so such code is already incorrect.
[`Vec::leak`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.leak
Optimize VecDeque::append
Optimize `VecDeque::append` to do unsafe copy rather than iterating through each element.
On my `Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz`, the benchmark shows 37% improvements:
```
Master:
custom-bench vec_deque_append 583164 ns/iter
custom-bench vec_deque_append 550040 ns/iter
Patched:
custom-bench vec_deque_append 349204 ns/iter
custom-bench vec_deque_append 368164 ns/iter
```
Additional notes on the context: this is the third attempt to implement a non-trivial version of `VecDeque::append`, the last two are reverted due to unsoundness or regression, see:
- https://github.com/rust-lang/rust/pull/52553, reverted in https://github.com/rust-lang/rust/pull/53571
- https://github.com/rust-lang/rust/pull/53564, reverted in https://github.com/rust-lang/rust/pull/54851
Both cases are covered by existing tests.
Signed-off-by: tabokie <xy.tao@outlook.com>
The unifying theme for this commit is weak, admittedly. I put together a
list of "expensive" functions when I originally proposed this whole
effort, but nobody's cared about that criterion. Still, it's a decent
way to bite off a not-too-big chunk of work.
Given the grab bag nature of this commit, the messages I used vary quite
a bit.
Add #[must_use] to non-mutating verb methods
These are methods that could be misconstrued to mutate their input, similar to #89694. I gave each one a different custom message.
I wrote that `upgrade` and `downgrade` don't modify the input pointers. Logically they don't, but technically they do...
Parent issue: #89692
r? ```@joshtriplett```
Add #[must_use] to from_value conversions
I added two methods to the list myself. Clippy did not flag them because they take `mut` args, but neither modifies their argument.
```rust
core::str const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str;
std::ffi::CString unsafe fn from_raw(ptr: *mut c_char) -> CString;
```
I put a custom note on `from_raw`:
```rust
#[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `CString`"]
pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
```
Parent issue: #89692
r? ``@joshtriplett``
Add #[must_use] to alloc constructors
Added `#[must_use]`. to the various forms of `new`, `pin`, and `with_capacity` in the `alloc` crate. No extra explanations given as I couldn't think of anything useful to add.
I figure this deserves extra scrutiny compared to the other PRs I've done so far. In particular:
* The 4 `pin`/`pin_in` methods I touched. Are there legitimate use cases for pinning and not using the result? Pinning's a difficult concept I'm not very comfortable with.
* `Box`'s constructors. Do people ever create boxes just for the side effects... allocating or zeroing out memory?
Parent issue: #89692
r? ``@joshtriplett``
Cfg hide no_global_oom_handling and no_fp_fmt_parse
These are unstable sysroot customisation cfg options that only projects building their own sysroot will use (e.g. Rust-for-linux). Most users shouldn't care. `no_global_oom_handling` can be especially annoying since it's applied on many commonly used alloc crate methods (e.g. `Box::new`, `Vec::push`).
r? ```@GuillaumeGomez```
Add documentation to boxed conversions
Among other changes, documents whether allocations are necessary
to complete the type conversion.
Part of #51430, supersedes #89199