Add `suggestion` for some `#[deprecated]` items
Consider code:
```rust
fn main() {
let _ = ["a", "b"].connect(" ");
}
```
Currently it shows deprecated warning:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
```
This PR adds `suggestion` for `connect` and some other deprecated items, so the warning will be changed to this:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
help: replace the use of the deprecated method
|
2 | let _ = ["a", "b"].join(" ");
| ^^^^
```
Add the following facts:
* `handle_alloc_error` may panic instead of aborting.
* What happens if a hook returns rather than diverging.
* A hook may panic. (This was already demonstrated in an example,
but not stated in prose.)
* A hook must be sound to call — it cannot assume that it is only
called by the runtime, since its function pointer can be retrieved by
safe code.
avoid transmuting Box when we can just cast raw pointers instead
Always better to avoid a transmute, in particular when the layout assumptions it is making are not clearly documented. :)
Don't panic in ceil_char_boundary
Implementing the alternative mentioned in this comment: https://github.com/rust-lang/rust/issues/93743#issuecomment-1579935853
Since `floor_char_boundary` will always work (rounding down to the length of the string is possible), it feels best for `ceil_char_boundary` to not panic either. However, the semantics of "rounding up" past the length of the string aren't very great, which is why the method originally panicked in these cases.
Taking into account how people are using this method, it feels best to simply return the end of the string in these cases, so that the result is still a valid char boundary.
* remove `impl Provider for Error`
* rename `Demand` to `Request`
* update docstrings to focus on the conceptual API provided by `Request`
* move `core::any::{request_ref, request_value}` functions into `core::error`
* move `core::any::tag`, `core::any::Request`, an `core::any::TaggedOption` into `core::error`
* replace `provide_any` feature name w/ `error_generic_member_access`
* move `core::error::request_{ref,value} tests into core::tests::error module
* update unit and doc tests
Fix documentation of impl From<Vec<T>> for Rc<[T]>
The example in the documentation of `impl From<Vec<T>> for <Rc<[T]>` is irrelevant (likely was copied from `impl From<Box<T>> for <Rc<T>`). I suggest taking corresponding example from the documentation of `Arc` and replacing `Arc` with `Rc`.
It lints against features that are inteded to be internal to the
compiler and standard library. Implements MCP #596.
We allow `internal_features` in the standard library and compiler as those
use many features and this _is_ the standard library from the "internal to the compiler and
standard library" after all.
Marking some features as internal wasn't exactly the most scientific approach, I just marked some
mostly obvious features. While there is a categorization in the macro,
it's not very well upheld (should probably be fixed in another PR).
We always pass `-Ainternal_features` in the testsuite
About 400 UI tests and several other tests use internal features.
Instead of throwing the attribute on each one, just always allow them.
There's nothing wrong with testing internal features^^
Improve test case for experimental API remove_matches
## Add Test Cases for `remove_matches` Function
### Motivation
After reading the discussion in [this GitHub thread](https://github.com/rust-lang/rust/pull/71780), I'm trying to redesign the current API to use less memory when working with `String` and to make it simpler. I've discovered that some test cases are very helpful in ensuring that the new API behaves as intended. I'm still in the process of redesigning the current API, and these test cases have proven to be very useful.
### Testing
The current test has been tested with the command `./x test --stage 0 library/alloc`.
### Overview
This pull request adds several new test cases for the `remove_matches` function to make sure it works correctly in different situations. The `remove_matches` function is used to get rid of all instances of a specific pattern from a given text. These test cases thoroughly check how the function behaves in various scenarios.
### Test Cases
1. **Single Pattern Occurrence** (`test_single_pattern_occurrence`):
- Description: Tests the removal of a single pattern occurrence from the text.
- Input: Text: "abc", Pattern: 'b'
- Expected Output: "ac"
2. **Repeat Test Single Pattern Occurrence** (`repeat_test_single_pattern_occurrence`):
- Description: Repeats the previous test case to ensure consecutive removal of the same pattern.
- Input: Text: "ac", Pattern: 'b'
- Expected Output: "ac"
3. **Single Character Pattern** (`test_single_character_pattern`):
- Description: Tests the removal of a single character pattern.
- Input: Text: "abcb", Pattern: 'b'
- Expected Output: "ac"
4. **Pattern with Special Characters** (`test_pattern_with_special_characters`):
- Description: Tests the removal of a pattern containing special characters.
- Input: Text: "ศไทย中华Việt Nam; foobarศ", Pattern: 'ศ'
- Expected Output: "ไทย中华Việt Nam; foobar"
5. **Pattern Empty Text and Pattern** (`test_pattern_empty_text_and_pattern`):
- Description: Tests the removal of an empty pattern from an empty text.
- Input: Text: "", Pattern: ""
- Expected Output: ""
6. **Pattern Empty Text** (`test_pattern_empty_text`):
- Description: Tests the removal of a pattern from an empty text.
- Input: Text: "", Pattern: "something"
- Expected Output: ""
7. **Empty Pattern** (`test_empty_pattern`):
- Description: Tests the behavior of removing an empty pattern from the text.
- Input: Text: "Testing with empty pattern.", Pattern: ""
- Expected Output: "Testing with empty pattern."
8. **Multiple Consecutive Patterns 1** (`test_multiple_consecutive_patterns_1`):
- Description: Tests the removal of multiple consecutive occurrences of a pattern.
- Input: Text: "aaaaa", Pattern: 'a'
- Expected Output: ""
9. **Multiple Consecutive Patterns 2** (`test_multiple_consecutive_patterns_2`):
- Description: Tests the removal of a longer pattern that occurs consecutively.
- Input: Text: "Hello **world****today!**", Pattern: "**"
- Expected Output: "Hello worldtoday!"
10. **Case Insensitive Pattern** (`test_case_insensitive_pattern`):
- Description: Tests the removal of a case-insensitive pattern from the text.
- Input: Text: "CASE ** SeNsItIvE ** PaTtErN.", Pattern: "sEnSiTiVe"
- Expected Output: "CASE ** SeNsItIvE ** PaTtErN."
Stabilize const-weak-new
This is a fairly uncontroversial library stabilization, so I'm going ahead and proposing it to ride the trains to stable.
This stabilizes the following APIs, which are defined to be non-allocating constructors.
```rust
// alloc::rc
impl<T> Weak<T> {
pub const fn new() -> Weak<T>;
}
// alloc::sync
impl<T> Weak<T> {
pub const fn new() -> Weak<T>;
}
```
Closes#95091
``@rustbot`` modify labels: +needs-fcp
Bump its stabilization version several times along
the way to accommodate changes in release processes.
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Co-authored-by: Trevor Gross <t.gross35@gmail.com>
Documentation: Fix Stilted Language in Vec->Indexing
Problem
Language in the Vec->Indexing documentation sounds stilted due to incorrect word ordering: "... type allows to access values by index."
Solution
Reorder words in the Vec->Indexing documentation to flow better: "... type allows access to values by index." The phrase "allows access to" also matches other existing documentation.
Clarify behavior of inclusive bounds in BTreeMap::{lower,upper}_bound
It wasn’t quite clear to me how these methods would interpret inclusive bounds so I added examples for those.
Remove redundant example of `BTreeSet::iter`
The usage and that `Values returned by the iterator are returned in ascending order` are already demonstrated by the other example and the description, so I removed the useless one.
Problem
Language in the Vec->Indexing documentation sounds stilted due to
incorrect word ordering: "... type allows to access values by index."
Solution
Reorder words in the Vec->Indexing documentation to flow better:
"... type allows access to values by index." The phrase "allows access to"
also matches other existing documentation.
The status quo is highly confusing, since the overlap is not apparent,
and specialization is not a feature of Rust. This addresses #87545;
I'm not certain if it closes it, since that issue might also be trackign
a *general* solution for hiding specializing impls automatically.
Multibyte character removal in String::pop and String::remove doctests
I think it would be useful to have the doctests for the `String::pop()` and `String::remove()` methods demonstrate that they work on multibyte UTF-8 sequences.
Fix size_hint for EncodeUtf16
More realistic upper and lower bounds, and handle the case where the iterator is located within a surrogate pair.
Resolves#113897
Add support for allocators in `Rc` & `Arc`
Adds the ability for `std::rc:Rc`, `std::rc::Weak`, `std::sync::Arc`, and `std::sync::Weak` to live in custom allocators
Rename VecDeque's `rotate_left` and `rotate_right` parameters
This pull request introduces a modification to the `VecDeque` collection, specifically the `rotate_left` and `rotate_right` functions, by renaming the parameter associated with these functions.
The rationale behind this change is to provide clearer and more consistent naming for the parameter that specifies the number of places to rotate the double-ended queue. By using `n` as the parameter name in both functions, it becomes easier to understand and remember the purpose of the parameter.
Eliminate ZST allocations in `Box` and `Vec`
This PR fixes 2 issues with `Box` and `RawVec` related to ZST allocations. Specifically, the `Allocator` trait requires that:
- If you allocate a zero-sized layout then you must later deallocate it, otherwise the allocator may leak memory.
- You cannot pass a ZST pointer to the allocator that you haven't previously allocated.
These restrictions exist because an allocator implementation is allowed to allocate non-zero amounts of memory for a zero-sized allocation. For example, `malloc` in libc does this.
Currently, ZSTs are handled differently in `Box` and `Vec`:
- `Vec` never allocates when `T` is a ZST or if the vector capacity is 0.
- `Box` just blindly passes everything on to the allocator, including ZSTs.
This causes problems due to the free conversions between `Box<[T]>` and `Vec<T>`, specifically that ZST allocations could get leaked or a dangling pointer could be passed to `deallocate`.
This PR fixes this by changing `Box` to not allocate for zero-sized values and slices. It also fixes a bug in `RawVec::shrink` where shrinking to a size of zero did not actually free the backing memory.
Revert "alloc: Allow comparing Boxs over different allocators", add regression test
Temporary fix for #113283
Adds a test to fix the regression introduced in 001b081cc1 and revert that commit. The test fails without the revert.
This reverts commit 001b081cc1.
This change was done as the above commit introduces a regression in type
inference. Regression test located at
`tests/ui/type-inference/issue-113283-alllocator-trait-eq.rs`
Allow comparing `Box`es with different allocators
Currently, comparing `Box`es over different allocators is not allowed:
```Rust
error[E0308]: mismatched types
--> library/alloc/tests/boxed.rs:22:20
|
22 | assert_eq!(b1, b2);
| ^^ expected `Box<{integer}, ConstAllocator>`, found `Box<{integer}, AnotherAllocator>`
|
= note: expected struct `Box<{integer}, ConstAllocator>`
found struct `Box<{integer}, AnotherAllocator>`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `alloc` (test "collectionstests") due to previous error
```
This PR lifts this limitation
remove unused field
Followup to #104455. The field is no longer needed since ExtractIf (previously DrainFilter) doesn't keep draining in its drop impl.
Implement PartialOrd for `Vec`s over different allocators
It is already possible to `PartialEq` `Vec`s with different allocators, but that is not the case with `PartialOrd`.
This is an `Rc` that is guaranteed to only have one strong reference.
Because it is uniquely owned, it can safely implement `DerefMut`, which
allows programs to have an initialization phase where structures inside
the `Rc` can be mutated.
The `UniqueRc` can then be converted to a regular `Rc`, allowing sharing
and but read-only access.
During the "initialization phase," weak references can be created, but
attempting to upgrade these will fail until the `UniqueRc` has been
converted to a regular `Rc`. This feature can be useful to create
cyclic data structures.
This API is an implementation based on the feedback provided to the ACP
at https://github.com/rust-lang/libs-team/issues/90.
Remove `box_free` lang item
This PR removes the `box_free` lang item, replacing it with `Box`'s `Drop` impl. Box dropping is still slightly magic because the contained value is still dropped by the compiler.
Stabilize String::leak
Stabilizes the following API:
```Rust
impl String {
pub fn leak(self) -> &'static mut str;
}
```
closes#102929
blocked by having an FCP for stabilization.
Ignore `core`, `alloc` and `test` tests that require unwinding on `-C panic=abort`
Some of the tests for `core` and `alloc` require unwinding through their use of `catch_unwind`. These tests fail when testing using `-C panic=abort` (in my case through a target without unwinding support, and `-Z panic-abort-tests`), while they should be ignored as they don't indicate a failure.
This PR marks all of these tests with this attribute:
```rust
#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
```
I'm not aware of a way to test this on rust-lang/rust's CI, as we don't test any target with `-C panic=abort`, but I tested this locally on a Ferrocene target and it does indeed make the test suite pass.
Uplift `clippy::invalid_utf8_in_unchecked` lint
This PR aims at uplifting the `clippy::invalid_utf8_in_unchecked` lint into two lints.
## `invalid_from_utf8_unchecked`
(deny-by-default)
The `invalid_from_utf8_unchecked` lint checks for calls to `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut` with an invalid UTF-8 literal.
### Example
```rust
unsafe {
std::str::from_utf8_unchecked(b"cl\x82ippy");
}
```
### Explanation
Creating such a `str` would result in undefined behavior as per documentation for `std::str::from_utf8_unchecked` and `std::str::from_utf8_unchecked_mut`.
## `invalid_from_utf8`
(warn-by-default)
The `invalid_from_utf8` lint checks for calls to `std::str::from_utf8` and `std::str::from_utf8_mut` with an invalid UTF-8 literal.
### Example
```rust
std::str::from_utf8(b"ru\x82st");
```
### Explanation
Trying to create such a `str` would always return an error as per documentation for `std::str::from_utf8` and `std::str::from_utf8_mut`.
-----
Mostly followed the instructions for uplifting a clippy lint described here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751
````@rustbot```` label: +I-lang-nominated
r? compiler
-----
For Clippy:
changelog: Moves: Uplifted `clippy::invalid_utf8_in_unchecked` into rustc
Support #[global_allocator] without the allocator shim
This makes it possible to use liballoc/libstd in combination with `--emit obj` if you use `#[global_allocator]`. This is what rust-for-linux uses right now and systemd may use in the future. Currently they have to depend on the exact implementation of the allocator shim to create one themself as `--emit obj` doesn't create an allocator shim.
Note that currently the allocator shim also defines the oom error handler, which is normally required too. Once `#![feature(default_alloc_error_handler)]` becomes the only option, this can be avoided. In addition when using only fallible allocator methods and either `--cfg no_global_oom_handling` for liballoc (like rust-for-linux) or `--gc-sections` no references to the oom error handler will exist.
To avoid this feature being insta-stable, you will have to define `__rust_no_alloc_shim_is_unstable` to avoid linker errors.
(Labeling this with both T-compiler and T-lang as it originally involved both an implementation detail and had an insta-stable user facing change. As noted above, the `__rust_no_alloc_shim_is_unstable` symbol requirement should prevent unintended dependence on this unstable feature.)
Mark internal functions and traits unsafe to reflect preconditions
No semantics are changed in this PR; I only mark some functions and and a trait `unsafe` which already had implicit preconditions. Although it seems somewhat redundant for `numfmt::Part::Copy` to contain a `&[u8]` instead of a `&str`, given that all of its current consumers ultimately expect valid UTF-8. Is the type also intended to work for byte-slice formatting in the future?
Fix duplicate `arcinner_layout_for_value_layout` calls when using the uninit `Arc` constructors
What this fixes is the duplicate calls to `arcinner_layout_for_value_layout` seen here: https://godbolt.org/z/jr5Gxozhj
The issue was discovered alongside #111603 but is otherwise unrelated to the duplicate `alloca`s, which remain unsolved. Everything I tried to solve said main issue has failed.
As for the duplicate layout calculations, I also tried slapping `#[inline]` and `#[inline(always)]` on everything in sight but the only thing that worked in the end is to dedup the calls by hand.
Specialize ToString implementation for fmt::Arguments
Generates far fewer instructions by formatting into a String with `fmt::format` directly instead of going through the `fmt::Display` impl. This change is insta-stable.
Change Vec examples to not assert exact capacity except where it is guaranteed
It was [brought up on discord](https://discord.com/channels/273534239310479360/818964227783262209/1107633959329878077) that the `Vec::into_boxed_slice` example contradicted the `Vec::with_capacity` docs in that the returned `Vec` might have _more_ capacity than requested.
So, to reduce confusion change all the `assert_eq!(vec.capacity(), _)` to `assert!(vec.capacity() >= _)`, except in 4 examples that have guaranteed capacities: `Vec::from_raw_parts`, `Vec::from_raw_parts_in`, `Vec::<()>::with_capacity`,`Vec::<(), _>::with_capacity_in`.
You will need to add the following as replacement for the old __rust_*
definitions when not using the alloc shim.
#[no_mangle]
static __rust_no_alloc_shim_is_unstable: u8 = 0;
enable `rust_2018_idioms` lint group for doctests
With this change, `rust_2018_idioms` lint group will be enabled for compiler/libstd doctests.
Resolves#106086Resolves#99144
Signed-off-by: ozkanonur <work@onurozkan.dev>
Make sure that some stdlib method signatures aren't accidental refinements
In the process of implementing https://rust-lang.github.io/rfcs/3245-refined-impls.html, I found a bunch of stdlib implementations that accidentally "refined" their method signatures by dropping (unnecessary) bounds.
This isn't currently a problem, but may become one if/when method signature refining is stabilized in the future. Shouldn't hurt to make these signatures a bit more accurate anyways.
NOTE (just to be clear lol): This does not affect behavior at all, since we don't actually take advantage of refined implementations yet!
Spelling library
Split per https://github.com/rust-lang/rust/pull/110392
I can squash once people are happy w/ the changes. It's really uncommon for large sets of changes to be perfectly acceptable w/o at least some changes.
I probably won't have time to respond until tomorrow or the next day
Updating Wake example to use new 'pin!' macro
Closes: https://github.com/rust-lang/rust/issues/109965
I have already had this reviewed and approved here: https://github.com/rust-lang/rust/pull/110026 . But because I had some git issues and chose the "nuke it" option as my solution it didn't get merged. I nuked it too quickly. I am sorry for trouble of reviewing twice.
Report allocation errors as panics
OOM is now reported as a panic but with a custom payload type (`AllocErrorPanicPayload`) which holds the layout that was passed to `handle_alloc_error`.
This should be review one commit at a time:
- The first commit adds `AllocErrorPanicPayload` and changes allocation errors to always be reported as panics.
- The second commit removes `#[alloc_error_handler]` and the `alloc_error_hook` API.
ACP: https://github.com/rust-lang/libs-team/issues/192Closes#51540Closes#51245
More `IS_ZST` in `library`
I noticed that `post_inc_start` and `pre_dec_end` were doing this check in different ways
d19b64fb54/library/core/src/slice/iter/macros.rs (L76-L93)
so started making this PR, then added a few more I found since I was already making changes anyway.
I noticed that `post_inc_start` and `pre_dec_end` were doing this check in different ways
d19b64fb54/library/core/src/slice/iter/macros.rs (L76-L93)
so started making this PR, then added a few more I found since I was already making changes anyway.
Add `tidy-alphabetical` to features in `alloc` & `std`
So that people have to keep them sorted in future, rather than just sticking them on the end where they conflict more often.
Follow-up to #110269
cc `@jyn514`
binary_heap: Optimize Extend implementation.
This PR makes the `Extend` implementation for `BinaryHeap` no longer rely on specialization, so that it always use the bulk rebuild optimization that was previously only available for the `Vec` specialization.
Improve documentation for str::replace() and str::replacen()
Currently, to know what the function will return when the pattern doesn't match, the docs require the reader to understand the implementation detail and mentally evaluate or run the example code. It is not immediately clear.
This PR makes it more explicit so the reader can quickly find the information.
Rollup of 7 pull requests
Successful merges:
- #106985 (Enhanced doucmentation of binary search methods for `slice` and `VecDeque` for unsorted instances)
- #109509 (compiletest: Don't allow tests with overlapping prefix names)
- #109719 (RELEASES: Add "Only support Android NDK 25 or newer" to 1.68.0)
- #109748 (Don't ICE on `DiscriminantKind` projection in new solver)
- #109749 (Canonicalize float var as float in new solver)
- #109761 (Drop binutils on powerpc-unknown-freebsd)
- #109766 (Fix title for openharmony.md)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Enhanced doucmentation of binary search methods for `slice` and `VecDeque` for unsorted instances
Fixes#106746. Issue #106746 raises the concern that the binary search methods for slices and deques aren't explicit enough about the fact that they are only applicable to sorted slices/deques. I changed the explanation for these methods. I took the relatively harsh description of the behaviour of binary search on unsorted collections ("unspecified and meaningless") from the description of the [`partition_point`](https://doc.rust-lang.org/std/primitive.slice.html#method.partition_point) method:
> If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.
Partial stabilization of `once_cell`
This PR aims to stabilize a portion of the `once_cell` feature:
- `core::cell::OnceCell`
- `std::cell::OnceCell` (re-export of the above)
- `std::sync::OnceLock`
This will leave `LazyCell` and `LazyLock` unstabilized, which have been moved to the `lazy_cell` feature flag.
Tracking issue: https://github.com/rust-lang/rust/issues/74465 (does not fully close, but it may make sense to move to a new issue)
Future steps for separate PRs:
- ~~Add `#[inline]` to many methods~~ #105651
- Update cranelift usage of the `once_cell` crate
- Update rust-analyzer usage of the `once_cell` crate
- Update error messages discussing once_cell
## To be stabilized API summary
```rust
// core::cell (in core/cell/once.rs)
pub struct OnceCell<T> { .. }
impl<T> OnceCell<T> {
pub const fn new() -> OnceCell<T>;
pub fn get(&self) -> Option<&T>;
pub fn get_mut(&mut self) -> Option<&mut T>;
pub fn set(&self, value: T) -> Result<(), T>;
pub fn get_or_init<F>(&self, f: F) -> &T where F: FnOnce() -> T;
pub fn into_inner(self) -> Option<T>;
pub fn take(&mut self) -> Option<T>;
}
impl<T: Clone> Clone for OnceCell<T>;
impl<T: Debug> Debug for OnceCell<T>
impl<T> Default for OnceCell<T>;
impl<T> From<T> for OnceCell<T>;
impl<T: PartialEq> PartialEq for OnceCell<T>;
impl<T: Eq> Eq for OnceCell<T>;
```
```rust
// std::sync (in std/sync/once_lock.rs)
impl<T> OnceLock<T> {
pub const fn new() -> OnceLock<T>;
pub fn get(&self) -> Option<&T>;
pub fn get_mut(&mut self) -> Option<&mut T>;
pub fn set(&self, value: T) -> Result<(), T>;
pub fn get_or_init<F>(&self, f: F) -> &T where F: FnOnce() -> T;
pub fn into_inner(self) -> Option<T>;
pub fn take(&mut self) -> Option<T>;
}
impl<T: Clone> Clone for OnceLock<T>;
impl<T: Debug> Debug for OnceLock<T>;
impl<T> Default for OnceLock<T>;
impl<#[may_dangle] T> Drop for OnceLock<T>;
impl<T> From<T> for OnceLock<T>;
impl<T: PartialEq> PartialEq for OnceLock<T>
impl<T: Eq> Eq for OnceLock<T>;
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T>;
unsafe impl<T: Send> Send for OnceLock<T>;
unsafe impl<T: Sync + Send> Sync for OnceLock<T>;
impl<T: UnwindSafe> UnwindSafe for OnceLock<T>;
```
No longer planned as part of this PR, and moved to the `rust_cell_try` feature gate:
```rust
impl<T> OnceCell<T> {
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>;
}
impl<T> OnceLock<T> {
pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E> where F: FnOnce() -> Result<T, E>;
}
```
I am new to this process so would appreciate mentorship wherever needed.
Remove ~const from alloc
There is currently an effort underway to stop using `~const Trait`, temporarily, so as to refactor the logic underlying const traits with relative ease. This means it has to go from the standard library, as well.
I have taken the initial step of just removing these impls from alloc, as removing them from core is a much more tangled task. In addition, all of these implementations are one more-or-less logically-connected group, so reverting their deconstification as a group seems like it will also be sensible.
r? `@fee1-dead`
Change advance(_back)_by to return the remainder instead of the number of processed elements
When advance_by can't advance the iterator by the number of requested elements it now returns the amount by which it couldn't be advanced instead of the amount by which it did.
This simplifies adapters like chain, flatten or cycle because the remainder doesn't have to be calculated as the difference between requested steps and completed steps anymore.
Additionally switching from `Result<(), usize>` to `Result<(), NonZeroUsize>` reduces the size of the result and makes converting from/to a usize representing the number of remaining steps cheap.
A successful advance is now signalled by returning `0` and other values now represent the remaining number
of steps that couldn't be advanced as opposed to the amount of steps that have been advanced during a partial advance_by.
This simplifies adapters a bit, replacing some `match`/`if` with arithmetic. Whether this is beneficial overall depends
on whether `advance_by` is mostly used as a building-block for other iterator methods and adapters or whether
we also see uses by users where `Result` might be more useful.
Stabilize `nonnull_slice_from_raw_parts`
FCP is done: https://github.com/rust-lang/rust/issues/71941#issuecomment-1100910416
Note that this doesn't const-stabilize `NonNull::slice_from_raw_parts` as `slice_from_raw_parts_mut` isn't const-stabilized yet. Given #67456 and #57349, it's not likely available soon, meanwhile, stabilizing only the feature makes some sense, I think.
Closes#71941
Currently, to know what the function will return when the pattern
doesn't match, the docs require the reader to understand the
implementation detail and mentally evaluate or run the example
code. It is not immediately clear.
This PR makes it more explicit so the reader can quickly find the
information.
Implement Default for some alloc/core iterators
Add `Default` impls to the following collection iterators:
* slice::{Iter, IterMut}
* binary_heap::IntoIter
* btree::map::{Iter, IterMut, Keys, Values, Range, IntoIter, IntoKeys, IntoValues}
* btree::set::{Iter, IntoIter, Range}
* linked_list::IntoIter
* vec::IntoIter
and these adapters:
* adapters::{Chain, Cloned, Copied, Rev, Enumerate, Flatten, Fuse, Rev}
For iterators which are generic over allocators it only implements it for the global allocator because we can't conjure an allocator from nothing or would have to turn the allocator field into an `Option` just for this change.
These changes will be insta-stable.
ACP: https://github.com/rust-lang/libs-team/issues/77
Remove the assume(!is_null) from Vec::as_ptr
At a guess, this code is leftover from LLVM was worse at keeping track of the niche information here. In any case, we don't need this anymore: Removing this `assume` doesn't get rid of the `nonnull` attribute on the return type.
Introduce `Rc::into_inner`, as a parallel to `Arc::into_inner`
Unlike `Arc`, `Rc` doesn't have the same race condition to avoid, but
maintaining an equivalent API still makes it easier to work with both
`Rc` and `Arc`.
Unlike `Arc`, `Rc` doesn't have the same race condition to avoid, but
maintaining an equivalent API still makes it easier to work with both
`Rc` and `Arc`.
Rollup of 9 pull requests
Successful merges:
- #104363 (Make `unused_allocation` lint against `Box::new` too)
- #106633 (Stabilize `nonzero_min_max`)
- #106844 (allow negative numeric literals in `concat!`)
- #108071 (Implement goal caching with the new solver)
- #108542 (Force parentheses around `match` expression in binary expression)
- #108690 (Place size limits on query keys and values)
- #108708 (Prevent overflow through Arc::downgrade)
- #108739 (Prevent the `start_bx` basic block in codegen from having two `Builder`s at the same time)
- #108806 (Querify register_tools and post-expansion early lints)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup