about summary refs log tree commit diff
path: root/library/alloc
AgeCommit message (Collapse)AuthorLines
2022-04-15Auto merge of #95224 - mjbshaw:patch-1, r=yaahcbors-10/+28
Optimize RcInnerPtr::inc_strong()/inc_weak() instruction count Inspired by this internals thread: https://internals.rust-lang.org/t/rc-optimization-on-64-bit-targets/16362 [The generated assembly is a bit smaller](https://rust.godbolt.org/z/TeTnf6144) and is a more efficient usage of the CPU's instruction cache. `unlikely` doesn't impact any of the small artificial tests I've done, but I've included it in case it might help more complex scenarios when this is inlined.
2022-04-15Rollup merge of #96034 - Gumichocopengin8:test/btree-set, r=Dylan-DPCDylan DPC-0/+56
[test] Add test cases of untested functions for BTreeSet - add [`is_superset()`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.is_superset) and [`remove()`](https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.remove) test cases for BTreeSet since these functions has no test cases.
2022-04-15Implement str to [u8] conversion for refcounted containersJohn-John Tedro-0/+38
2022-04-15chore: formattingKeita Nonaka-11/+9
2022-04-15test: add try_insert() test cases for BTreeSetKeita Nonaka-0/+15
2022-04-15test: add get_key_value() test cases for BTreeSetKeita Nonaka-0/+24
2022-04-14test: add pop_first() pop_last() test cases for BTreeSetKeita Nonaka-9/+77
2022-04-14Fix targets not supporting `target_has_atomic = "ptr"`Vadim Petrochenkov-1/+5
2022-04-14library: Use type aliases to make `CStr(ing)` in libcore/liballoc unstableVadim Petrochenkov-6/+9
2022-04-14library: Move `CStr` to libcore, and `CString` to liballocVadim Petrochenkov-1/+1544
2022-04-14Remove use of `#[rustc_deprecated]`Jacob Pratt-1/+1
2022-04-13test: add remove() test cases for BTreeSetKeita Nonaka-0/+20
2022-04-13test: add is_superset test cases for BTreeSetKeita Nonaka-0/+36
2022-04-13Speed up Vec::clear().Nicholas Nethercote-1/+12
Currently it just calls `truncate(0)`. `truncate()` is (a) not marked as `#[inline]`, and (b) more general than needed for `clear()`. This commit changes `clear()` to do the work itself. This modest change was first proposed in rust-lang#74172, where the reviewer rejected it because there was insufficient evidence that `Vec::clear()`'s performance mattered enough to justify the change. Recent changes within rustc have made `Vec::clear()` hot within `macro_parser.rs`, so the change is now clearly worthwhile. Although it doesn't show wins on CI perf runs, this seems to be because they use PGO. But not all platforms currently use PGO. Also, local builds don't use PGO, and `truncate` sometimes shows up in an over-represented fashion in local profiles. So local profiling will be made easier by this change. Note that this will also benefit `String::clear()`, because it just calls `Vec::clear()`. Finally, the commit removes the `vec-clear.rs` codegen test. It was added in #52908. From before then until now, `Vec::clear()` just called `Vec::truncate()` with a zero length. The body of Vec::truncate() has changed a lot since then. Now that `Vec::clear()` is doing actual work itself, and not just calling `Vec::truncate()`, it's not surprising that its generated code includes a load and an icmp. I think it's reasonable to remove this test.
2022-04-11impl const Default for Box<[T]> and Box<str>Josh Stone-4/+18
2022-04-11Rollup merge of #95917 - RalfJung:thin-box-test, r=dtolnayMatthias Krüger-1/+1
thin_box test: import from std, not alloc Importing from `alloc` makes [Miri fail](https://github.com/rust-lang/miri-test-libstd/runs/5964922742?check_suite_focus=true), probably due to the hack that we used to resolve https://github.com/rust-lang/miri-test-libstd/issues/4. There might be better ways around this, but for now this is the easiest thing to do -- no other alloc integration test is importing from `alloc::`.
2022-04-11Rollup merge of #95743 - yaahc:binary-search-clarification, r=Mark-SimulacrumMatthias Krüger-2/+16
Update binary_search example to instead redirect to partition_point Inspired by discussion in the tracking issue for `Result::into_ok_or_err`: https://github.com/rust-lang/rust/issues/82223#issuecomment-1067098167 People are surprised by us not providing a `Result<T, T> -> T` conversion, and the main culprit for this confusion seems to be the `binary_search` API. We should instead redirect people to the equivalent API that implicitly does that `Result<T, T> -> T` conversion internally which should obviate the need for the `into_ok_or_err` function and give us time to work towards a more general solution that applies to all enums rather than just `Result` such as making or_patterns usable for situations like this via postfix `match`. I choose to duplicate the example rather than simply moving it from `binary_search` to partition point because most of the confusion seems to arise when people are looking at `binary_search`. It makes sense to me to have the example presented immediately rather than requiring people to click through to even realize there is an example. If I had to put it in only one place I'd leave it in `binary_search` and remove it from `partition_point` but it seems pretty obviously relevant to `partition_point` so I figured the best option would be to duplicate it.
2022-04-10thin_box test: import from std, not allocRalf Jung-1/+1
2022-04-09Rollup merge of #95817 - oconnor663:doc_comment2, r=yaahcDylan DPC-1/+1
hide another #[allow] directive from a docs example This is a repeat for Rc of e0e64a89304de2b34dbafbc6cb354d2be9e67835, which cleaned up the same thing for Arc.
2022-04-09Rework String UTF-8 DocumentationMark Lodato-10/+82
**This Commit** Adds some clarity around indexing into Strings and the constraints driving various decisions there. **Why?** The [`String` documentation][0] mentions how `String`s can't be indexed but `Range` has an implementation for `SliceIndex<str>`. This can be confusing. There are also several statements to explain the lack of `String` indexing: - the inability to index into a `String` is an implication of UTF-8 encoding - indexing into a `String` could not be constant-time with UTF-8 encoding - indexing into a `String` does not have an obvious return type This last statement made sense but the first two seemed contradictory to the documentation around [`SliceIndex<str>`][1] which mention: - one can index into a `String` with a `Range` (also called substring slicing but it uses the same syntax and the method name is `index`) - `Range` indexing into a `String` is constant-time To resolve this seeming contradiction the documentation is reworked to more clearly explain what factors drive the decision to disallow indexing into a `String` with a single number. [0]: https://doc.rust-lang.org/stable/std/string/struct.String.html#utf-8 [1]: https://doc.rust-lang.org/stable/std/slice/trait.SliceIndex.html#impl-SliceIndex%3Cstr%3E
2022-04-08hide another #[allow] directive from a docs exampleJack O'Connor-1/+1
This is a repeat for Rc of e0e64a89304de2b34dbafbc6cb354d2be9e67835, which cleaned up the same thing for Arc.
2022-04-08Add ThinBox type for 1 stack pointer sized heap allocated trait objectsJane Lusby-0/+250
Relevant commit messages from squashed history in order: Add initial version of ThinBox update test to actually capture failure swap to middle ptr impl based on matthieu-m's design Fix stack overflow in debug impl The previous version would take a `&ThinBox<T>` and deref it once, which resulted in a no-op and the same type, which it would then print causing an endless recursion. I've switched to calling `deref` by name to let method resolution handle deref the correct number of times. I've also updated the Drop impl for good measure since it seemed like it could be falling prey to the same bug, and I'll be adding some tests to verify that the drop is happening correctly. add test to verify drop is behaving add doc examples and remove unnecessary Pointee bounds ThinBox: use NonNull ThinBox: tests for size Apply suggestions from code review Co-authored-by: Alphyr <47725341+a1phyr@users.noreply.github.com> use handle_alloc_error and fix drop signature update niche and size tests add cfg for allocating APIs check null before calculating offset add test for zst and trial usage prevent optimizer induced ub in drop and cleanup metadata gathering account for arbitrary size and alignment metadata Thank you nika and thomcc! Update library/alloc/src/boxed/thin.rs Co-authored-by: Josh Triplett <josh@joshtriplett.org> Update library/alloc/src/boxed/thin.rs Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-04-08Rollup merge of #95791 - oconnor663:doc_comment, r=thomccDylan DPC-1/+1
hide an #[allow] directive from the Arc::new_cyclic doc example A minor docs cleanup.
2022-04-08Rollup merge of #95579 - Cyborus04:slice_flatten, r=scottmcmDylan DPC-0/+54
Add `<[[T; N]]>::flatten{_mut}` Adds `flatten` to convert `&[[T; N]]` to `&[T]` (and `flatten_mut` for `&mut [[T; N]]` to `&mut [T]`)
2022-04-08add `<[[T; N]]>::flatten`, `<[[T; N]]>::flatten_mut`, and `Vec::<[T; ↵Cyborus04-0/+54
N]>::into_flattened`
2022-04-07hide an #[allow] directive from the Arc::new_cyclic doc exampleJack O'Connor-1/+1
2022-04-07Auto merge of #95678 - pietroalbini:pa-1.62.0-bootstrap, r=Mark-Simulacrumbors-49/+32
Bump bootstrap compiler to 1.61.0 beta This PR bumps the bootstrap compiler to the 1.61.0 beta. The first commit changes the stage0 compiler, the second commit applies the "mechanical" changes and the third and fourth commits apply changes explained in the relevant comments. r? `@Mark-Simulacrum`
2022-04-06add necessary closure for partition_pointJane Lusby-2/+2
2022-04-06Update binary_search example to instead redirect to partition_pointJane Lusby-2/+16
2022-04-05trivial cfg(bootstrap) changesPietro Albini-49/+32
2022-04-06formattingSparkyPotato-1/+1
2022-04-06cleanupSparkyPotato-8/+2
2022-04-06fix Vec leak with 0 capacitySparkyPotato-0/+7
2022-04-03Auto merge of #92686 - saethlin:unsafe-debug-asserts, r=Amanieubors-2/+2
Add debug assertions to some unsafe functions As suggested by https://github.com/rust-lang/rust/issues/51713 ~~Some similar code calls `abort()` instead of `panic!()` but aborting doesn't work in a `const fn`, and the intrinsic for doing dispatch based on whether execution is in a const is unstable.~~ This picked up some invalid uses of `get_unchecked` in the compiler, and fixes them. I can confirm that they do in fact pick up invalid uses of `get_unchecked` in the wild, though the user experience is less-than-awesome: ``` Running unittests (target/x86_64-unknown-linux-gnu/debug/deps/rle_decode_fast-04b7918da2001b50) running 6 tests error: test failed, to rerun pass '--lib' Caused by: process didn't exit successfully: `/home/ben/rle-decode-helper/target/x86_64-unknown-linux-gnu/debug/deps/rle_decode_fast-04b7918da2001b50` (signal: 4, SIGILL: illegal instruction) ``` ~~As best I can tell these changes produce a 6% regression in the runtime of `./x.py test` when `[rust] debug = true` is set.~~ Latest commit (https://github.com/rust-lang/rust/pull/92686/commits/6894d559bdb4365243b3f4bf73f18e4b1bed04d1) brings the additional overhead from this PR down to 0.5%, while also adding a few more assertions. I think this actually covers all the places in `core` that it is reasonable to check for safety requirements at runtime. Thoughts?
2022-03-31make utf8_char_counts test faster in MiriRalf Jung-4/+7
2022-03-31Rollup merge of #95491 - faern:stabilize-vec_retain_mut, r=yaahcDylan DPC-6/+2
Stabilize feature vec_retain_mut on Vec and VecDeque Closes #90829
2022-03-31Rollup merge of #95298 - ↵Dylan DPC-7/+38
jhorstmann:fix-double-drop-of-allocator-in-vec-into-iter, r=oli-obk Fix double drop of allocator in IntoIter impl of Vec Fixes #95269 The `drop` impl of `IntoIter` reconstructs a `RawVec` from `buf`, `cap` and `alloc`, when that `RawVec` is dropped it also drops the allocator. To avoid dropping the allocator twice we wrap it in `ManuallyDrop` in the `InttoIter` struct. Note this is my first contribution to the standard library, so I might be missing some details or a better way to solve this.
2022-03-30Stabilize feature vec_retain_mut on Vec and VecDequeLinus Färnstrand-6/+2
2022-03-30Auto merge of #94963 - lcnr:inherent-impls-std, r=oli-obk,m-ou-sebors-3/+25
allow arbitrary inherent impls for builtin types in core Part of https://github.com/rust-lang/compiler-team/issues/487. Slightly adjusted after some talks with `@m-ou-se` about the requirements of `t-libs-api`. This adds a crate attribute `#![rustc_coherence_is_core]` which allows arbitrary impls for builtin types in core. For other library crates impls for builtin types should be avoided if possible. We do have to allow the existing stable impls however. To prevent us from accidentally adding more of these in the future, there is a second attribute `#[rustc_allow_incoherent_impl]` which has to be added to **all impl items**. This only supports impls for builtin types but can easily be extended to additional types in a future PR. This implementation does not check for overlaps in these impls. Perfectly checking that requires us to check the coherence of these incoherent impls in every crate, as two distinct dependencies may add overlapping methods. It should be easy enough to detect if it goes wrong and the attribute is only intended for use inside of std. The first two commits are mostly unrelated cleanups.
2022-03-30remove now unnecessary lang itemslcnr-3/+3
2022-03-30rework implementation for inherent impls for builtin typeslcnr-0/+22
2022-03-29fixup feature position in liballocAria Beingessner-1/+1
2022-03-29cleanup some of the less terrifying library codeAria Beingessner-2/+2
2022-03-29Make the stdlib largely conform to strict provenance.Aria Beingessner-6/+6
Some things like the unwinders and system APIs are not fully conformant, this only covers a lot of low-hanging fruit.
2022-03-29Add debug assertions to some unsafe functionsBen Kimock-2/+2
These debug assertions are all implemented only at runtime using `const_eval_select`, and in the error path they execute `intrinsics::abort` instead of being a normal debug assertion to minimize the impact of these assertions on code size, when enabled. Of all these changes, the bounds checks for unchecked indexing are expected to be most impactful (case in point, they found a problem in rustc).
2022-03-28Auto merge of #95249 - HeroicKatora:set-ptr-value, r=dtolnaybors-6/+7
Refactor set_ptr_value as with_metadata_of Replaces `set_ptr_value` (#75091) with methods of reversed argument order: ```rust impl<T: ?Sized> *mut T { pub fn with_metadata_of<U: ?Sized>(self, val: *mut U) -> *mut U; } impl<T: ?Sized> *const T { pub fn with_metadata_of<U: ?Sized>(self, val: *const U) -> *const U; } ``` By reversing the arguments we achieve several clarifications: - The function closely resembles `cast` with an argument to initialize the metadata. This is easier to teach and answers a long outstanding question that had restricted cast to `Sized` pointee targets. See multiples reviews of <https://github.com/rust-lang/rust/pull/47631> - The 'object identity', in the form of provenance, is now preserved from the receiver argument to the result. This helps explain the method as a builder-style, instead of some kind of setter that would modify something in-place. Ensuring that the result has the identity of the `self` argument is also beneficial for an intuition of effects. - An outstanding concern, 'Correct argument type', is avoided by not committing to any specific argument type. This is consistent with cast which does not require its receiver to be a 'raw address'. Hopefully the usage examples in `sync/rc.rs` serve as sufficient examples of the style to convince the reader of the readability improvements of this style, when compared to the previous order of arguments. I want to take the opportunity to motivate inclusion of this method _separate_ from metadata API, separate from `feature(ptr_metadata)`. It does _not_ involve the `Pointee` trait in any form. This may be regarded as a very, very light form that does not commit to any details of the pointee trait, or its associated metadata. There are several use cases for which this is already sufficient and no further inspection of metadata is necessary. - Storing the coercion of `*mut T` into `*mut dyn Trait` as a way to dynamically cast some an arbitrary instance of the same type to a dyn trait instance. In particular, one can have a field of type `Option<*mut dyn io::Seek>` to memorize if a particular writer is seekable. Then a method `fn(self: &T) -> Option<&dyn Seek>` can be provided, which does _not_ involve the static trait bound `T: Seek`. This makes it possible to create an API that is capable of utilizing seekable streams and non-seekable streams (instead of a possible less efficient manner such as more buffering) through the same entry-point. - Enabling more generic forms of unsizing for no-`std` smart pointers. Using the stable APIs only few concrete cases are available. One can unsize arrays to `[T]` by `ptr::slice_from_raw_parts` but unsizing a custom smart pointer to, e.g., `dyn Iterator`, `dyn Future`, `dyn Debug`, can't easily be done generically. Exposing `with_metadata_of` would allow smart pointers to offer their own `unsafe` escape hatch with similar parameters where the caller provides the unsized metadata. This is particularly interesting for embedded where `dyn`-trait usage can drastically reduce code size.
2022-03-28Rollup merge of #95098 - shepmaster:vec-from-array-ref, r=dtolnayDylan DPC-0/+42
impl From<&[T; N]> and From<&mut [T; N]> for Vec<T> I really wanted to write: ```rust fn example(a: impl Into<Vec<u8>>) {} fn main() { example(b"raw"); } ```
2022-03-28Rollup merge of #95016 - janpaul123:patch-1, r=dtolnayDylan DPC-3/+7
Docs: make Vec::from_raw_parts documentation less strict This is my first PR; be gentle! In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters. Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too. Let me know what you think! :)
2022-03-28Rollup merge of #93755 - ↵Dylan DPC-1/+1
ChayimFriedman2:allow-comparing-vecs-with-different-allocators, r=dtolnay Allow comparing `Vec`s with different allocators using `==` See https://stackoverflow.com/q/71021633/7884305. I did not changed the `PartialOrd` impl too because it was not generic already (didn't support `Vec<T> <=> Vec<U> where T: PartialOrd<U>`). Does it needs tests? I don't think this will hurt type inference much because the default allocator is usually not inferred (`new()` specifies it directly, and even with other allocators, you pass the allocator to `new_in()` so the compiler usually knows the type). I think this requires FCP since the impls are already stable.
2022-03-27Rollup merge of #95368 - ↵Dylan DPC-1/+1
lopopolo:lopopolo/string-try-reserve-exact-doc-typo, r=Dylan-DPC Fix typo in `String::try_reserve_exact` docs Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`, it looks like this doc comment is intending to refer to the currently-being-documented function.