Stabilize slice_ptr_range.
This has been unstable for almost a year now. Time to stabilize?
Closes#65807.
@rustbot modify labels: +T-libs +A-raw-pointers +A-slice +needs-fcp
This commit entroduces `core::str::SplitInclusive::as_str` method similar to
`core::str::Split::as_str`, but under different gate -
"str_split_inclusive_as_str" (this is done so because `SplitInclusive` is
itself unstable).
This commit introduses 2 methods under "str_split_as_str" gate with common
signature of `&Split<'a, _> -> &'a str'`. Both of them work like
`Chars::as_str` - return unyield part of the inner string.
Refactor memchr to allow optimization
Closes#75659
The implementation already uses naive search if the slice if short enough, but the case is complicated enough to not be optimized away. This PR refactors memchr so that it exists early when the slice is short enough.
Codegen-wise, as shown in #75659, memchr was not inlined previously so the only way I could find to test this is to check if there is no memchr call. Let me know if there is a more robust solution here.
Add Iterator::advance_by and DoubleEndedIterator::advance_back_by
This PR adds the iterator method
```rust
fn advance_by(&mut self, n: usize) -> Result<(), usize>
```
that advances the iterator by `n` elements, returning `Ok(())` if this succeeds or `Err(len)` if the length of the iterator was less than `n`.
Currently `Iterator::nth` is the method to override for efficiently advancing an iterator by multiple elements at once. `advance_by` is superior for this purpose because
- it's simpler to implement: instead of advancing the iterator and producing the next element you only need to advance the iterator
- it composes better: iterators like `Chain` and `FlatMap` can implement `advance_by` in terms of `advance_by` on their inner iterators, but they cannot implement `nth` in terms of `nth` on their inner iterators (see #60395)
- the default implementation of `nth` can trivially be implemented in terms of `advance_by` and `next`, which this PR also does
This PR also adds `DoubleEndedIterator::advance_back_by` for all the same reasons.
I'll make a tracking issue if it's decided this is worth merging. Also let me know if anything can be improved, this went through several iterations so there might very well still be room for improvement (especially in the doc comments). I've written overrides of these methods for most iterators that already override `nth`/`nth_back`, but those still need tests so I'll add them in a later PR.
cc @cuviper @scottmcm @Amanieu
Split core/str/mod.rs to smaller files
Note for reviewer:
* I split to multiple commits for easier reviewing, but I could git squash them all to one if requested.
* Recommend pulling this change locally and using advanced git diff viewer or this command:
```bash
git show --reverse --color-moved=dimmed-zebra --color-moved-ws=ignore-all-space master..
```
---
I split `core/str/mod.rs` to these modules:
* `converts`: Contains helper functions to convert from bytes to str.
* `error`: For error structs like Utf8Error.
* `iter`: For iterators of many str methods.
* `traits`: For indexing operations and build in traits on str.
* `validations`: For functions validating utf8 --- This name is awkward, maybe utf8.rs is better.
Add zero padding
Add benchmarks for fmt u128
This tests both when there is the max amount of work(all characters used)
And least amount of work(1 character used)
Add doc alias for iterator fold
fold is known in python and javascript as reduce,
not sure about inject but it was written in doc there.
This was my first confusion when coming into rust, I somehow cannot find where is reduce, sometimes I still forget that it is known as `fold`.
Remove `#[rustc_allow_const_fn_ptr]` and add `#![feature(const_fn_fn_ptr_basics)]`
`rustc_allow_const_fn_ptr` was a hack to work around the lack of an escape hatch for the "min `const fn`" checks in const-stable functions. Now that we have co-opted `allow_internal_unstable` for this purpose, we no longer need a bespoke attribute.
Now this functionality is gated under `const_fn_fn_ptr_basics` (how concise!), and `#[allow_internal_unstable(const_fn_fn_ptr_basics)]` replaces `#[rustc_allow_const_fn_ptr]`. `const_fn_fn_ptr_basics` allows function pointer types to appear in the arguments and locals of a `const fn` as well as function pointer casts to be performed inside a `const fn`. Both of these were allowed in constants and statics already. Notably, this does **not** allow users to invoke function pointers in a const context. Presumably, we will use a nicer name for that (`const_fn_ptr`?).
r? @oli-obk
UI to unit test for those using Cell/RefCell/UnsafeCell
Helps with #76268.
I'm working on all files using `Cell` and moving them to unit tests when possible.
r? @matklad
This was a hack to work around the lack of an escape hatch for the "min
`const fn`" checks in const-stable functions. Now that we have co-opted
`allow_internal_unstable` for this purpose, we no longer need the
bespoke attribute.
Add `#![feature(const_fn_floating_point_arithmetic)]`
cc #76618
This is a template for splitting up `const_fn` into granular feature gates. I think this will make it easier, both for us and for users, to track stabilization of each individual feature. We don't *have* to do this, however. We could also keep stabilizing things out from under `const_fn`.
cc @rust-lang/wg-const-eval
r? @oli-obk
Explicitly document the size guarantees that Option makes.
Triggered by a discussion on wg-unsafe-code-guidelines about which layouts of `Option<T>` one can guarantee are optimised to a single pointer.
CC @RalfJung
It's possible for method resolution to pick this method over a lower
priority stable method, causing compilation errors. Since this method
is permanently unstable, give it a name that is very unlikely to be used
in user code.
Make [].as_[mut_]ptr_range() (unstably) const.
Gated behind `const_ptr_offset`, as suggested by https://github.com/rust-lang/rust/issues/65807#issuecomment-697229404
This also marks `[].as_mut_ptr()` as const, because it's used by `as_mut_ptr_range`. I gated it behind the same feature, because I figured it's not worth adding a separate tracking issue for const `as_mut_ptr`.
Use `Self` in docs when possible
Fixes#76542.
I used `rg '\s*//[!/]\s+fn [\w_]+\(&?self, ' .` in `library/` to find instances, I found some with that and some by manually checking.
@rustbot modify labels: C-enhancement T-doc
add array::from_ref
mirrors the methods in `std::slice` with the same name.
I guess this method previously didn't exist as there was close to no reason to create an array of size `1`.
This will change due to const generics in the near future.
revert const_type_id stabilization
This reverts #72488, which is currently on beta and scheduled to stabilize in `1.47.0`, based on https://github.com/rust-lang/rust/pull/75923#issuecomment-696676511
It turns out we might not be quite ready to stabilize `TypeId` in const contexts before having a chance to rework its internals. Since `TypeId` is a bit of an oddity we want to be careful about how those internals are currently being relied on while making changes. That will be easier to do without having to also consider compile-time contexts.
r? `@eddyb`
Add #[track_caller] to more panicking Cell functions
Continuation of #74526
Adds the #[track_caller] attribute to almost all panicking Cell
functions. The ones that borrow two Cells in their function
body are spared, because the panic location helps pinpoint
which of the two borrows failed. You'd need to have
full debuginfo and backtraces enabled together with column
info in order to be able to discern the cases.
Column info in debuginfo is only available on non-Windows platforms.
Add cfg(target_has_atomic_equal_alignment) and use it for Atomic::from_mut.
Fixes some platform-specific problems with #74532 by using the actual alignment of the types instead of hardcoding a few `target_arch`s.
r? @RalfJung
Continuation of #74526
Adds the #[track_caller] attribute to almost all panicking Cell
functions. The ones that borrow two Cells in their function
body are spared, because the panic location helps pinpoint
which of the two borrows failed. You'd need to have
full debuginfo and backtraces enabled together with column
info in order to be able to discern the cases.
Column info is only available on non-Windows platforms.
Make some methods of `Pin` unstable const
Make the following methods unstable const under the `const_pin` feature:
- `new`
- `new_unchecked`
- `into_inner`
- `into_inner_unchecked`
- `get_ref`
- `into_ref`
- `get_mut`
- `get_unchecked_mut`
Of these, `into_inner` and `into_inner_unchecked` require the unstable `const_precise_live_drops`.
Also adds tests for these methods in a const context.
Tracking issue: #76654
r? @ecstatic-morse
Don't recommend ManuallyDrop to customize drop order
See
https://internals.rust-lang.org/t/need-for-controlling-drop-order-of-fields/12914/21
for the discussion.
TL;DR: ManuallyDrop is unsafe and footguny, but you can just ask the compiler to do all the work for you by re-ordering declarations.
Specifically, the original example from the docs is much better written as
```rust
struct Peach;
struct Banana;
struct Melon;
struct FruitBox {
melon: Melon,
// XXX: mind the relative drop order of the fields below
peach: Peach,
banana: Banana,
}
```
Revert adding Atomic::from_mut.
This reverts #74532, which made too many assumptions about platforms, breaking some things.
Will need to be added later with a better way of gating on proper alignment, without hardcoding cfg(target_arch)s.
---
To be merged if fixing from_mut (#76965) takes too long.
r? @ghost
Add non-`unsafe` `.get_mut()` for `Unsafecell`
- Tracking issue: https://github.com/rust-lang/rust/issues/76943
As discussed in: https://internals.rust-lang.org/t/add-non-unsafe-get-mut-for-unsafecell/12407
- ### [Rendered documentation](https://modest-dubinsky-1f9f47.netlify.app/core/cell/struct.unsafecell)
This PR tries to move the sound `&mut UnsafeCell<T> -> &mut T` projection that all the "downstream" constructions were already relying on, up to the root abstraction, where it rightfully belongs, and officially blessing it.
- this **helps reduce the amount of `unsafe` snippets out there** (_c.f._, the second commit of this PR: 09503fd1b3)
The fact that this getter is now expose for `UnsafeCell<T>` itself, will also help convey the idea that **`UnsafeCell` is not magical _w.r.t._ `&mut` accesses**, contrary to what some people incorrectly think.
- Even the standard library itself at some point had such a confusion, _c.f._ this comment where there is a mention of multi-threaded (and thus _shared_) access despite dealing with exclusive references over unique ownership: 59fb88d061/library/core/src/cell.rs (L498-L499)
r? @RalfJung
Use intra-doc links in core/src/iter when possible
Helps with #75080.
I also updated lots of links to use `fn()` instead of `fn` when possible.
@rustbot modify labels: T-doc A-intra-doc-links
r? @jyn514
Stabilize some Option methods as const
Stabilize the following methods of `Option` as const:
- `is_some`
- `is_none`
- `as_ref`
These methods are currently const under the unstable feature `const_option` (tracking issue: #67441).
I believe these methods to be eligible for stabilization because of the stabilization of #49146 (Allow if and match in constants) and the trivial implementations, see also: [PR#75463](https://github.com/rust-lang/rust/pull/75463).
Related: #76225
Remove MMX from Rust
Follow-up to https://github.com/rust-lang/stdarch/pull/890
This removes most of MMX from Rust (tests pass with small changes), keeping stable `is_x86_feature_detected!("mmx")` working.
Stabilize the following methods of `Option` as const:
- `is_some`
- `is_none`
- `as_ref`
Possible because of stabilization of #49146 (Allow if and match in constants).
Rollup of 15 pull requests
Successful merges:
- #76732 (Add docs for `BasicBlock`)
- #76832 (Let backends define custom targets)
- #76866 (Remove unused feature gates from library/ crates)
- #76875 (Move to intra-doc links in library/alloc/src/collections/binary_heap.rs)
- #76876 (Move to intra-doc links in collections/btree/map.rs and collections/linked_list.rs)
- #76877 (Move to intra-doc links in collections/vec_deque.rs and collections/vec_deque/drain.rs)
- #76878 (Move the version number to a plaintext file)
- #76883 (README.md: Remove prompts from code blocks)
- #76887 (Add missing examples on HashSet iter types)
- #76890 (use matches!() macro for simple if let conditions)
- #76891 (don't take `TyCtxt` by reference)
- #76910 (transmute: use diagnostic item)
- #76924 (Add tracking issue for feature(unix_socket_peek))
- #76926 (BTreeMap: code readability tweaks)
- #76940 (Don't allow implementing trait directly on type-alias-impl-trait)
Failed merges:
r? `@ghost`
transmute: use diagnostic item
closes#66075, we now have no remaining uses of `match_def_path` in the compiler while some uses still remain in `clippy`.
cc @RalfJung
Remove unused feature gates from library/ crates
Removes some unused feature gates from library crates. It's likely not a complete list as I only tested a subset for which it's more likely that it is unused.
Stabilize some Result methods as const
Stabilize the following methods of Result as const:
- `is_ok`
- `is_err`
- `as_ref`
A test is also included, analogous to the test for `const_option`.
These methods are currently const under the unstable feature `const_result` (tracking issue: #67520).
I believe these methods to be eligible for stabilization because of the stabilization of #49146 (Allow if and match in constants) and the trivial implementations, see also: [PR#75463](https://github.com/rust-lang/rust/pull/75463) and [PR#76135](https://github.com/rust-lang/rust/pull/76135).
Note: these methods are the only methods currently under the `const_result` feature, thus this PR results in the removal of the feature.
Related: #76225
This made too many assumptions about platforms, breaking some things.
Will need to be added later with a better way of gating on proper
alignment, without hardcoding cfg(target_arch)s.
Add associated constant `BITS` to all integer types
Recently I've regularly come across this snippet (in a few different crates, including `core` and `std`):
```rust
std::mem::size_of<usize>() * 8
```
I think it's time for a `usize::BITS`.
do not inline black_box when building for Miri
We cannot do the assembly trick in Miri, but let's at least make sure MIR inlining does not circumvent the black_box.
Also use black_box instead of local optimization barriers in a few const tests.
Add array_windows fn
This mimicks the functionality added by array_chunks, and implements a const-generic form of
`windows`. It makes egregious use of `unsafe`, but by necessity because the array must be
re-interpreted as a slice of arrays, and unlike array_chunks this cannot be done by casting the
original array once, since each time the index is advanced it needs to move one element, not
`N`.
I'm planning on adding more tests, but this should be good enough as a premise for the functionality.
Notably: should there be more functions overwritten for the iterator implementation/in general?
~~I've marked the issue as #74985 as there is no corresponding exact issue for `array_windows`, but it's based of off `array_chunks`.~~
Edit: See Issue #75027 created by @lcnr for tracking issue
~~Do not merge until I add more tests, please.~~
r? @lcnr