Commit Graph

752 Commits

Author SHA1 Message Date
Eduardo Sánchez Muñoz
fb9e1f73b3 Stabilize (const_)slice_ptr_len and (const_)slice_ptr_is_empty_nonnull 2024-04-12 21:23:20 +02:00
Matthias Krüger
cb7f1eec04
Rollup merge of #122291 - lilasta:stabilize_const_location_fields, r=dtolnay
Stabilize `const_caller_location` and `const_location_fields`

Closes #102911. Closes #76156.

tests: [library/core/tests/panic/location.rs](3521a2f2f3/library/core/tests/panic/location.rs)

API:
```rust
// core::panic::location
impl Location {
    pub const fn caller() -> &'static Location<'static>;
    pub const fn file(&self) -> &str;
    pub const fn line(&self) -> u32;
    pub const fn column(&self) -> u32;
}
```
2024-04-06 13:00:05 +02:00
Jacob Pratt
de2cb0d76c
Rollup merge of #123206 - stepancheg:pointee-metadata-freeze, r=Amanieu
Require Pointee::Metadata to be Freeze

So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488

r? joboet
2024-04-04 21:16:55 -04:00
bors
a77322c16f Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwco
Add `Ord::cmp` for primitives as a `BinOp` in MIR

Update: most of this OP was written months ago.  See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review.

---

There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches.  Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level:

1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest.
2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations.

Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic.  Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical.  Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)?  But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)?  And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers.  Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it.

As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR.  The best way to see that is with 8811efa88b (diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113) -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks.  Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues.  (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.)

---

r? `@ghost`
But first I should check that perf is ok with this
~~...and my true nemesis, tidy.~~
2024-04-02 19:21:44 +00:00
Stepan Koltsov
8f5a28e0aa Require Pointee::Metadata to be Freeze
So pointee metadata can be used in anonymous statics.

This is prerequisite for implementing ThinBox without allocation for
ZST.

See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488
2024-03-31 03:35:17 +01:00
bors
1aedc9640c Auto merge of #123181 - stepancheg:pointee-metadata-debug, r=the8472,Amanieu
Require Debug for Pointee::Metadata

Useful for debugging.
2024-03-31 00:09:41 +00:00
George Bateman
3855b8bb60
Make {integer}::from_str_radix constant 2024-03-30 12:43:58 +00:00
Aria Beingessner
ea92faec49 stabilize ptr.is_aligned, move ptr.is_aligned_to to a new feature gate
This is an alternative to #121920
2024-03-29 19:59:46 -04:00
Stepan Koltsov
b110cb3dc6 Require Debug for Pointee::Metadata
Useful for debugging
2024-03-29 03:53:29 +00:00
Scott McMurray
c59e93c753 Address PR feedback 2024-03-24 17:42:35 -07:00
Scott McMurray
3da115a93b Add+Use mir::BinOp::Cmp 2024-03-23 23:23:41 -07:00
lilasta
d324d6de0e Stabilize const_caller_location and const_location_fields 2024-03-21 22:19:57 +09:00
Mark Rousskov
02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
Yotam Ofek
d0c0887498 Add as_(mut_)ptr and as_(mut_)slice to raw array pointers 2024-03-16 20:15:30 +00:00
The 8472
be33586adc fix unsoundness in Step::forward_unchecked for signed integers 2024-03-14 00:57:02 +01:00
Andrew Wock
0a0074980f Implement MaybeUninit::fill{,_with,_from}
ACP: rust-lang/libs-team#156

Signed-off-by: Andrew Wock <ajwock@gmail.com>
2024-03-05 15:27:35 -05:00
bors
b0d3e04ca9 Auto merge of #120393 - Urgau:rfc3373-non-local-defs, r=WaffleLapkin
Implement RFC 3373: Avoid non-local definitions in functions

This PR implements [RFC 3373: Avoid non-local definitions in functions](https://github.com/rust-lang/rust/issues/120363).
2024-02-25 19:11:06 +00:00
Ralf Jung
b58f647d54 rename ptr::invalid -> ptr::without_provenance
also introduce ptr::dangling matching NonNull::dangling
2024-02-21 20:15:52 +01:00
bors
6672c16afc Auto merge of #121204 - cuviper:flatten-one-shot, r=the8472
Specialize flattening iterators with only one inner item

For iterators like `Once` and `option::IntoIter` that only ever have a
single item at most, the front and back iterator states in `FlatMap` and
`Flatten` are a waste, as they're always consumed already. We can use
specialization for these types to simplify the iterator methods.

It's a somewhat common pattern to use `flatten()` for options and
results, even recommended by [multiple][1] [clippy][2] [lints][3]. The
implementation is more efficient with `filter_map`, as mentioned in
[clippy#9377], but this new specialization should close some of that
gap for existing code that flattens.

[1]: https://rust-lang.github.io/rust-clippy/master/#filter_map_identity
[2]: https://rust-lang.github.io/rust-clippy/master/#option_filter_map
[3]: https://rust-lang.github.io/rust-clippy/master/#result_filter_map
[clippy#9377]: https://github.com/rust-lang/rust-clippy/issues/9377
2024-02-17 20:18:54 +00:00
Urgau
1b733558bf Allow newly added non_local_definitions in std 2024-02-17 13:59:46 +01:00
bors
405b22f1a3 Auto merge of #120741 - a1phyr:safe_buffer_advance, r=m-ou-se
Make `io::BorrowedCursor::advance` safe

This also keeps the old `advance` method under `advance_unchecked` name.

This makes pattern like `std::io::default_read_buf` safe to write.
2024-02-17 00:23:15 +00:00
Josh Stone
974bc455ee Specialize flattening iterators with only one inner item
For iterators like `Once` and `option::IntoIter` that only ever have a
single item at most, the front and back iterator states in `FlatMap` and
`Flatten` are a waste, as they're always consumed already. We can use
specialization for these types to simplify the iterator methods.

It's a somewhat common pattern to use `flatten()` for options and
results, even recommended by [multiple][1] [clippy][2] [lints][3]. The
implementation is more efficient with `filter_map`, as mentioned in
[clippy#9377], but this new specialization should close some of that
gap for existing code that flattens.

[1]: https://rust-lang.github.io/rust-clippy/master/#filter_map_identity
[2]: https://rust-lang.github.io/rust-clippy/master/#option_filter_map
[3]: https://rust-lang.github.io/rust-clippy/master/#result_filter_map
[clippy#9377]: https://github.com/rust-lang/rust-clippy/issues/9377
2024-02-16 13:49:29 -08:00
bors
ae9d7b0c64 Auto merge of #116385 - kornelski:maybe-rename, r=Amanieu
Rename MaybeUninit::write_slice

A step to push #79995 forward.

https://github.com/rust-lang/libs-team/issues/122 also suggested to make them inherent methods, but they can't be — they'd conflict with slice's regular methods.
2024-02-16 14:11:10 +00:00
Markus Reiter
a90cc05233
Replace NonZero::<_>::new with NonZero::new. 2024-02-15 08:09:42 +01:00
Markus Reiter
746a58d435
Use generic NonZero internally. 2024-02-15 08:09:42 +01:00
Matthias Krüger
ba405a47bd
Rollup merge of #120307 - djc:duration-constructors, r=Mark-Simulacrum
core: add Duration constructors

Add more `Duration` constructors.

Tracking issue: #120301.

These match similar convenience constructors available on both `chrono::Duration` and `time::Duration`.

What's the best ordering for these with respect to the existing constructors?
2024-02-11 08:25:42 +01:00
Mark Rousskov
9a5034a20e Step all bootstrap cfgs forward
This also takes care of other bootstrap-related changes.
2024-02-08 07:44:34 -05:00
Benoît du Garreau
0a42a540c6 Make io::BorrowedCursor::advance safe
This also keeps the old `advance` method under `advance_unchecked` name.

This makes pattern like `std::io::default_read_buf` safe to write.
2024-02-07 16:46:28 +01:00
r0cky
c7519d42c2 Update tests 2024-02-07 10:42:01 +08:00
Ralf Jung
0184ca695b revert stabilization of const_intrinsic_copy 2024-02-05 20:58:31 +01:00
Matthias Krüger
c9ab37bf4f
Rollup merge of #103522 - Dylan-DPC:76118/array-methods-stab, r=dtolnay
stabilise array methods

Closes #76118

Stabilises the remaining array methods

FCP is yet to be carried out for this

There wasn't a clear consensus on the naming, but all the other alternatives had some flaws as discussed in the tracking issue and there was a silence on this issue for a year
2024-01-26 23:15:47 +01:00
Dirkjan Ochtman
e077ff0eed
core: add Duration constructors 2024-01-24 14:24:57 +01:00
Oli Scherer
9a20cf1697 Revert "Auto merge of #118133 - Urgau:stabilize_trait_upcasting, r=WaffleLapkin"
This reverts commit 6d2b84b3ed, reversing
changes made to 73bc12199e.
2024-01-22 14:24:31 +00:00
bors
fa404339c9 Auto merge of #85528 - the8472:iter-markers, r=dtolnay
Implement iterator specialization traits on more adapters

This adds

* `TrustedLen` to `Skip` and `StepBy`
* `TrustedRandomAccess` to `Skip`
* `InPlaceIterable` and `SourceIter` to  `Copied` and `Cloned`

The first two might improve performance in the compiler itself since `skip` is used in several places. Constellations that would exercise the last point are probably rare since it would require an owning iterator that has references as Items somewhere in its iterator pipeline.

Improvements for `Skip`:

```
# old
test iter::bench_skip_trusted_random_access                     ... bench:       8,335 ns/iter (+/- 90)

# new
test iter::bench_skip_trusted_random_access                     ... bench:       2,753 ns/iter (+/- 27)
```
2024-01-21 11:17:46 +00:00
Nadrieril
3cd378cc15
Rollup merge of #119081 - jstasiak:is-ipv4-mapped, r=dtolnay
Add Ipv6Addr::is_ipv4_mapped

This change consists of cherry-picking the content from the original PR[1], which got closed due to inactivity, and applying the following changes:

* Resolving merge conflicts (obviously)
* Linked to to_ipv4_mapped instead of to_ipv4 in the documentation (seems more appropriate)
* Added the must_use and rustc_const_unstable attributes the original didn't have

I think it's a reasonably useful method to have.

[1] https://github.com/rust-lang/rust/pull/86490
2024-01-21 06:38:35 +01:00
Nadrieril
e8d1c2ef9c
Rollup merge of #118811 - EbbDrop:is-sorted-by-bool, r=Mark-Simulacrum
Use `bool` instead of `PartiolOrd` as return value of the comparison closure in `{slice,Iteraotr}::is_sorted_by`

Changes the function signature of the closure given to `{slice,Iteraotr}::is_sorted_by` to return a `bool` instead of a `PartiolOrd` as suggested by the libs-api team here: https://github.com/rust-lang/rust/issues/53485#issuecomment-1766411980.

This means these functions now return true if the closure returns true for all the pairs of values.
2024-01-21 06:38:35 +01:00
EbbDrop
606eeb84ad Use bool instead of PartiolOrd in is_sorted_by 2024-01-20 21:38:34 +01:00
Matthias Krüger
6f67208d72
Rollup merge of #118799 - GKFX:stabilize-simple-offsetof, r=wesleywiser
Stabilize single-field offset_of

This PR stabilizes offset_of for a single field. There has been some further discussion at https://github.com/rust-lang/rust/issues/106655 about whether this is advisable; I'm opening the PR anyway so that the code is available.
2024-01-20 09:37:26 +01:00
Matthias Krüger
17c95b6330
Rollup merge of #113142 - the8472:opt-cstr-display, r=Mark-Simulacrum
optimize EscapeAscii's Display  and CStr's Debug

```
old:
    ascii::bench_ascii_escape_display_mixed      17.97µs/iter +/- 204.00ns
    ascii::bench_ascii_escape_display_no_escape 545.00ns/iter   +/- 6.00ns
new:
    ascii::bench_ascii_escape_display_mixed      4.99µs/iter +/- 56.00ns
    ascii::bench_ascii_escape_display_no_escape 91.00ns/iter  +/- 1.00ns
```
2024-01-20 09:37:25 +01:00
George Bateman
803b810eac
Remove feature(offset_of) from tests 2024-01-19 20:38:51 +00:00
George Bateman
615946db4f
Stabilize simple offset_of 2024-01-19 20:38:51 +00:00
Matthias Krüger
455382d8df
Rollup merge of #119984 - kpreid:waker-noop, r=dtolnay
Change return type of unstable `Waker::noop()` from `Waker` to `&Waker`.

The advantage of this is that it does not need to be assigned to a variable to be used in a `Context` creation, which is the most common thing to want to do with a noop waker. It also avoids unnecessarily executing the dynamically dispatched drop function when the noop waker is dropped.

If an owned noop waker is desired, it can be created by cloning, but the reverse is harder to do since it requires declaring a constant. Alternatively, both versions could be provided, like `futures::task::noop_waker()` and `futures::task::noop_waker_ref()`, but that seems to me to be API clutter for a very small benefit, whereas having the `&'static` reference available is a large reduction in boilerplate.

[Previous discussion on the tracking issue starting here](https://github.com/rust-lang/rust/issues/98286#issuecomment-1862159766)
2024-01-19 19:27:01 +01:00
Matthias Krüger
64461dab01
Rollup merge of #117561 - tgross35:split-array, r=scottmcm
Stabilize `slice_first_last_chunk`

This PR does a few different things based around stabilizing `slice_first_last_chunk`. They are split up so this PR can be by-commit reviewed, I can move parts to a separate PR if desired.

This feature provides a very elegant API to extract arrays from either end of a slice, such as for parsing integers from binary data.

## Stabilize `slice_first_last_chunk`

ACP: https://github.com/rust-lang/libs-team/issues/69
Implementation: https://github.com/rust-lang/rust/issues/90091
Tracking issue: https://github.com/rust-lang/rust/issues/111774

This stabilizes the functionality from https://github.com/rust-lang/rust/issues/111774:

```rust
impl [T] {
    pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
    pub fn split_first_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
    pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>;
    pub fn split_last_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T], &mut [T; N])>;
}
```

Const stabilization is included for all non-mut methods, which are blocked on `const_mut_refs`. This change includes marking the trivial function `slice_split_at_unchecked` const-stable for internal use (but not fully stable).

## Remove `split_array` slice methods

Tracking issue: https://github.com/rust-lang/rust/issues/90091
Implementation: https://github.com/rust-lang/rust/pull/83233#pullrequestreview-780315524

This PR also removes the following unstable methods from the `split_array` feature, https://github.com/rust-lang/rust/issues/90091:

```rust
impl<T> [T] {
    pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]);
    pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]);

    pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]);
    pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]);
}
```

This is done because discussion at #90091 and its implementation PR indicate a strong preference for nonpanicking APIs that return `Option`. The only difference between functions under the `split_array` and `slice_first_last_chunk` features is `Option` vs. panic, so remove the duplicates as part of this stabilization.

This does not affect the array methods from `split_array`. We will want to revisit these once `generic_const_exprs` is further along.

## Reverse order of return tuple for `split_last_chunk{,_mut}`

An unresolved question for #111774 is whether to return `(preceding_slice, last_chunk)` (`(&[T], &[T; N])`) or the reverse (`(&[T; N], &[T])`), from `split_last_chunk` and `split_last_chunk_mut`. It is currently implemented as `(last_chunk, preceding_slice)` which matches `split_last -> (&T, &[T])`. The first commit changes these to `(&[T], &[T; N])` for these reasons:

- More consistent with other splitting methods that return multiple values: `str::rsplit_once`, `slice::split_at{,_mut}`, `slice::align_to` all return tuples with the items in order
- More intuitive (arguably opinion, but it is consistent with other language elements like pattern matching `let [a, b, rest @ ..] ...`
- If we ever added a varidic way to obtain multiple chunks, it would likely return something in order: `.split_many_last::<(2, 4)>() -> (&[T], &[T; 2], &[T; 4])`
- It is the ordering used in the `rsplit_array` methods

I think the inconsistency with `split_last` could be acceptable in this case, since for `split_last` the scalar `&T` doesn't have any internal order to maintain with the other items.

## Unresolved questions

Do we want to reserve the same names on `[u8; N]` to avoid inference confusion? https://github.com/rust-lang/rust/pull/117561#issuecomment-1793388647

---

`slice_first_last_chunk` has only been around since early 2023, but `split_array` has been around since 2021.

`@rustbot` label -T-libs +T-libs-api -T-libs +needs-fcp
cc `@rust-lang/wg-const-eval,` `@scottmcm` who raised this topic, `@clarfonthey` implementer of `slice_first_last_chunk` `@jethrogb` implementer of `split_array`

Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Stabilizing.20array-from-slice.20*something*.3F

Fixes: #111774
2024-01-19 19:26:59 +01:00
Kevin Reid
c48cdfe8ee Remove unnecessary lets and borrowing from Waker::noop() usage.
`Waker::noop()` now returns a `&'static Waker` reference, so it can be
passed directly to `Context` creation with no temporary lifetime issue.
2024-01-17 12:00:27 -08:00
klensy
aa696c5a22 apply fmt 2024-01-11 15:04:48 +03:00
Jakub Stasiak
4621357d14 Make is_global/is_unicast_global special address handling complete
IANA explicitly documents 192.0.0.9/32, 192.0.0.9/32 and 2001:30::/28 as
globally reachable[1][2] and the is_global implementations declare
following IANA so let's make this happen.

In case of 2002::/16 IANA says N/A so I think it's safe to say we
shouldn't return true there either.

[1] https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
[2] https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
2024-01-11 01:03:34 +01:00
The8472
a2a7caacf7 implement TrustedLen for StepBy 2024-01-10 18:55:34 +01:00
Trevor Gross
500d6f6479 Stabilize slice_first_last_chunk
This stabilizes all methods under `slice_first_last_chunk`.

Additionally, it const stabilizes the non-mut functions and moves the `_mut`
functions under `const_slice_first_last_chunk`. These are blocked on
`const_mut_refs`.

As part of this change, `slice_split_at_unchecked` was marked const-stable for
internal use (but not fully stable).
2024-01-10 03:06:49 -05:00
Michael Goulet
8bea1df254
Rollup merge of #119583 - AngelicosPhosphoros:const_assume, r=RalfJung
Make `intrinsics::assume` const stable

Closes https://github.com/rust-lang/rust/issues/76972
Blocks https://github.com/rust-lang/rust/pull/119452

Approved in https://github.com/rust-lang/rust/pull/119452#issuecomment-1875741678

r? `@RalfJung`
2024-01-05 10:57:23 -05:00
AngelicosPhosphoros
59c76fb21b Make intrinsics::assume const stable
Closes https://github.com/rust-lang/rust/issues/76972
Blocks https://github.com/rust-lang/rust/pull/119452

Approved in https://github.com/rust-lang/rust/pull/119452#issuecomment-1875741678
2024-01-04 19:14:31 +01:00