about summary refs log tree commit diff
path: root/library/alloc/src
AgeCommit message (Collapse)AuthorLines
2024-12-21Less unwrap() in documentationKornel-2/+1
2024-12-20Rollup merge of #126118 - jan-ferdinand:docs_for_vec_set_len, r=the8472Jacob Pratt-1/+6
docs: Mention `spare_capacity_mut()` in `Vec::set_len` I recently went down a small rabbit hole when trying to identify safe use of `Vec::set_len`. The solution was `Vec::spare_capacity_mut`. I think the docs on `Vec::set_len` benefit from mentioning this method. A possible counter-argument could be that the [clippy lint `uninit_vec`](https://rust-lang.github.io/rust-clippy/master/index.html#/uninit_vec) already nudges people in the right direction. However, I think a working example on `Vec::set_len` is still beneficial. Happy to hear your thoughts on the matter. :blush:
2024-12-19Add missing safety descriptions to Arc's ↵LemonJ-2/+6
'from_raw','increment_strong_count','decrement_strong_count'
2024-12-18Auto merge of #134443 - joshtriplett:use-field-init-shorthand, ↵bors-2/+2
r=lqd,tgross35,nnethercote Use field init shorthand where possible Field init shorthand allows writing initializers like `tcx: tcx` as `tcx`. The compiler already uses it extensively. Fix the last few places where it isn't yet used. EDIT: this PR also updates `rustfmt.toml` to set `use_field_init_shorthand = true`.
2024-12-18Add 'into_array' conversion destructors for 'Box', 'Rc', and 'Arc';Gabriel Bjørnager Jensen-0/+60
2024-12-17Use field init shorthand where possibleJosh Triplett-2/+2
Field init shorthand allows writing initializers like `tcx: tcx` as `tcx`. The compiler already uses it extensively. Fix the last few places where it isn't yet used.
2024-12-16remove obsolete comment and pub(super) visibilityThe 8472-12/+6
2024-12-16remove bounds from vec and linkedlist ExtractIfThe 8472-19/+7
since drain-on-drop behavior was removed those bounds no longer serve a purpose
2024-12-16Add a range argument to vec.extract_ifThe 8472-20/+46
2024-12-15Auto merge of #134332 - Zalathar:rollup-oe23hkw, r=Zalatharbors-24/+27
Rollup of 7 pull requests Successful merges: - #130361 (std::net: Solaris supports `SOCK_CLOEXEC` as well since 11.4.) - #133406 (Add value accessor methods to `Mutex` and `RwLock`) - #133633 (don't show the full linker args unless `--verbose` is passed) - #134285 (Add some convenience helper methods on `hir::Safety`) - #134310 (Add clarity to the examples of some `Vec` & `VecDeque` methods) - #134313 (Don't make a def id for `impl_trait_in_bindings`) - #134315 (A couple of polonius fact generation cleanups) r? `@ghost` `@rustbot` modify labels: rollup
2024-12-15Rollup merge of #134310 - tkr-sh:master, r=NoratriebStuart Cook-24/+27
Add clarity to the examples of some `Vec` & `VecDeque` methods In some `Vec` and `VecDeque` examples where elements are `i32`, examples can seem a bit confusing at first glance if a parameter of the method is an `usize`. In this case, I think it's better to use `char` rather than `i32`. > [!NOTE] > It's already done in the implementation of `VecDeque::insert` #### Difference - `i32` ```rs let mut v = vec![1, 2, 3]; assert_eq!(v.remove(1), 2); assert_eq!(v, [1, 3]); ``` - `char` ```rs let mut v = vec!['a', 'b', 'c']; assert_eq!(v.remove(1), 'b'); assert_eq!(v, ['a', 'c']); ``` Even tho it's pretty minor, it's a nice to have.
2024-12-15Auto merge of #133223 - zachs18:uniquerc-impls, r=Noratriebbors-4/+249
`UniqueRc` trait impls UniqueRc tracking Issue: #112566 Stable traits: (i.e. impls behind only the `unique_rc_arc` feature gate) * Support the same formatting as `Rc`: * `fmt::Debug` and `fmt::Display` delegate to the pointee. * `fmt::Pointer` prints the address of the pointee. * Add explicit `!Send` and `!Sync` impls, to mirror `Rc`. * Borrowing traits: `Borrow`, `BorrowMut`, `AsRef`, `AsMut` * `Rc` does not implement `BorrowMut` and `AsMut`, but `UniqueRc` can. * Unconditional `Unpin`, like other heap-allocated types. * Comparison traits `(Partial)Ord` and `(Partial)Eq` delegate to the pointees. * `PartialEq for UniqueRc` does not do `Rc`'s specialization shortcut for pointer equality when `T: Eq`, since by definition two `UniqueRc`s cannot share an allocation. * `Hash` delegates to the pointee. * `AsRawFd`, `AsFd`, `AsHandle`, `AsSocket` delegate to the pointee like `Rc`. * Sidenote: The bounds on `T` for the existing `Pointer<T>` impls for specifically `AsRawFd` and `AsSocket` do not allow `T: ?Sized`. For the added `UniqueRc` impls I allowed `T: ?Sized` for all four traits, but I did not change the existing (stable) impls. Unstable traits: * `DispatchFromDyn`, allows using `UniqueRc<Self>` as a method receiver under `feature(arbitrary_self_types)`. * Existing `PinCoerceUnsized for UniqueRc` is generalized to allow non-`Global` allocators, like `Rc`. * `DerefPure`, allows using `UniqueRc` in deref-patterns under `feature(deref_patterns)`, like `Rc`. For documentation, `Rc` only has documentation on the comparison traits' methods, so I copied/adapted the documentation for those, and left the rest without impl-specific docs. ~~Edit: Marked as draft while I figure out `UnwindSafe`.~~ Edit: Ignoring `UnwindSafe` for this PR
2024-12-15Asserts the maximum value that can be returned from `Vec::len`EFanZh-2/+9
2024-12-15Auto merge of #134258 - bjorn3:no_public_specialization, r=petrochenkovbors-37/+32
Remove support for specializing ToString outside the standard library This is the only trait specializable outside of the standard library. Before stabilizing specialization we will probably want to remove support for this. It was originally made specializable to allow a more efficient ToString in libproc_macro back when this way the only way to get any data out of a TokenStream. We now support getting individual tokens, so proc macros no longer need to call it as often.
2024-12-14Add clarity to the "greater" of `VecDeque::insert`tkirishima-1/+1
2024-12-14Replace i32 by char to add claritytkirishima-23/+26
In some `Vec` and `VecDeque` examples where elements are i32, examples can seem a bit confusing at first glance if a parameter of the method is an usize.
2024-12-13Remove support for specializing ToString outside the standard librarybjorn3-37/+32
This is the only trait specializable outside of the standard library. Before stabilizing specialization we will probably want to remove support for this. It was originally made specializable to allow a more efficient ToString in libproc_macro back when this way the only way to get any data out of a TokenStream. We now support getting individual tokens, so proc macros no longer need to call it as often.
2024-12-13Stabilize async closuresMichael Goulet-4/+7
2024-12-12Rollup merge of #133859 - bjorn3:move_tests_to_alloctests, r=tgross35Matthias Krüger-1707/+0
Move some alloc tests to the alloctests crate Unit tests directly inside of standard library crates require a very fragile way of building that is hard to reproduce outside of bootstrap.
2024-12-11Rollup merge of #133598 - ChayimFriedman2:get-many-mut-detailed-err, r=scottmcmMatthias Krüger-0/+2
Change `GetManyMutError` to match T-libs-api decision That is, differentiate between out-of-bounds and overlapping indices, and remove the generic parameter `N`. I also exported `GetManyMutError` from `alloc` (and `std`), which was apparently forgotten. Changing the error to carry additional details means LLVM no longer generates separate short-circuiting branches for the checks, instead it generates one branch at the end. I therefore changed the code to use early returns to make LLVM generate jumps. Benchmark results between the approaches are somewhat mixed, but I chose this approach because it is significantly faster with ranges and also faster with `unwrap()`. Benchmark (`jumps` refer to short-circuiting, `acc` is not short-circuiting): ```rust use criterion::{black_box, criterion_group, criterion_main, Criterion}; use my_crate::{get_many_check_valid_acc, get_many_check_valid_jumps, GetManyMutError}; mod externs { #[unsafe(no_mangle)] fn foo() {} #[unsafe(no_mangle)] fn bar() {} #[unsafe(no_mangle)] fn baz() {} } unsafe extern "C" { safe fn foo(); safe fn bar(); safe fn baz(); } fn bench_method(c: &mut Criterion) { c.bench_function("jumps two usize", |b| { b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10))) }); c.bench_function("jumps two usize unwrap", |b| { b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10)).unwrap()) }); c.bench_function("jumps two usize ok", |b| { b.iter(|| get_many_check_valid_jumps(&[black_box(1), black_box(5)], black_box(10)).ok()) }); c.bench_function("jumps three usize", |b| { b.iter(|| { get_many_check_valid_jumps(&[black_box(1), black_box(5), black_box(7)], black_box(10)) }) }); c.bench_function("jumps three usize match", |b| { b.iter(|| { match get_many_check_valid_jumps( &[black_box(1), black_box(5), black_box(7)], black_box(10), ) { Err(GetManyMutError::IndexOutOfBounds) => foo(), Err(GetManyMutError::OverlappingIndices) => bar(), Ok(()) => baz(), } }) }); c.bench_function("jumps two Range", |b| { b.iter(|| { get_many_check_valid_jumps( &[black_box(1)..black_box(5), black_box(7)..black_box(8)], black_box(10), ) }) }); c.bench_function("jumps two RangeInclusive", |b| { b.iter(|| { get_many_check_valid_jumps( &[black_box(1)..=black_box(5), black_box(7)..=black_box(8)], black_box(10), ) }) }); c.bench_function("acc two usize", |b| { b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10))) }); c.bench_function("acc two usize unwrap", |b| { b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10)).unwrap()) }); c.bench_function("acc two usize ok", |b| { b.iter(|| get_many_check_valid_acc(&[black_box(1), black_box(5)], black_box(10)).ok()) }); c.bench_function("acc three usize", |b| { b.iter(|| { get_many_check_valid_acc(&[black_box(1), black_box(5), black_box(7)], black_box(10)) }) }); c.bench_function("acc three usize match", |b| { b.iter(|| { match get_many_check_valid_jumps( &[black_box(1), black_box(5), black_box(7)], black_box(10), ) { Err(GetManyMutError::IndexOutOfBounds) => foo(), Err(GetManyMutError::OverlappingIndices) => bar(), Ok(()) => baz(), } }) }); c.bench_function("acc two Range", |b| { b.iter(|| { get_many_check_valid_acc( &[black_box(1)..black_box(5), black_box(7)..black_box(8)], black_box(10), ) }) }); c.bench_function("acc two RangeInclusive", |b| { b.iter(|| { get_many_check_valid_acc( &[black_box(1)..=black_box(5), black_box(7)..=black_box(8)], black_box(10), ) }) }); } criterion_group!(benches, bench_method); criterion_main!(benches); ``` Benchmark results: ```none jumps two usize time: [586.44 ps 590.20 ps 594.50 ps] jumps two usize unwrap time: [390.44 ps 393.63 ps 397.44 ps] jumps two usize ok time: [585.52 ps 591.74 ps 599.38 ps] jumps three usize time: [976.51 ps 983.79 ps 991.51 ps] jumps three usize match time: [390.82 ps 393.80 ps 397.07 ps] jumps two Range time: [1.2583 ns 1.2640 ns 1.2695 ns] jumps two RangeInclusive time: [1.2673 ns 1.2770 ns 1.2877 ns] acc two usize time: [592.63 ps 596.44 ps 600.52 ps] acc two usize unwrap time: [582.65 ps 587.07 ps 591.90 ps] acc two usize ok time: [581.59 ps 587.82 ps 595.71 ps] acc three usize time: [894.69 ps 901.23 ps 908.24 ps] acc three usize match time: [392.68 ps 395.73 ps 399.17 ps] acc two Range time: [1.5531 ns 1.5617 ns 1.5711 ns] acc two RangeInclusive time: [1.5746 ns 1.5840 ns 1.5939 ns] ```
2024-12-06Auto merge of #118159 - EliasHolzmann:formatting_options, r=m-ou-sebors-1/+5
Implementation of `fmt::FormattingOptions` Tracking issue: #118117 Public API: ```rust #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct FormattingOptions { … } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Sign { Plus, Minus } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum DebugAsHex { Lower, Upper } impl FormattingOptions { pub fn new() -> Self; pub fn sign(&mut self, sign: Option<Sign>) -> &mut Self; pub fn sign_aware_zero_pad(&mut self, sign_aware_zero_pad: bool) -> &mut Self; pub fn alternate(&mut self, alternate: bool) -> &mut Self; pub fn fill(&mut self, fill: char) -> &mut Self; pub fn align(&mut self, alignment: Option<Alignment>) -> &mut Self; pub fn width(&mut self, width: Option<usize>) -> &mut Self; pub fn precision(&mut self, precision: Option<usize>) -> &mut Self; pub fn debug_as_hex(&mut self, debug_as_hex: Option<DebugAsHex>) -> &mut Self; pub fn get_sign(&self) -> Option<Sign>; pub fn get_sign_aware_zero_pad(&self) -> bool; pub fn get_alternate(&self) -> bool; pub fn get_fill(&self) -> char; pub fn get_align(&self) -> Option<Alignment>; pub fn get_width(&self) -> Option<usize>; pub fn get_precision(&self) -> Option<usize>; pub fn get_debug_as_hex(&self) -> Option<DebugAsHex>; pub fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a>; } impl<'a> Formatter<'a> { pub fn new(write: &'a mut (dyn Write + 'a), options: FormattingOptions) -> Self; pub fn with_options<'b>(&'b mut self, options: FormattingOptions) -> Formatter<'b>; pub fn sign(&self) -> Option<Sign>; pub fn options(&self) -> FormattingOptions; } ``` Relevant changes from the public API in the tracking issue (I'm leaving out some stuff I consider obvious mistakes, like missing `#[derive(..)]`s and `pub` specifiers): - `enum DebugAsHex`/`FormattingOptions::debug_as_hex`/`FormattingOptions::get_debug_as_hex`: To support `{:x?}` as well as `{:X?}`. I had completely missed these options in the ACP. I'm open for any and all bikeshedding, not married to the name. - `fill`/`get_fill` now takes/returns `char` instead of `Option<char>`. This simply mirrors what `Formatter::fill` returns (with default being `' '`). - Changed `zero_pad`/`get_zero_pad` to `sign_aware_zero_pad`/`get_sign_aware_zero_pad`. This also mirrors `Formatter::sign_aware_zero_pad`. While I'm not a fan of this quite verbose name, I do believe that having the interface of `Formatter` and `FormattingOptions` be compatible is more important. - For the same reason, renamed `alignment`/`get_alignment` to `aling`/`get_align`. - Deviating from my initial idea, `Formatter::with_options` returns a `Formatter` which has the lifetime of the `self` reference as its generic lifetime parameter (in the original API spec, the generic lifetime of the returned `Formatter` was the generic lifetime used by `self` instead). Otherwise, one could construct two `Formatter`s that both mutably borrow the same underlying buffer, which would be unsound. This solution still has performance benefits over simply using `Formatter::new`, so I believe it is worthwhile to keep this method.
2024-12-06Auto merge of #133089 - eholk:stabilize-noop-waker, r=dtolnaybors-1/+0
Stabilize noop_waker Tracking Issue: #98286 This is a handy feature that's been used widely in tests and example async code and it'd be nice to make it available to users. cc `@rust-lang/wg-async`
2024-12-05Stabilize noop_wakerEric Holk-1/+0
Co-authored-by: zachs18 <8355914+zachs18@users.noreply.github.com>
2024-12-05Fixed another broken testElias Holzmann-2/+2
2024-12-05Added struct `fmt::FormattingOptions`Elias Holzmann-1/+5
This allows to build custom `std::Formatter`s at runtime. Also added some related enums and two related methods on `std::Formatter`.
2024-12-05Improve documentationXelph-11/+14
Fix missing newlines that rustfmt removed. fix trailing whitespace Fix duplicate word. Reformat panic reasons into a list remove trailing whitespace 2 electric boogaloo Change verbe tense. Integrate suggestions
2024-12-04Move some alloc tests to the alloctests cratebjorn3-1707/+0
Unit tests directly inside of standard library crates require a very fragile way of building that is hard to reproduce outside of bootstrap.
2024-12-02Use c"lit" for CStrings without unwrapKornel-22/+20
2024-12-01Rollup merge of #133672 - RalfJung:const-stability-cleanup, r=jhprattJacob Pratt-9/+0
Remove a bunch of unnecessary const stability noise
2024-11-30get rid of a bunch of unnecessary rustc_const_unstableRalf Jung-1/+0
2024-11-30remove a whole bunch of unnecessary const feature gatesRalf Jung-8/+0
2024-11-30Rollup merge of #133548 - cuviper:btreeset-entry-api, r=Mark-Simulacrum许杰友 Jieyou Xu (Joe)-2/+530
Add `BTreeSet` entry APIs to match `HashSet` The following methods are added, along with the corresponding `Entry` implementation. ```rust impl<T, A: Allocator + Clone> BTreeSet<T, A> { pub fn get_or_insert(&mut self, value: T) -> &T where T: Ord, {...} pub fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T where T: Borrow<Q> + Ord, Q: Ord, F: FnOnce(&Q) -> T, {...} pub fn entry(&mut self, value: T) -> Entry<'_, T, A> where T: Ord, {...} } ``` Tracking issue #133549 Closes https://github.com/rust-lang/rfcs/issues/1490
2024-11-29Auto merge of #133533 - BoxyUwU:bump-boostrap, r=jieyouxu,Mark-Simulacrumbors-25/+18
Bump boostrap compiler to new beta Currently failing due to something about the const stability checks and `panic!`. I'm not sure why though since I wasn't able to see any PRs merged in the past few days that would result in a `cfg(bootstrap)` that shouldn't be removed. cc `@RalfJung` #131349
2024-11-29Rollup merge of #133530 - timvisee:master, r=jhprattMatthias Krüger-6/+6
Use consistent wording in docs, use is zero instead of is 0 In documentation, wording of _"`rhs` is zero"_ and _"`rhs` is 0"_ is intermixed. This is especially visible [here](https://doc.rust-lang.org/std/primitive.usize.html#method.div_ceil). This changes all occurrences to _"`rhs` is zero"_ for better readability.
2024-11-28Change `GetManyMutError` to match T-libs-api decisionChayim Refael Friedman-0/+2
That is, differentiate between out-of-bounds and overlapping indices, and remove the generic parameter `N`. I also exported `GetManyMutError` from `alloc` (and `std`), which was apparently forgotten. Changing the error to carry additional details means LLVM no longer generates separate short-circuiting branches for the checks, instead it generates one branch at the end. I therefore changed the code to use early returns to make LLVM generate jumps. Benchmark results between the approaches are somewhat mixed, but I chose this approach because it is significantly faster with ranges and also faster with `unwrap()`.
2024-11-28Share inline(never) generics across cratesMark Rousskov-1/+3
This reduces code sizes and better respects programmer intent when marking inline(never). Previously such a marking was essentially ignored for generic functions, as we'd still inline them in remote crates.
2024-11-28Also use zero when referencing to capacity or lengthtimvisee-6/+6
2024-11-27Fill in a `BTreeSet::entry` exampleJosh Stone-1/+31
2024-11-27Add a tracking issue for `btree_set_entry`Josh Stone-20/+20
2024-11-27Add `BTreeSet` entry APIs to match `HashSet`Josh Stone-2/+500
* `fn get_or_insert(&mut self, value: T) -> &T` * `fn get_or_insert_with<Q: ?Sized, F>(&mut self, value: &Q, f: F) -> &T` * `fn entry(&mut self, value: T) -> Entry<'_, T, A>` (+ `Entry` APIs)
2024-11-27update cfgsBoxy-16/+9
2024-11-27replace placeholder versionBoxy-9/+9
2024-11-26Rollup merge of #133042 - cuviper:btreemap-insert_entry, r=AmanieuMichael Goulet-31/+76
btree: add `{Entry,VacantEntry}::insert_entry` This matches the recently-stabilized methods on `HashMap` entries. I've reused tracking issue #65225 for now, but we may want to split it.
2024-11-24fix `Allocator` method names in `alloc` free function docsm-4/+4
2024-11-24Auto merge of #132597 - lukas-code:btree-plug-leak, r=jhprattbors-2/+64
btree: don't leak value if destructor of key panics This PR fixes a regression from https://github.com/rust-lang/rust/pull/84904. The `BTreeMap` already attempts to handle panicking destructors of the key-value pairs by continuing to execute the remaining destructors after one destructor panicked. However, after #84904 the destructor of a value in a key-value pair gets skipped if the destructor of the key panics, only continuing with the next key-value pair. This PR reverts to the behavior before #84904 to also drop the corresponding value if the destructor of a key panics. This avoids potential memory leaks and can fix the soundness of programs that rely on the destructors being executed (even though this should not be relied upon, because the std collections currently do not guarantee that the remaining elements are dropped after a panic in a destructor). cc `@Amanieu` because you had opinions on panicking destructors
2024-11-20Make PointerLike opt-in as a traitMichael Goulet-0/+7
2024-11-20Rollup merge of #132732 - gavincrawford:as_ptr_attribute, r=UrgauJacob Pratt-0/+4
Use attributes for `dangling_pointers_from_temporaries` lint Checking for dangling pointers by function name isn't ideal, and leaves out certain pointer-returning methods that don't follow the `as_ptr` naming convention. Using an attribute for this lint cleans things up and allows more thorough coverage of other methods, such as `UnsafeCell::get()`.
2024-11-19UniqueRc: PinCoerceUnsized and DerefPureZachary S-3/+8
2024-11-19UniqueRc: comparisons and HashZachary S-0/+173
2024-11-19Rollup merge of #123947 - zopsicle:vec_deque-Iter-as_slices, r=AmanieuMatthias Krüger-0/+142
Add vec_deque::Iter::as_slices and friends Add the following methods, that work similarly to VecDeque::as_slices: - alloc::collections::vec_deque::Iter::as_slices - alloc::collections::vec_deque::IterMut::into_slices - alloc::collections::vec_deque::IterMut::as_slices - alloc::collections::vec_deque::IterMut::as_mut_slices Obtaining slices from a VecDeque iterator was not previously possible.