about summary refs log tree commit diff
path: root/library/alloc/src
AgeCommit message (Collapse)AuthorLines
2024-02-11Address ThinBox::try_new PR reviewDavid Tolnay-4/+3
2024-02-11fix incorrect doctestripytide-2/+2
2024-02-11improve `btree_cursors` functions documentationripytide-87/+130
2024-02-11Rollup merge of #117740 - majaha:format_docs, r=joshtriplettMatthias Krüger-0/+5
Add some links and minor explanatory comments to `std::fmt` I thought the documentation for the `#` flag could do with a link to the explanation of the `?xXbo` flags, because at that point they haven't been explained yet and it's a bit confusing. I also added that the `0` flag overrides the fill character and alignment flag, here's a [Rust Playgrond](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0d580b7b78b8a2d8c08a2fc7a936ef17) that shows what I mean.
2024-02-10Remove the link.Kevin Reid-4/+5
2024-02-10URL-encode chars in fragment.Kevin Reid-1/+1
2024-02-10Additional doc links and explanation of `Wake`.Kevin Reid-3/+9
This is intended to clarify: * That `Wake` exists and can be used instead of `RawWaker`. * How to construct a `Waker` when you are looking at `Wake` (which was previously only documented in the example).
2024-02-10Auto merge of #120712 - compiler-errors:async-closures-harmonize, r=oli-obkbors-0/+30
Harmonize `AsyncFn` implementations, make async closures conditionally impl `Fn*` traits This PR implements several changes to the built-in and libcore-provided implementations of `Fn*` and `AsyncFn*` to address two problems: 1. async closures do not implement the `Fn*` family traits, leading to breakage: https://crater-reports.s3.amazonaws.com/pr-120361/index.html 2. *references* to async closures do not implement `AsyncFn*`, as a consequence of the existing blanket impls of the shape `AsyncFn for F where F: Fn, F::Output: Future`. In order to fix (1.), we implement `Fn` traits appropriately for async closures. It turns out that async closures can: * always implement `FnOnce`, meaning that they're drop-in compatible with `FnOnce`-bound combinators like `Option::map`. * conditionally implement `Fn`/`FnMut` if they have no captures, which means that existing usages of async closures should *probably* work without breakage (crater checking this: https://github.com/rust-lang/rust/pull/120712#issuecomment-1930587805). In order to fix (2.), we make all of the built-in callables implement `AsyncFn*` via built-in impls, and instead adjust the blanket impls for `AsyncFn*` provided by libcore to match the blanket impls for `Fn*`.
2024-02-09Auto merge of #120676 - Mark-Simulacrum:bootstrap-bump, r=clubby789bors-2/+2
Bump bootstrap compiler to just-built 1.77 beta https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-02-08Reduce use of NonNull::new_unchecked in library/Ben Kimock-10/+11
2024-02-08Bump version placeholdersMark Rousskov-2/+2
2024-02-06Harmonize blanket implementations for AsyncFn* traitsMichael Goulet-0/+30
2024-02-05Rollup merge of #118960 - tvallotton:local_waker, r=Mark-SimulacrumMatthias Krüger-6/+182
Add LocalWaker and ContextBuilder types to core, and LocalWake trait to alloc. Implementation for #118959.
2024-02-05Rollup merge of #113833 - WiktorPrzetacznik:master, r=dtolnayMatthias Krüger-8/+8
`std::error::Error` -> Trait Implementations: lifetimes consistency improvement This cleans up `std::error::Error` trait implementations lifetime inconsistency (`'static` -> `'a`) **Reasoning:** Trait implementations for `std::error::Error`, like: `impl From<&str> for Box<dyn Error + 'static, Global>` `impl<'a> From<&str> for Box<dyn Error + Sync + Send + 'a, Global>` use different lifetime annotations misleadingly implying using different life annotations here is a conscious, nonaccidental decision. [(Related forum discussion here)](https://users.rust-lang.org/t/confusing-std-error-source-code/97011/5?u=wiktor)
2024-02-05Rollup merge of #120458 - rytheo:cstr-conversion-doc, r=Mark-SimulacrumMatthias Krüger-0/+2
Document `&CStr` to `CString` conversion Related to #51430
2024-01-31Rollup merge of #120355 - the8472:doc-vec-fromiter, r=cuviperNadrieril-0/+44
document `FromIterator for Vec` allocation behaviors [t-libs discussion](https://rust-lang.zulipchat.com/#narrow/stream/259402-t-libs.2Fmeetings/topic/Meeting.202024-01-24/near/417686526) about #120091 didn't reach a strong consensus, but it was agreed that if we keep the current behavior it should at least be documented even though it is an implementation detail. The language is intentionally non-committal. The previous (non-existent) documentation permits a lot of implementation leeway and we want retain that. In some cases we even must retain it to be able to rip out some code paths that rely on unstable features.
2024-01-30Apply suggestions from code reviewthe8472-12/+11
Co-authored-by: Josh Stone <cuviper@gmail.com>
2024-01-30document `FromIterator for Vec` allocation behaviorsThe 8472-0/+45
2024-01-30Fix BTreeMap's Cursor::remove_{next,prev}Amanieu d'Antras-0/+12
These would incorrectly leave `current` as `None` after a failed attempt to remove an element (due to the cursor already being at the start/end).
2024-01-30Rollup merge of #120445 - Nemo157:arc-plug, r=Mark-SimulacrumGuillaume Gomez-29/+80
Fix some `Arc` allocator leaks This doesn't matter for the stable `Global` allocator as it is a ZST singleton, but other allocators may rely on all instances being dropped.
2024-01-29Rollup merge of #120266 - steffahn:a_rc_into_inner_docs, r=Mark-SimulacrumDylan DPC-5/+12
Improve documentation for [A]Rc::into_inner General improvements, and also aims to better encourage the reader to actually check out Arc::try_unwrap. This addresses concerns from https://github.com/rust-lang/rust/issues/106894#issuecomment-1905627234. Rendered: ![Screenshot_20240123_114436](https://github.com/rust-lang/rust/assets/3986214/68896d62-13e0-4f3a-8073-91d8e77c5554) ![Screenshot_20240123_114455](https://github.com/rust-lang/rust/assets/3986214/dc58e4bd-dd7f-40b1-bc50-fd6200dde593)
2024-01-28Document From<&CStr> for CStringRyan Lowe-0/+2
2024-01-28Fix some `Arc` allocator leaksWim Looman-29/+80
This doesn't matter for the stable `Global` allocator as it is a ZST singleton, but other allocators may rely on all instances being dropped.
2024-01-28Fix doctestJohn-John Tedro-4/+6
2024-01-28Replicate documentation in {Rc,Arc}::from_raw_inJohn-John Tedro-16/+66
2024-01-28Fix doctestJohn-John Tedro-4/+4
2024-01-28Tidy upJohn-John Tedro-2/+2
2024-01-28Add examples for unsized {Rc,Arc}::from_rawJohn-John Tedro-0/+28
2024-01-28Document requirements for unsized {Rc,Arc}::from_rawJohn-John Tedro-12/+28
2024-01-26Rollup merge of #113489 - tguichaoua:cow_from_array, r=dtolnayMatthias Krüger-0/+13
impl `From<&[T; N]>` for `Cow<[T]>` Implement `From<&[T; N]>` for `Cow<[T]>` to simplify its usage in the following example. ```rust fn foo(data: impl Into<Cow<'static, [&'static str]>>) { /* ... */ } fn main() { foo(vec!["hello", "world"]); foo(&["hello", "world"]); // Error: the trait `From<&[&str; 2]>` is not implemented for `Cow<'static, [&'static str]>` foo(&["hello", "world"] as &[_]); // Explicit convertion into a slice is required } ```
2024-01-26Rollup merge of #103522 - Dylan-DPC:76118/array-methods-stab, r=dtolnayMatthias Krüger-1/+0
stabilise array methods Closes #76118 Stabilises the remaining array methods FCP is yet to be carried out for this There wasn't a clear consensus on the naming, but all the other alternatives had some flaws as discussed in the tracking issue and there was a silence on this issue for a year
2024-01-26Rollup merge of #120372 - bjorn3:fix_outdated_comment, r=NilstriebMatthias Krüger-2/+1
Fix outdated comment on Box Caught by `@vi` in https://github.com/rust-lang/rust/pull/113960#discussion_r1454278520
2024-01-26Rollup merge of #119917 - Zalathar:split-off, r=cuviperMatthias Krüger-8/+0
Remove special-case handling of `vec.split_off(0)` #76682 added special handling to `Vec::split_off` for the case where `at == 0`. Instead of copying the vector's contents into a freshly-allocated vector and returning it, the special-case code steals the old vector's allocation, and replaces it with a new (empty) buffer with the same capacity. That eliminates the need to copy the existing elements, but comes at a surprising cost, as seen in #119913. The returned vector's capacity is no longer determined by the size of its contents (as would be expected for a freshly-allocated vector), and instead uses the full capacity of the old vector. In cases where the capacity is large but the size is small, that results in a much larger capacity than would be expected from reading the documentation of `split_off`. This is especially bad when `split_off` is called in a loop (to recycle a buffer), and the returned vectors have a wide variety of lengths. I believe it's better to remove the special-case code, and treat `at == 0` just like any other value: - The current documentation states that `split_off` returns a “newly allocated vector”, which is not actually true in the current implementation when `at == 0`. - If the value of `at` could be non-zero at runtime, then the caller has already agreed to the cost of a full memcpy of the taken elements in the general case. Avoiding that copy would be nice if it were close to free, but the different handling of capacity means that it is not. - If the caller specifically wants to avoid copying in the case where `at == 0`, they can easily implement that behaviour themselves using `mem::replace`. Fixes #119913.
2024-01-26Rollup merge of #117678 - niklasf:stabilize-slice_group_by, r=dtolnayMatthias Krüger-3/+2
Stabilize `slice_group_by` Renamed "group by" to "chunk by" a per #80552. Newly stable items: * `core::slice::ChunkBy` * `core::slice::ChunkByMut` * `[T]::chunk` * `[T]::chunk_by` Closes #80552.
2024-01-26Fix outdated comment on Boxbjorn3-2/+1
2024-01-26Rollup merge of #119466 - Sky9x:str_from_raw_parts, r=dtolnayMatthias Krüger-0/+2
Initial implementation of `str::from_raw_parts[_mut]` ACP (accepted): rust-lang/libs-team#167 Tracking issue: #119206 Thanks to ``@Kixiron`` for previous work on this (#107207) ``@rustbot`` label +T-libs-api -T-libs r? ``@thomcc`` Closes #107207.
2024-01-25Export core::str::from_raw_parts{,_mut} into alloc::str and std::strDavid Tolnay-0/+2
2024-01-25Rollup merge of #118208 - Amanieu:btree_cursor2, r=dtolnayMatthias Krüger-392/+549
Rewrite the BTreeMap cursor API using gaps Tracking issue: #107540 Currently, a `Cursor` points to a single element in the tree, and allows moving to the next or previous element while mutating the tree. However this was found to be confusing and hard to use. This PR completely refactors cursors to instead point to a gap between two elements in the tree. This eliminates the need for a "ghost" element that exists after the last element and before the first one. Additionally, `upper_bound` and `lower_bound` now have a much clearer meaning. The ability to mutate keys is also factored out into a separate `CursorMutKey` type which is unsafe to create. This makes the API easier to use since it avoids duplicated versions of each method with and without key mutation. API summary: ```rust impl<K, V> BTreeMap<K, V> { fn lower_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V> where K: Borrow<Q> + Ord, Q: Ord; fn lower_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V> where K: Borrow<Q> + Ord, Q: Ord; fn upper_bound<Q>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V> where K: Borrow<Q> + Ord, Q: Ord; fn upper_bound_mut<Q>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V> where K: Borrow<Q> + Ord, Q: Ord; } struct Cursor<'a, K: 'a, V: 'a>; impl<'a, K, V> Cursor<'a, K, V> { fn next(&mut self) -> Option<(&'a K, &'a V)>; fn prev(&mut self) -> Option<(&'a K, &'a V)>; fn peek_next(&self) -> Option<(&'a K, &'a V)>; fn peek_prev(&self) -> Option<(&'a K, &'a V)>; } struct CursorMut<'a, K: 'a, V: 'a>; impl<'a, K, V> CursorMut<'a, K, V> { fn next(&mut self) -> Option<(&K, &mut V)>; fn prev(&mut self) -> Option<(&K, &mut V)>; fn peek_next(&mut self) -> Option<(&K, &mut V)>; fn peek_prev(&mut self) -> Option<(&K, &mut V)>; unsafe fn insert_after_unchecked(&mut self, key: K, value: V); unsafe fn insert_before_unchecked(&mut self, key: K, value: V); fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>; fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>; fn remove_next(&mut self) -> Option<(K, V)>; fn remove_prev(&mut self) -> Option<(K, V)>; fn as_cursor(&self) -> Cursor<'_, K, V>; unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A>; } struct CursorMutKey<'a, K: 'a, V: 'a>; impl<'a, K, V> CursorMut<'a, K, V> { fn next(&mut self) -> Option<(&mut K, &mut V)>; fn prev(&mut self) -> Option<(&mut K, &mut V)>; fn peek_next(&mut self) -> Option<(&mut K, &mut V)>; fn peek_prev(&mut self) -> Option<(&mut K, &mut V)>; unsafe fn insert_after_unchecked(&mut self, key: K, value: V); unsafe fn insert_before_unchecked(&mut self, key: K, value: V); fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>; fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError>; fn remove_next(&mut self) -> Option<(K, V)>; fn remove_prev(&mut self) -> Option<(K, V)>; fn as_cursor(&self) -> Cursor<'_, K, V>; unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A>; } struct UnorderedKeyError; ```
2024-01-23Auto merge of #119433 - taiki-e:rc-uninit-ref, r=Nilstriebbors-20/+25
rc,sync: Do not create references to uninitialized values Closes #119241 r? `@RalfJung`
2024-01-23Improve documentation for [A]Rc::into_innerFrank Steffahn-5/+12
General improvements, and also aims to better encourage the reader to actually check out Arc::try_unwrap.
2024-01-23Auto merge of #119892 - joboet:libs_use_assert_unchecked, r=Nilstrieb,cuviperbors-10/+12
Use `assert_unchecked` instead of `assume` intrinsic in the standard library Now that a public wrapper for the `assume` intrinsic exists, we can use it in the standard library. CC #119131
2024-01-22Rollup merge of #119801 - zachs18:zachs18-patch-1, r=steffahn,NilstriebMatthias Krüger-2/+2
Fix deallocation with wrong allocator in (A)Rc::from_box_in Deallocate the `Box` with the original allocator (via `&A`), not `Global`. Fixes #119749 <details> <summary>Example code with error and Miri output</summary> (Note that this UB is not observable on stable, because the only usable allocator on stable is `Global` anyway.) Code ([playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=96193c2c6a1912d7f669fbbe39174b09)): ```rs #![feature(allocator_api)] use std::alloc::System; // uncomment one of these use std::rc::Rc; //use std::sync::Arc as Rc; fn main() { let x: Box<[u32], System> = Box::new_in([1,2,3], System); let _: Rc<[u32], System> = Rc::from(x); } ``` Miri output: ```rs error: Undefined Behavior: deallocating alloc904, which is C heap memory, using Rust heap deallocation operation --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14 | 117 | unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ deallocating alloc904, which is C heap memory, using Rust heap deallocation operation | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = note: BACKTRACE: = note: inside `std::alloc::dealloc` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14: 117:64 = note: inside `<std::alloc::Global as std::alloc::Allocator>::deallocate` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:254:22: 254:51 = note: inside `<std::boxed::Box<std::mem::ManuallyDrop<[u32]>> as std::ops::Drop>::drop` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1244:17: 1244:66 = note: inside `std::ptr::drop_in_place::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>> - shim(Some(std::boxed::Box<std::mem::ManuallyDrop<[u32]>>))` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:507:1: 507:56 = note: inside `std::mem::drop::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:992:24: 992:25 = note: inside `std::rc::Rc::<[u32], std::alloc::System>::from_box_in` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:1928:13: 1928:22 = note: inside `<std::rc::Rc<[u32], std::alloc::System> as std::convert::From<std::boxed::Box<[u32], std::alloc::System>>>::from` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:2504:9: 2504:27 note: inside `main` --> src/main.rs:10:32 | 10 | let _: Rc<[u32], System> = Rc::from(x); | ^^^^^^^^^^^ note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error ``` </details>
2024-01-21Rollup merge of #120180 - Zalathar:vec-split-off-alternatives, r=dtolnayMatthias Krüger-0/+6
Document some alternatives to `Vec::split_off` One of the discussion points that came up in #119917 is that some people use `Vec::split_off` in cases where they probably shouldn't, because the alternatives (like `mem::take`) are hard to discover. This PR adds some suggestions to the documentation of `split_off` that should point people towards alternatives that might be more appropriate for their use-case. I've deliberately tried to keep these changes as simple and uncontroversial as possible, so that they don't depend on how the team decides to handle the concerns raised in #119917. That's why I haven't touched the existing documentation for `split_off`, and haven't added links to `split_off` to the documentation of other methods.
2024-01-21Rollup merge of #120145 - the8472:fix-inplace-dest-drop, r=cuviperMatthias Krüger-13/+25
fix: Drop guard was deallocating with the incorrect size InPlaceDstBufDrop holds onto the allocation before the shrinking happens which means it must deallocate the destination elements but the source allocation. Thanks `@cuviper` for spotting this.
2024-01-21Document some alternatives to `Vec::split_off`Zalathar-0/+6
2024-01-20Rollup merge of #120116 - the8472:only-same-alignments, r=cuviperGuillaume Gomez-12/+15
Remove alignment-changing in-place collect This removes the alignment-changing in-place collect optimization introduced in #110353 Currently stable users can't benefit from the optimization because GlobaAlloc doesn't support alignment-changing realloc and neither do most posix allocators. So in practice it has a negative impact on performance. Explanation from https://github.com/rust-lang/rust/issues/120091#issuecomment-1899071681: > > You mention that in case of alignment mismatch -- when the new alignment is less than the old -- the implementation calls `mremap`. > > I was trying to note that this isn't really the case in practice, due to the semantics of Rust's allocator APIs. The only use of the allocator within the `in_place_collect` implementation itself is [a call to `Allocator::shrink()`](https://github.com/rust-lang/rust/blob/db7125f008cfd72e8951c9a863178956e2cbacc3/library/alloc/src/vec/in_place_collect.rs#L299-L303), which per its documentation [allows decreasing the required alignment](https://doc.rust-lang.org/1.75.0/core/alloc/trait.Allocator.html). However, in stable Rust, the only available `Allocator` is [`Global`](https://doc.rust-lang.org/1.75.0/alloc/alloc/struct.Global.html), which delegates to the registered `GlobalAlloc`. Since `GlobalAlloc::realloc()` [cannot change the required alignment](https://doc.rust-lang.org/1.75.0/core/alloc/trait.GlobalAlloc.html#method.realloc), the implementation of [`<Global as Allocator>::shrink()`](https://github.com/rust-lang/rust/blob/db7125f008cfd72e8951c9a863178956e2cbacc3/library/alloc/src/alloc.rs#L280-L321) must fall back to creating a brand-new allocation, `memcpy`ing the data into it, and freeing the old allocation, whenever the alignment doesn't remain exactly the same. > > Therefore, the underlying allocator, provided by libc or some other source, has no opportunity to internally `mremap()` the data when the alignment is changed, since it has no way of knowing that the allocation is the same.
2024-01-20doc: fix some doctests after rebaseTomás Vallotton-2/+2
2024-01-20refactor: make waker mandatory.Tomás Vallotton-6/+10
This also removes * impl From<&Context> for ContextBuilder * Context::try_waker() The from implementation is removed because now that wakers are always supported, there are less incentives to override the current context. Before, the incentive was to add Waker support to a reactor that didn't have any.
2024-01-20fix: Apply suggestions from code reviewtvallotton-3/+3
Co-authored-by: Mark Rousskov <mark.simulacrum@gmail.com>
2024-01-20chore: fix ci failuresTomás Vallotton-1/+1