about summary refs log tree commit diff
path: root/library/alloc
AgeCommit message (Collapse)AuthorLines
2024-02-13Rollup merge of #120967 - LeoDog896:master, r=cuviperMatthias Krüger-0/+16
docs: mention round-to-even in precision formatting _Note_: Not quite sure exactly how to format this documentation. Mentions round-to-even usage in precision formatting. (should this also be mentioned in `f64::round`?) From https://github.com/rust-lang/rust/issues/70336
2024-02-12docs: use correct link, use secondary exampleTristan F-2/+5
2024-02-12Rollup merge of #120936 - ripytide:master, r=AmanieuMatthias Krüger-85/+128
improve `btree_cursors` functions documentation As suggested by ``@Amanieu`` (and others) in #107540 (https://github.com/rust-lang/rust/issues/107540#issuecomment-1937760547) Improvements: - Document exact behavior of `{upper/lower}_bound{,_mut}` with each of the three `Bound` types using unambigous words `{greatest,greater,smallest,smaller,before,after}`. - Added another doc-example for the `Bound::Unbounded` for each of the methods - Changed doc-example to use From<[T; N]> rather than lots of `insert()`s which requires a mutable map which clutters the example when `mut` may not be required for the method (such as for `{upper,lower}_bound`. - Removed `# Panics` section from `insert_{before,after}` methods since they were changed to return an error instead a while ago. - Reworded some phrases to be more consistent with the more regular `BTreeMap` methods such as calling entries "key-value" rather than "element"s.
2024-02-12style: fmtTristan F.-1/+1
2024-02-12docs: mention round-to-even in precision formattingTristan F-0/+13
2024-02-11Rollup merge of #110483 - tleibert:thin-box-try-new, r=dtolnayMatthias Krüger-0/+64
Create try_new function for ThinBox The `allocator_api` feature has proven very useful in my work in the FreeBSD kernel. I've found a few places where a `ThinBox` #92791 would be useful, but it must be able to be fallibly allocated for it to be used in the kernel. This PR proposes a change to add such a constructor for ThinBox. ACP: https://github.com/rust-lang/libs-team/issues/213
2024-02-11fix intra-doc linksripytide-12/+12
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-14/+18
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-12/+10
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-22Auto merge of #120196 - matthiaskrgr:rollup-id2zocf, r=matthiaskrgrbors-13/+31
Rollup of 8 pull requests Successful merges: - #120005 (Update Readme) - #120045 (Un-hide `iter::repeat_n`) - #120128 (Make stable_mir::with_tables sound) - #120145 (fix: Drop guard was deallocating with the incorrect size) - #120158 (`rustc_mir_dataflow`: Restore removed exports) - #120167 (Capture the rationale for `-Zallow-features=` in bootstrap.py) - #120174 (Warn users about limited review for tier 2 and 3 code) - #120180 (Document some alternatives to `Vec::split_off`) Failed merges: - #120171 (Fix assume and assert in jump threading) r? `@ghost` `@rustbot` modify labels: rollup