about summary refs log tree commit diff
path: root/library/alloc/src
AgeCommit message (Collapse)AuthorLines
2021-03-12Rollup merge of #82950 - mockersf:slice-intra-doc-link, r=jyn514Yuki Okushi-5/+5
convert slice doc link to intra-doc links Continuing where #80189 stopped, with `core::slice`. I had an issue with two dead links in my doc when implementing `Deref<Target = [T]>` for one of my type. This means that [`binary_search_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.binary_search_by_key) was available, but not [`sort_by_key`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.sort_by_key) even though it was linked in it's doc (same issue with [`as_ptr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_ptr) and [`as_mut_pbr`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_mut_ptr)). It becomes available if I implement `DerefMut`, as it needs an `&mut self`. <details> <summary>Code that will have dead links in its doc</summary> ```rust pub struct A; pub struct B; impl std::ops::Deref for B{ type Target = [A]; fn deref(&self) -> &Self::Target { &A } } ``` </details> I removed the link to `sort_by_key` from `binary_search_by_key` doc as I didn't find a nice way to have a live link: - `binary_search_by_key` is in `core` - `sort_by_key` is in `alloc` - intra-doc link `slice::sort_by_key` doesn't work, as `alloc` is not available when `core` is being build (the warning can't be ignored: ```error[E0710]: an unknown tool name found in scoped lint: `rustdoc::broken_intra_doc_links` ```) - keeping the link as an anchor `#method.sort_by_key` meant a dead link - an absolute link would work but doesn't feel right...
2021-03-10Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, ↵Yuki Okushi-1/+1
r=nikomatsakis Stabilize `unsafe_op_in_unsafe_fn` lint This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896. Tracking issue: #71668 r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung``` # Stabilization report This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`. ## Summary Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside. The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block. For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level. For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md) ### Example ```rust // An `unsafe fn` for demonstration purposes. // Calling this is an unsafe operation. unsafe fn unsf() {} // #[allow(unsafe_op_in_unsafe_fn)] by default, // the behavior of `unsafe fn` is unchanged unsafe fn allowed() { // Here, no `unsafe` block is needed to // perform unsafe operations... unsf(); // ...and any `unsafe` block is considered // unused and is warned on by the compiler. unsafe { unsf(); } } #[warn(unsafe_op_in_unsafe_fn)] unsafe fn warned() { // Removing this `unsafe` block will // cause the compiler to emit a warning. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } #[deny(unsafe_op_in_unsafe_fn)] unsafe fn denied() { // Removing this `unsafe` block will // cause a compilation error. // (Also, no "unused unsafe" warning will be emitted here.) unsafe { unsf(); } } ```
2021-03-09convert slice doc link to intra-doc linksFrançois Mockers-5/+5
2021-03-09Rollup merge of #81127 - hanmertens:binary_heap_sift_down_perf, r=dtolnayMara Bos-2/+2
Improve sift_down performance in BinaryHeap Replacing `child < end - 1` with `child <= end.saturating_sub(2)` in `BinaryHeap::sift_down_range` (surprisingly) results in a significant speedup of `BinaryHeap::into_sorted_vec`. The same substitution can be done for `BinaryHeap::sift_down_to_bottom`, which causes a slight but probably statistically insignificant speedup for `BinaryHeap::pop`. It's interesting that benchmarks aside from `bench_into_sorted_vec` are barely affected, even those that do use `sift_down_*` methods internally. | Benchmark | Before (ns/iter) | After (ns/iter) | Speedup | |--------------------------|------------------|-----------------|---------| | bench_find_smallest_1000<sup>1</sup> | 392,617 | 385,200 | 1.02 | | bench_from_vec<sup>1</sup> | 506,016 | 504,444 | 1.00 | | bench_into_sorted_vec<sup>1</sup> | 476,869 | 384,458 | 1.24 | | bench_peek_mut_deref_mut<sup>3</sup> | 518,753 | 519,792 | 1.00 | | bench_pop<sup>2</sup> | 446,718 | 444,409 | 1.01 | | bench_push<sup>3</sup> | 772,481 | 770,208 | 1.00 | <sup>1</sup>: internally calls `sift_down_range` <sup>2</sup>: internally calls `sift_down_to_bottom` <sup>3</sup>: should not be affected
2021-03-08Closer similarities.Giles Cope-26/+16
2021-03-08Update library/alloc/src/string.rsSquirrel-6/+3
Co-authored-by: LingMan <LingMan@users.noreply.github.com>
2021-03-07Add documentation for string->Cow conversionsMichael Howell-0/+33
Mostly, it's just to reassure everyone that these functions don't allocate. Part of #51430
2021-03-07vec![0;4] is a fast path.Giles Cope-22/+20
After much tweaking found a way to get similar asm size as the u8 to_string implementation.
2021-03-05Implement String::remove_matchesJosh Cotton-0/+56
2021-03-05Rollup merge of #82764 - m-ou-se:map-try-insert, r=AmanieuMara-1/+70
Add {BTreeMap,HashMap}::try_insert `{BTreeMap,HashMap}::insert(key, new_val)` returns `Some(old_val)` if the key was already in the map. It's often useful to assert no duplicate values are inserted. We experimented with `map.insert(key, val).unwrap_none()` (https://github.com/rust-lang/rust/issues/62633), but decided that that's not the kind of method we'd like to have on `Option`s. `insert` always succeeds because it replaces the old value if it exists. One could argue that `insert()` is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened. This PR adds a `try_insert` method that instead returns a `Result::Err` when the key already exists. This error contains both the `OccupiedEntry` and the value that was supposed to be inserted. This means that unwrapping that result gives more context: ```rust map.insert(10, "world").unwrap_none(); // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29 ``` ```rust map.try_insert(10, "world").unwrap(); // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33 ``` It also allows handling the failure in any other way, as you have full access to the `OccupiedEntry` and the value. `try_insert` returns a reference to the value in case of success, making it an alternative to `.entry(key).or_insert(value)`. r? ```@Amanieu``` Fixes https://github.com/rust-lang/rfcs/issues/3092
2021-03-05Rollup merge of #80723 - rylev:noop-lint-pass, r=estebankMara-4/+4
Implement NOOP_METHOD_CALL lint Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`). This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs: * [ ] No UFCS support * [ ] The warning message is pretty plain * [ ] Doesn't work for `ToOwned` The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type. Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-04less uB in i8Giles Cope-2/+6
2021-03-04Add tracking issue for map_try_insert.Mara Bos-4/+4
2021-03-04Implement Error for OccupiedError.Mara Bos-0/+13
2021-03-04Improve Debug implementations of OccupiedError.Mara Bos-2/+3
2021-03-04Add BTreeMap::try_insert and btree_map::OccupiedError.Mara Bos-1/+56
2021-03-04Add regression test for `Vec::extend_from_within` leakWaffle-3/+5
2021-03-04Fix leak in Vec::extend_from_withinWaffle-16/+27
Previously vec's len was updated only after full copy, making the method leak if T::clone panic!s. This commit makes `Vec::extend_from_within` (or, more accurately, it's `T: Clone` specialization) update vec's len on every iteration, fixing the issue. `T: Copy` specialization was not affected by the issue b/c it doesn't call user specified code (as, e.g. `T::clone`), and instead calls `ptr::copy_nonoverlapping`.
2021-03-04Rollup merge of #82564 - WaffleLapkin:revert_spare_mut, r=RalfJungYuki Okushi-10/+14
Revert `Vec::spare_capacity_mut` impl to prevent pointers invalidation The implementation was changed in #79015. Later it was [pointed out](https://github.com/rust-lang/rust/issues/81944#issuecomment-782849785) that the implementation invalidates pointers to the buffer (initialized elements) by creating a unique reference to the buffer. This PR reverts the implementation. r? ```@RalfJung```
2021-03-04Alternative LUT rather than dividing.Giles Cope-1/+34
2021-03-03BTree: move blocks around in node.rsStein Somers-167/+165
2021-03-03Update library/alloc/src/vec/mod.rsWaffle Lapkin-1/+1
Co-authored-by: Ralf Jung <post@ralfj.de>
2021-03-03Fix ui-full-deps suiteRyan Levick-4/+4
2021-03-03Rollup merge of #82439 - ssomers:btree_fix_unsafety, r=Mark-SimulacrumYuki Okushi-16/+15
BTree: fix untrue safety Fix needless and missing `unsafe` tags. r? ````@Mark-Simulacrum````
2021-03-03Make Vec::split_at_spare_mut impl safer & simplierWaffle-9/+5
2021-03-02Auto merge of #82043 - tmiasko:may-have-side-effect, r=kennytmbors-3/+1
Turn may_have_side_effect into an associated constant The `may_have_side_effect` is an implementation detail of `TrustedRandomAccess` trait. It describes if obtaining an iterator element may have side effects. It is currently implemented as an associated function. Turn `may_have_side_effect` into an associated constant. This makes the value immediately available to the optimizer.
2021-03-02Rollup merge of #80189 - jyn514:convert-primitives, r=poliorceticsYuki Okushi-17/+20
Convert primitives in the standard library to intra-doc links Blocked on https://github.com/rust-lang/rust/pull/80181. I forgot that this needs to wait for the beta bump so the standard library can be documented with `doc --stage 0`. Notably I didn't convert `core::slice` because it's like 50 links and I got scared :fearful:
2021-03-01Rollup merge of #82578 - camsteffen:diag-items, r=oli-obkJoshua Nelson-0/+4
Add some diagnostic items for Clippy
2021-03-01Rollup merge of #81210 - ssomers:btree_fix_node_size_test, r=Mark-SimulacrumJoshua Nelson-5/+6
BTreeMap: correct node size test case for choices of B r? `@Mark-Simulacrum`
2021-03-01Add diagnostic itemsCameron Steffen-0/+4
2021-03-01Auto merge of #82440 - ssomers:btree_fix_casts, r=Mark-Simulacrumbors-8/+10
BTree: no longer define impossible casts Casts to leaf to internal only make sense when the original has a chance of being the thing it's cast to. r? `@Mark-Simulacrum`
2021-03-01Auto merge of #81094 - ssomers:btree_drainy_refactor_3, r=Mark-Simulacrumbors-118/+228
BTreeMap: split up range_search into two stages `range_search` expects the caller to pass the same root twice and starts searching a node for both bounds of a range. It's not very clear that in the early iterations, it searches twice in the same node. This PR splits that search up in an initial `find_leaf_edges_spanning_range` that postpones aliasing until the last second, and a second phase for continuing the search for the range in the each subtree independently (`find_lower_bound_edge` & `find_upper_bound_edge`), which greatly helps for use in #81075. It also moves those functions over to the search module. r? `@Mark-Simulacrum`
2021-02-27u8::to_string() specialisation (far less asm).Giles Cope-0/+19
2021-02-27Revert `Vec::spare_capacity_mut` impl to prevent pointers invalidationWaffle-1/+9
2021-02-26Fix invalid slice access in String::retainGiacomo Stevanato-15/+22
2021-02-25Convert primitives to use intra-doc linksJoshua Nelson-17/+20
2021-02-24library: Normalize safety-for-unsafe-block commentsMiguel Ojeda-10/+11
Almost all safety comments are of the form `// SAFETY:`, so normalize the rest and fix a few of them that should have been a `/// # Safety` section instead. Furthermore, make `tidy` only allow the uppercase form. While currently `tidy` only checks `core`, it is a good idea to prevent `core` from drifting to non-uppercase comments, so that later we can start checking `alloc` etc. too. Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-02-23Rollup merge of #82113 - m-ou-se:panic-format-lint, r=estebankDylan DPC-0/+1
Improve non_fmt_panic lint. This change: - fixes the span used by this lint in the case the panic argument is a single macro expansion (e.g. `panic!(a!())`); - adds a suggestion for `panic!(format!(..))` to remove `format!()` instead of adding `"{}", ` or using `panic_any` like it does now; and - fixes the incorrect suggestion to replace `panic![123]` by `panic_any(123]`. Fixes #82109. Fixes #82110. Fixes #82111. Example output: ``` warning: panic message is not a string literal --> src/main.rs:8:12 | 8 | panic!(format!("error: {}", "oh no")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(non_fmt_panic)]` on by default = note: this is no longer accepted in Rust 2021 = note: the panic!() macro supports formatting, so there's no need for the format!() macro here help: remove the `format!(..)` macro call | 8 | panic!("error: {}", "oh no"); | -- -- ``` r? `@estebank`
2021-02-23BTree: fix untrue safetyStein Somers-16/+15
2021-02-23BTree: no longer define impossible castsStein Somers-8/+10
2021-02-23BTree: split off reusable components from range_searchStein Somers-118/+228
2021-02-23Auto merge of #82076 - jyn514:update-bootstrap, r=Mark-Simulacrumbors-5/+0
Update the bootstrap compiler This updates the bootstrap compiler, notably leaving out a change to enable semicolon in macro expressions lint, because stdarch still depends on the old behavior.
2021-02-23Add more links between hash and btree collectionsJoshua Nelson-3/+4
- Link from `core::hash` to `HashMap` and `HashSet` - Link from HashMap and HashSet to the module-level documentation on when to use the collection - Link from several collections to Wikipedia articles on the general concept
2021-02-23Auto merge of #82430 - Dylan-DPC:rollup-nu4kfyc, r=Dylan-DPCbors-7/+13
Rollup of 12 pull requests Successful merges: - #79423 (Enable smart punctuation) - #81154 (Improve design of `assert_len`) - #81235 (Improve suggestion for tuple struct pattern matching errors.) - #81769 (Suggest `return`ing tail expressions that match return type) - #81837 (Slight perf improvement on char::to_ascii_lowercase) - #81969 (Avoid `cfg_if` in `std::os`) - #81984 (Make WASI's `hard_link` behavior match other platforms.) - #82091 (use PlaceRef abstractions more consistently) - #82128 (add diagnostic items for OsString/PathBuf/Owned as well as to_vec on slice) - #82166 (add s390x-unknown-linux-musl target) - #82234 (Remove query parameters when skipping search results) - #82255 (Make `treat_err_as_bug` Option<NonZeroUsize>) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2021-02-23Rollup merge of #82128 - anall:feature/add_diagnostic_items, r=davidtwcoDylan DPC-0/+3
add diagnostic items for OsString/PathBuf/Owned as well as to_vec on slice This is adding diagnostic items to be used by rust-lang/rust-clippy#6730, but my understanding is the clippy-side change does need to be done over there since I am adding a new clippy feature. Add diagnostic items to the following types: OsString (os_string_type) PathBuf (path_buf_type) Owned (to_owned_trait) As well as the to_vec method on slice/[T]
2021-02-23Rollup merge of #81154 - dylni:improve-design-of-assert-len, r=KodrAusDylan DPC-7/+10
Improve design of `assert_len` It was discussed in the [tracking issue](https://github.com/rust-lang/rust/issues/76393#issuecomment-761765448) that `assert_len`'s name and usage are confusing. This PR improves them based on a suggestion by ``@scottmcm`` in that issue. I also improved the documentation to make it clearer when you might want to use this method. Old example: ```rust let range = range.assert_len(slice.len()); ``` New example: ```rust let range = range.ensure_subset_of(..slice.len()); ``` Fixes #81157
2021-02-23Auto merge of #81937 - ssomers:btree_drainy_refactor_9b, r=Mark-Simulacrumbors-98/+67
BTree: move more shared iterator code into navigate.rs The functions in navigate.rs only exist to support iterators, and these look easier on my eyes if there is a shared `struct` with the recurring pair of handles. r? `@Mark-Simulacrum`
2021-02-22Auto merge of #81362 - ssomers:btree_drainy_refactor_8, r=Mark-Simulacrumbors-146/+176
BTreeMap: gather and decompose reusable tree fixing functions This is kind of pushing it as a standalone refactor, probably only useful for #81075 (or similar). r? `@Mark-Simulacrum`
2021-02-21BTreeMap: correct tests for alternative choices of BStein Somers-5/+6
2021-02-21Improve sift_down performance in BinaryHeapHan Mertens-2/+2
Because child > 0, the two statements are equivalent, but using saturating_sub and <= yields in faster code. This is most notable in the binary_heap::bench_into_sorted_vec benchmark, which shows a speedup of 1.26x, which uses sift_down_range internally. The speedup of pop (that uses sift_down_to_bottom internally) is much less significant as the sifting method is not called in a loop.