about summary refs log tree commit diff
path: root/library/alloc
AgeCommit message (Collapse)AuthorLines
2022-01-11Partially stabilize `maybe_uninit_extra`Miguel Ojeda-1/+0
This covers: impl<T> MaybeUninit<T> { pub unsafe fn assume_init_read(&self) -> T { ... } pub unsafe fn assume_init_drop(&mut self) { ... } } It does not cover the const-ness of `write` under `const_maybe_uninit_write` nor the const-ness of `assume_init_read` (this commit adds `const_maybe_uninit_assume_init_read` for that). FCP: https://github.com/rust-lang/rust/issues/63567#issuecomment-958590287. Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2022-01-11Auto merge of #92070 - rukai:replace_vec_into_iter_with_array_into_iter, ↵bors-39/+38
r=Mark-Simulacrum Replace usages of vec![].into_iter with [].into_iter `[].into_iter` is idiomatic over `vec![].into_iter` because its simpler and faster (unless the vec is optimized away in which case it would be the same) So we should change all the implementation, documentation and tests to use it. I skipped: * `src/tools` - Those are copied in from upstream * `src/test/ui` - Hard to tell if `vec![].into_iter` was used intentionally or not here and not much benefit to changing it. * any case where `vec![].into_iter` was used because we specifically needed a `Vec::IntoIter<T>` * any case where it looked like we were intentionally using `vec![].into_iter` to test it.
2022-01-09Clarify explicitly that BTree{Map,Set} are ordered.Brennan Vincent-4/+10
2022-01-09Compute most of Public/Exported access level in rustc_resolveLamb-0/+3
Mak DefId to AccessLevel map in resolve for export hir_id to accesslevel in resolve and applied in privacy using local def id removing tracing probes making function not recursive and adding comments Move most of Exported/Public res to rustc_resolve moving public/export res to resolve fix missing stability attributes in core, std and alloc move code to access_levels.rs return for some kinds instead of going through them Export correctness, macro changes, comments add comment for import binding add comment for import binding renmae to access level visitor, remove comments, move fn as closure, remove new_key fmt fix rebase fix rebase fmt fmt fix: move macro def to rustc_resolve fix: reachable AccessLevel for enum variants fmt fix: missing stability attributes for other architectures allow unreachable pub in rustfmt fix: missing impl access level + renaming export to reexport Missing impl access level was found thanks to a test in clippy
2022-01-09eplace usages of vec![].into_iter with [].into_iterLucas Kent-39/+38
2022-01-08Auto merge of #92068 - fee1-dead:libcore2021, r=m-ou-sebors-4/+1
Switch all libraries to the 2021 edition The fix for https://github.com/rust-lang/rust/issues/88638#issuecomment-996620107 is to simply add const-stability for these functions. r? `@m-ou-se` Closes #88638.
2022-01-08Change panic::update_hook to simplify usageBadel2-6/+4
And to remove possibility of panics while changing the panic handler, because that resulted in a double panic.
2022-01-07Implement panic::update_hookBadel2-6/+8
2022-01-06remove unused ExtendDefault structFrank Steffahn-10/+0
2022-01-06Add diagnostic items for macrosAlex Macleod-0/+1
2022-01-05Rollup merge of #92388 - SpriteOvO:master, r=Mark-SimulacrumMatthias Krüger-1/+1
Fix a minor mistake in `String::try_reserve_exact` examples The examples of `String::try_reserve_exact` didn't actually use `try_reserve_exact`, which was probably a minor mistake, and this PR fixed it.
2022-01-05Rollup merge of #92092 - saethlin:fix-sort-guards-sb, r=danielhenrymantillaMatthias Krüger-3/+3
Drop guards in slice sorting derive src pointers from &mut T, which is invalidated by interior mutation in comparison I tried to run https://github.com/rust-lang/miri-test-libstd on `alloc` with `-Zmiri-track-raw-pointers`, and got a failure on the test `slice::panic_safe`. The test failure has nothing to do with panic safety, it's from how the test tests for panic safety. I minimized the test failure into this very silly program: ```rust use std::cell::Cell; use std::cmp::Ordering; #[derive(Clone)] struct Evil(Cell<usize>); fn main() { let mut input = vec![Evil(Cell::new(0)); 3]; // Hits the bug pattern via CopyOnDrop in core input.sort_unstable_by(|a, _b| { a.0.set(0); Ordering::Less }); // Hits the bug pattern via InsertionHole in alloc input.sort_by(|_a, b| { b.0.set(0); Ordering::Less }); } ``` To fix this, I'm just removing the mutability/uniqueness where it wasn't required.
2022-01-04Clarify that ordering is unspecifiedMario Carneiro-0/+2
2022-01-04Update wordingMario Carneiro-3/+3
2022-01-04Rollup merge of #91884 - woppopo:const_box, r=oli-obkMatthias Krüger-32/+225
Constify `Box<T, A>` methods Tracking issue: none yet Most of the methods bounded on `~const`. `intrinsics::const_eval_select` is used for handling an allocation error. <details><summary>Constified API</summary> ```rust impl<T, A: Allocator> Box<T, A> { pub const fn new_in(x: T, alloc: A) -> Self where A: ~const Allocator + ~const Drop; pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError> where T: ~const Drop, A: ~const Allocator + ~const Drop; pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> where A: ~const Allocator + ~const Drop; pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> where A: ~const Allocator + ~const Drop; pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> where A: ~const Allocator + ~const Drop; pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> where A: ~const Allocator + ~const Drop; pub const fn pin_in(x: T, alloc: A) -> Pin<Self> where A: 'static, A: 'static + ~const Allocator + ~const Drop, pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A>; pub const fn into_inner(boxed: Self) -> T where Self: ~const Drop, } impl<T, A: Allocator> Box<MaybeUninit<T>, A> { pub const unsafe fn assume_init(self) -> Box<T, A>; pub const fn write(mut boxed: Self, value: T) -> Box<T, A>; pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self; pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A); pub const fn into_unique(b: Self) -> (Unique<T>, A); pub const fn allocator(b: &Self) -> &A; pub const fn leak<'a>(b: Self) -> &'a mut T where A: 'a; pub const fn into_pin(boxed: Self) -> Pin<Self> where A: 'static; } unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> const Drop for Box<T, A>; impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>> where A: 'static; impl<T: ?Sized, A: Allocator> const Deref for Box<T, A>; impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A>; impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static; ``` </details> <details><summary>Example</summary> ```rust pub struct ConstAllocator; unsafe impl const Allocator for ConstAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { unsafe { let ptr = core::intrinsics::const_allocate(layout.size(), layout.align()); Ok(NonNull::new_unchecked(ptr as *mut [u8; 0] as *mut [u8])) } } unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) { /* do nothing */ } fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { self.allocate(layout) } unsafe fn grow( &self, _ptr: NonNull<u8>, _old_layout: Layout, _new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unimplemented!() } unsafe fn grow_zeroed( &self, _ptr: NonNull<u8>, _old_layout: Layout, _new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unimplemented!() } unsafe fn shrink( &self, _ptr: NonNull<u8>, _old_layout: Layout, _new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { unimplemented!() } fn by_ref(&self) -> &Self where Self: Sized, { self } } #[test] fn const_box() { const VALUE: u32 = { let mut boxed = Box::new_in(1u32, ConstAllocator); assert!(*boxed == 1); *boxed = 42; assert!(*boxed == 42); *boxed }; assert!(VALUE == 42); } ``` </details>
2022-01-04Fix a compile error when no_global_oom_handlingwoppopo-1/+1
2022-01-04Add tracking issues (`const_box`, `const_alloc_error`)woppopo-25/+26
2022-01-01Rollup merge of #92463 - thomcc:thats-not-how-its-pronounced, r=joshtriplettMatthias Krüger-1/+1
Remove pronunciation guide from Vec<T> I performed an extremely scientific poll on twitter, and determined this is not how it's pronounced: https://twitter.com/at_tcsc/status/1476643344285581315
2022-01-01Rollup merge of #92097 - saethlin:split-without-deref, r=the8472Matthias Krüger-2/+7
Implement split_at_spare_mut without Deref to a slice so that the spare slice is valid ~I'm not sure I understand what's going on here correctly. And I'm pretty sure this safety comment needs to be changed. I'm just referring to the same thing that `as_mut_ptr_range` does.~ (Thanks `@RalfJung` for the guidance and clearing things up) I tried to run https://github.com/rust-lang/miri-test-libstd on alloc with -Zmiri-track-raw-pointers, and got a failure on the test `vec::test_extend_from_within`. I minimized the test failure into this program: ```rust #![feature(vec_split_at_spare)] fn main() { Vec::<i32>::with_capacity(1).split_at_spare_mut(); } ``` The problem is that the existing implementation is actually getting a pointer range where both pointers are derived from the initialized region of the Vec's allocation, but we need the second one to be valid for the region between len and capacity. (thanks Ralf for clearing this up)
2021-12-31Clarify safety commentBen Kimock-0/+2
2021-12-31Remove pronunciation guide from Vec<T>Thom Chiovoloni-1/+1
2021-12-30use generic params for arc_new_cyclicbdbai-2/+8
2021-12-29fix typo in btree/vec doc: Self -> selfVeeupup-4/+4
2021-12-29Fix a minor mistake in `String::try_reserve_exact` examplesSprite-1/+1
2021-12-24Remove `maybe_uninit_extra` feature from Vec docsShadlock0133-2/+2
In `Vec`, two doc tests are using `MaybeUninit::write` , stabilized in 1.55. This makes docs' usage of `maybe_uninit_extra` feature unnecessary.
2021-12-24Auto merge of #92220 - nnethercote:RawVec-dont-recompute-capacity, ↵bors-17/+18
r=joshtriplett RawVec: don't recompute capacity after allocating. Currently it sets the capacity to `ptr.len() / mem::size_of::<T>()` after any buffer allocation/reallocation. This would be useful if allocators ever returned a `NonNull<[u8]>` with a size larger than requested. But this never happens, so it's not useful. Removing this slightly reduces the size of generated LLVM IR, and slightly speeds up the hot path of `RawVec` growth. r? `@ghost`
2021-12-23Bless a few testsDeadbeef-3/+0
2021-12-23Constify `Box<T, A>` methodswoppopo-32/+224
2021-12-23Switch all libraries to the 2021 editionDeadbeef-1/+1
2021-12-23Rollup merge of #88858 - spektom:to_lower_upper_rev, r=dtolnayMatthias Krüger-0/+31
Allow reverse iteration of lowercase'd/uppercase'd chars The PR implements `DoubleEndedIterator` trait for `ToLowercase` and `ToUppercase`. This enables reverse iteration of lowercase/uppercase variants of character sequences. One of use cases: determining whether a char sequence is a suffix of another one. Example: ```rust fn endswith_ignore_case(s1: &str, s2: &str) -> bool { for eob in s1 .chars() .flat_map(|c| c.to_lowercase()) .rev() .zip_longest(s2.chars().flat_map(|c| c.to_lowercase()).rev()) { match eob { EitherOrBoth::Both(c1, c2) => { if c1 != c2 { return false; } } EitherOrBoth::Left(_) => return true, EitherOrBoth::Right(_) => return false, } } true } ```
2021-12-22RawVec: don't recompute capacity after allocating.Nicholas Nethercote-17/+18
Currently it sets the capacity to `ptr.len() / mem::size_of::<T>()` after any buffer allocation/reallocation. This would be useful if allocators ever returned a `NonNull<[u8]>` with a size larger than requested. But this never happens, so it's not useful. Removing this slightly reduces the size of generated LLVM IR, and slightly speeds up the hot path of `RawVec` growth.
2021-12-19Implement split_at_spare_mut directlyBen Kimock-2/+5
The previous implementation used slice::as_mut_ptr_range to derive the pointer for the spare capacity slice. This is invalid, because that pointer is derived from the initialized region, so it does not have provenance over the uninitialized region.
2021-12-19paniced -> panickedr00ster-1/+1
2021-12-19Rollup merge of #92071 - ajtribick:patch-1, r=the8472Matthias Krüger-5/+5
Update example code for Vec::splice to change the length The current example for `Vec::splice` illustrates the replacement of a section of length 2 with a new section of length 2. This isn't a particularly interesting case for splice, and makes it look a bit like a shorthand for the kind of manipulations that could be done with a mutable slice. In order to provide a stronger example, this updates the example to use different lengths for the source and destination regions, and uses a slice from the middle of the vector to illustrate that this does not necessarily have to be at the beginning or the end. Resolves #92067
2021-12-18Derive src pointers in sort drop guards from &TBen Kimock-3/+3
The src pointers in CopyOnDrop and InsertionHole used to be *mut T, and were derived via automatic conversion from &mut T. According to Stacked Borrows 2.1, this means that those pointers become invalidated by interior mutation in the comparison function. But there's no need for mutability in this code path. Thus, we can change the drop guards to use *const and derive those from &T.
2021-12-18Update example code for Vec::splice to change the lengthajtribick-5/+5
2021-12-18docs: fix typoSzilárd Parrag-1/+1
Add missing `'s` to ` Let check it out.`
2021-12-16Auto merge of #91527 - the8472:retain-opt, r=dtolnaybors-34/+46
Optimize `vec::retain` performance This simply moves the loops into the inner function which leads to better results. ``` old: test vec::bench_retain_100000 ... bench: 203,828 ns/iter (+/- 2,101) test vec::bench_retain_iter_100000 ... bench: 63,324 ns/iter (+/- 12,305) test vec::bench_retain_whole_100000 ... bench: 42,989 ns/iter (+/- 291) new: test vec::bench_retain_100000 ... bench: 42,180 ns/iter (+/- 451) test vec::bench_retain_iter_100000 ... bench: 65,167 ns/iter (+/- 11,971) test vec::bench_retain_whole_100000 ... bench: 33,736 ns/iter (+/- 12,404) ``` Measured on x86_64-unknown-linux-gnu, Zen2 Fixes #91497
2021-12-15Auto merge of #91962 - matthiaskrgr:rollup-2g082jw, r=matthiaskrgrbors-2/+2
Rollup of 7 pull requests Successful merges: - #91880 (fix clippy::single_char_pattern perf findings) - #91885 (Remove `in_band_lifetimes` from `rustc_codegen_ssa`) - #91898 (Make `TyS::is_suggestable` check for non-suggestable types structually) - #91915 (Add another regression test for unnormalized fn args with Self) - #91916 (Fix a bunch of typos) - #91918 (Constify `bool::then{,_some}`) - #91920 (Use `tcx.def_path_hash` in `ExistentialPredicate.stable_cmp`) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2021-12-15Rollup merge of #91916 - steffahn:fix-typos, r=dtolnayMatthias Krüger-2/+2
Fix a bunch of typos I hope that none of these files is not supposed to be modified. FYI, I opened separate PRs for typos in submodules, in the respective repositories * https://github.com/rust-lang/stdarch/pull/1267 * https://github.com/rust-lang/backtrace-rs/pull/455
2021-12-15Rollup merge of #90521 - jhpratt:stabilize-destructuring_assignment, ↵Matthias Krüger-1/+1
r=jackh726,pnkfelix Stabilize `destructuring_assignment` Closes #71126 - [Stabilization report](https://github.com/rust-lang/rust/issues/71126#issuecomment-941148058) - [Completed FCP](https://github.com/rust-lang/rust/issues/71126#issuecomment-954914819) `@rustbot` label +F-destructuring-assignment +T-lang Also needs +relnotes but I don't have permission to add that tag.
2021-12-14Stabilize `destructuring_assignment`Jacob Pratt-1/+1
2021-12-15Auto merge of #91945 - matthiaskrgr:rollup-jszf9zp, r=matthiaskrgrbors-1/+0
Rollup of 7 pull requests Successful merges: - #90939 (Tweak errors coming from `for`-loop, `?` and `.await` desugaring) - #91859 (Iterator::cycle() — document empty iterator special case) - #91868 (Use `OutputFilenames` to generate output file for `-Zllvm-time-trace`) - #91870 (Revert setting a default for the MACOSX_DEPLOYMENT_TARGET env var for linking) - #91881 (Stabilize `iter::zip`) - #91882 (Remove `in_band_lifetimes` from `rustc_typeck`) - #91940 (Update cargo) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2021-12-14Stabilize iter::zip.PFPoitras-1/+0
2021-12-14Rollup merge of #89825 - martinvonz:split-inclusive-empty, r=m-ou-seMatthias Krüger-4/+4
Make split_inclusive() on an empty slice yield an empty output `[].split_inclusive()` currently yields a single, empty slice. That's different from `"".split_inslusive()`, which yields no output at all. I think that makes the slice version harder to use. The case where I ran into this bug was when writing code for generating a diff between two slices of bytes. I wanted to prefix removed lines with "-" and a added lines with "+". Due to `split_inclusive()`'s current behavior, that means that my code prints just a "-" or "+" for empty files. I suspect most existing callers have similar "bugs" (which would be fixed by this patch). Closes #89716.
2021-12-14Fix a bunch of typosFrank Steffahn-2/+2
2021-12-14Rollup merge of #91529 - TennyZhuang:try_reserve_binary_heap, r=yaahcMatthias Krüger-0/+79
add BinaryHeap::try_reserve and BinaryHeap::try_reserve_exact `try_reserve` of many collections were stablized in https://github.com/rust-lang/rust/pull/87993 in 1.57.0. Add `try_reserve` for the rest collections such as `BinaryHeap` should be not controversial.
2021-12-14Auto merge of #91680 - saethlin:spare_capacity_mut-in-join, r=dtolnaybors-2/+10
Use spare_capacity_mut instead of invalid unchecked indexing when joining str This is a fix for https://github.com/rust-lang/rust/issues/91574 I think in general I'd prefer to see this code implemented with raw pointers or `MaybeUninit::write_slice`, but there's existing code in here based on copying from slice to slice, so converting everything from `&[T]` to `&[MaybeUninit<T>]` is less disruptive.
2021-12-13Stabilize arc_new_cyclicbdbai-25/+58
2021-12-13Rollup merge of #91749 - ssomers:btree_comments, r=Mark-SimulacrumMatthias Krüger-55/+58
BTree: improve public descriptions and comments BTreeSet has always used the term "value" next to and meaning the same thing as "elements" (in the mathematical sense but also used for key-value pairs in BTreeMap), while in the BTreeMap sense these "values" are known as "keys" and definitely not "values". Today I had enough of that. r? `@Mark-Simulacrum`