222 Commits

Author SHA1 Message Date
Jacob Pratt
5a0c9386a2
Rollup merge of #145381 - Gnurou:int_lowest_highest_one, r=jhpratt
Implement feature `int_lowest_highest_one` for integer and NonZero types

Tracking issue: rust-lang/rust#145203

Implement the accepted ACP rust-lang/rust#145203 for methods that find the index of the least significant (lowest) and most significant (highest) set bit in an integer for signed, unsigned, and NonZero types.

Also add unit tests for all these types.
2025-08-20 00:45:56 -04:00
许杰友 Jieyou Xu (Joe)
4327e69030
Rollup merge of #143730 - pascaldekloe:fmt-radix-trim, r=tgross35
fmt of non-decimal radix untangled

Have the implementation match its decimal counterpart.

* Digit table instead of conversion functions
* Correct buffer size per radix
* Elimination of dead code for negative
* No trait abstraction for integers

#### Original Performance
```
    fmt::write_10ints_bin                                                393.03ns/iter      +/- 1.41
    fmt::write_10ints_hex                                                316.84ns/iter      +/- 1.49
    fmt::write_10ints_oct                                                327.16ns/iter      +/- 0.46
```

#### Patched Performance
```
    fmt::write_10ints_bin                                                392.31ns/iter      +/- 3.05
    fmt::write_10ints_hex                                                302.41ns/iter      +/- 5.48
    fmt::write_10ints_oct                                                322.01ns/iter      +/- 3.82
```

r? tgross35
2025-08-19 19:42:03 +08:00
Stuart Cook
027c7a5d85
Rollup merge of #141744 - GrigorenkoPV:ip_from, r=Amanieu
Stabilize `ip_from`

Tracking issue: rust-lang/rust#131360

Stabilizes and const-stabilizes the following APIs:
```rust
// core::net
impl Ipv4Addr {
    pub const fn from_octets(octets: [u8; 4]) -> Ipv4Addr;
}
impl Ipv6Addr {
    pub const fn from_octets(octets: [u8; 16]) -> Ipv6Addr;
    pub const fn from_segments(segments: [u16; 8]) -> Ipv6Addr;
}
```

Closes rust-lang/rust#131360

```@rustbot``` label +needs-fcp
2025-08-19 14:18:15 +10:00
Alexandre Courbot
73d3d28bed Implement feature int_lowest_highest_one for integer and NonZero types
Implement the accepted ACP for methods that find the index of the least
significant (lowest) and most significant (highest) set bit in an
integer for signed, unsigned, and NonZero types.

Also add unit tests for all these types.
2025-08-18 18:59:44 +09:00
bors
99ba556567 Auto merge of #144081 - RalfJung:const-ptr-fragments, r=oli-obk
const-eval: full support for pointer fragments

This fixes https://github.com/rust-lang/const-eval/issues/72 and makes `swap_nonoverlapping` fully work in const-eval by enhancing per-byte provenance tracking with tracking of *which* of the bytes of the pointer this one is. Later, if we see all the same bytes in the exact same order, we can treat it like a whole pointer again without ever risking a leak of the data bytes (that encode the offset into the allocation). This lifts the limitation that was discussed quite a bit in https://github.com/rust-lang/rust/pull/137280.

For a concrete piece of code that used to fail and now works properly consider this example doing a byte-for-byte memcpy in const without using intrinsics:
```rust
use std::{mem::{self, MaybeUninit}, ptr};

type Byte = MaybeUninit<u8>;

const unsafe fn memcpy(dst: *mut Byte, src: *const Byte, n: usize) {
    let mut i = 0;
    while i < n {
        *dst.add(i) = *src.add(i);
        i += 1;
    }
}

const _MEMCPY: () = unsafe {
    let ptr = &42;
    let mut ptr2 = ptr::null::<i32>();
    // Copy from ptr to ptr2.
    memcpy(&mut ptr2 as *mut _ as *mut _, &ptr as *const _ as *const _, mem::size_of::<&i32>());
    assert!(*ptr2 == 42);
};
```
What makes this code tricky is that pointers are "opaque blobs" in const-eval, we cannot just let people look at the individual bytes since *we don't know what those bytes look like* -- that depends on the absolute address the pointed-to object will be placed at. The code above "breaks apart" a pointer into individual bytes, and then puts them back together in the same order elsewhere. This PR implements the logic to properly track how those individual bytes relate to the original pointer, and to recognize when they are in the right order again.

We still reject constants where the final value contains a not-fully-put-together pointer: I have no idea how one could construct an LLVM global where one byte is defined as "the 3rd byte of a pointer to that other global over there" -- and even if LLVM supports this somehow, we can leave implementing that to a future PR. It seems unlikely to me anyone would even want this, but who knows.^^

This also changes the behavior of Miri, by tracking the order of bytes with provenance and only considering a pointer to have valid provenance if all bytes are in the original order again. This is related to https://github.com/rust-lang/unsafe-code-guidelines/issues/558. It means one cannot implement XOR linked lists with strict provenance any more, which is however only of theoretical interest. Practically I am curious if anyone will show up with any code that Miri now complains about - that would be interesting data. Cc `@rust-lang/opsem`
2025-08-17 04:33:31 +00:00
Jacob Pratt
2776a21a4f
Rollup merge of #144963 - rossmacarthur-forks:stabilize-core-iter-chain, r=jhpratt
Stabilize `core::iter::chain`

Closes rust-lang/rust#125964
2025-08-15 18:13:29 -04:00
Guillaume Gomez
4bc1eb737d
Rollup merge of #142741 - a1phyr:fix_unsoundness, r=Mark-Simulacrum
Fix unsoundness in some tests

These tests were marked uninit bytes as initilized, which is unsound. Use initialized `MaybeUninit` instead.
2025-08-14 11:39:33 +02:00
Esteban Küber
74c3727b1f Remove unnecessary parentheses in assert!s 2025-08-10 21:59:04 +00:00
Stuart Cook
c15c2f0a42
Rollup merge of #145135 - Kivooeo:stabilize-duration_constructors_lite, r=ChrisDenton
Stabilize `duration_constructors_lite` feature

This closes [tracking issue](https://github.com/rust-lang/rust/issues/140881) and stabilises `Duration::from_hours` and `Duration::from_mins` while not touching a `duration_constructors` feature from the related [tracking issue (2)](https://github.com/rust-lang/rust/issues/120301)
2025-08-10 19:45:51 +10:00
Kivooeo
b5e2ba6775 Stabilize feature 2025-08-09 13:31:53 +05:00
Stuart Cook
7f77dfdda3
Rollup merge of #144923 - rocurley:float_tests_refactor_3, r=tgross35
Move several more float tests to floats/mod.rs

This PR moves several tests to `floats/mod.rs`, as discussed in https://github.com/rust-lang/rust/issues/141726. The tests moved are:

* `test_abs`
* `test_signum`
* `test_is_sign_positive`
* `test_is_sign_negative`
* `test_next_up`
* `test_next_down`
* `test_sqrt_domain`
* `test_clamp_min_greater_than_max`
* `test_clamp_min_is_nan`
* `test_clamp_max_is_nan`
* `test_total_cmp`

This covers all the "easy" tests: the ones that don't have a lot of precision-specific constants. It's not clear to me that it's worth migrating the others.

Each test is its own commit (with the exception of the clamp tests), so it may be easiest to review each commit individually.

r? tgross35
2025-08-09 13:58:45 +10:00
Stuart Cook
bd7af8a336
Rollup merge of #145057 - ShoyuVanilla:const-trait-tests-cleanup, r=petrochenkov
Clean up some resolved test regressions of const trait removals in std

cc rust-lang/rust#143871
2025-08-08 12:52:59 +10:00
Roger Curley
57cf40cd82 Hoist zero and one out into TestableFloat 2025-08-07 22:51:46 -04:00
Roger Curley
80bcd1a61f Consolidate total_cmp tests
This standardizes how max and min subnormals are generated. Since the
new method doesn't use powf, it also enables some of the tests for f128
that were previously disabled due to issues with powf (although it looks
like those issues were already fixed anyway). f16 signalling nan tests
previously disabled are not re-enabled, since the underlying LLVM issue
has not been closed.
2025-08-07 22:06:57 -04:00
Roger Curley
a5e4e7ab52 Consolidate clamp tests 2025-08-07 22:06:57 -04:00
Roger Curley
666bfcae21 Consolidate sqrt_domain tests 2025-08-07 22:06:57 -04:00
Roger Curley
8a65ce4360 Consolidate test_next_down 2025-08-07 22:06:57 -04:00
Roger Curley
f51f68b49a Consolidate test_next_up
Note that the behaviour of the f128 test is slightly changed to use the
same nan mask as is used in test_float_bits_conv, which is the behaviour
used by f16,f32,and f64.
2025-08-07 22:06:56 -04:00
Roger Curley
71973fcbdb Consolidate is_sign_negative tests 2025-08-07 22:06:56 -04:00
Roger Curley
951ef57b85 Consolidate is_positive tests 2025-08-07 22:06:56 -04:00
Roger Curley
83878ea228 Consolidate signum tests 2025-08-07 22:06:51 -04:00
Roger Curley
b4a3d3014e Consolidate abs tests
This clobbers the existing generic abs test, but it covers strictly
more, so that seems fine.
2025-08-07 22:03:30 -04:00
Shoyu Vanilla
34e5820e06 Clean up some resolved test regressions of const trait removals in std 2025-08-08 00:58:54 +09:00
Stuart Cook
b0fc38a362
Rollup merge of #140267 - jogru0:control_flow, r=dtolnay
implement continue_ok and break_ok for ControlFlow

Tracking issue: https://github.com/rust-lang/rust/issues/140266

r? ``````@dtolnay``````
2025-08-07 20:49:37 +10:00
okaneco
eee6f804a9 Renamed isolate_most_least_significant_one functions
libs-api has agreed to rename these functions to
`isolate_highest_one`/`isolate_lowest_one`
2025-08-05 16:37:04 -04:00
Ross MacArthur
b038197b16
Stabilize core::iter::chain 2025-08-05 17:05:23 +02:00
Evgenii Zheltonozhskii
9377e0af52 Constify additional Result functions 2025-08-01 08:55:50 +03:00
Ralf Jung
ba5b6b9ec4 const-eval: full support for pointer fragments 2025-07-30 08:13:58 +02:00
Jacob Pratt
48dfddd39e
Rollup merge of #144510 - orlp:fix-location-ord, r=ibraheemdev
Fix Ord, Eq and Hash implementation of panic::Location

Fixes https://github.com/rust-lang/rust/issues/144486.

Now properly compares/hashes the filename rather than the pointer to the string.
2025-07-29 18:55:18 -04:00
Orson Peters
05da623016 Fix Ord, Eq and Hash implementation of panic::Location
Faster equality compare

Add tests

Add missing files for tests
2025-07-29 22:15:44 +02:00
Stuart Cook
ed7d6a941d
Rollup merge of #144236 - yoshuawuyts:drop-guard, r=Mark-Simulacrum
Add `core::mem::DropGuard`

## 1.0 Summary

This PR introduces a new type `core::mem::DropGuard` which wraps a value and runs a closure when the value is dropped.

```rust
use core::mem::DropGuard;

// Create a new guard around a string that will
// print its value when dropped.
let s = String::from("Chashu likes tuna");
let mut s = DropGuard::new(s, |s| println!("{s}"));

// Modify the string contained in the guard.
s.push_str("!!!");

// The guard will be dropped here, printing:
// "Chashu likes tuna!!!"
```

## 2.0 Motivation

A number of programming languages include constructs like `try..finally` or `defer` to run code as the last piece of a particular sequence, regardless of whether an error occurred. This is typically used to clean up resources, like closing files, freeing memory, or unlocking resources. In Rust we use the `Drop` trait instead, allowing us to [never having to manually close sockets](https://blog.skylight.io/rust-means-never-having-to-close-a-socket/).

While `Drop` (and RAII in general) has been working incredibly well for Rust in general, sometimes it can be a little verbose to setup. In particular when upholding invariants are local to functions, having a quick inline way to setup an `impl Drop` can be incredibly convenient. We can see this in use in the Rust stdlib, which has a number of private `DropGuard` impls used internally:

- [library/alloc/src/vec/drain.rs](9982d6462b/library/alloc/src/vec/drain.rs (L177))
- [library/alloc/src/boxed/thin.rs](9982d6462b/library/alloc/src/boxed/thin.rs (L362))
- [library/alloc/src/slice.rs](9982d6462b/library/alloc/src/slice.rs (L413))
- [library/alloc/src/collections/linked_list.rs](9982d6462b/library/alloc/src/collections/linked_list.rs (L1135))
- [library/alloc/src/collections/binary_heap/mod.rs](9982d6462b/library/alloc/src/collections/binary_heap/mod.rs (L1816))
- [library/alloc/src/collections/btree/map.rs](9982d6462b/library/alloc/src/collections/btree/map.rs (L1715))
- [library/alloc/src/collections/vec_deque/drain.rs](9982d6462b/library/alloc/src/collections/vec_deque/drain.rs (L95))
- [library/alloc/src/vec/into_iter.rs](9982d6462b/library/alloc/src/vec/into_iter.rs (L488))
- [library/std/src/os/windows/process.rs](9982d6462b/library/std/src/os/windows/process.rs (L320))
- [tests/ui/process/win-proc-thread-attributes.rs](9982d6462b/tests/ui/process/win-proc-thread-attributes.rs (L17))

## 3.0 Design

This PR implements what can be considered about the simplest possible design:

1. A single type `DropGuard` which takes both a generic type `T` and a closure `F`.
2. `Deref` + `DerefMut` impls to make it easy to work with the `T` in the guard.
3. An `impl Drop` on the guard which calls the closure `F` on drop.
4. An inherent `fn into_inner` which takes the type `T` out of the guard without calling the closure `F`.

Notably this design does not allow divergent behavior based on the type of drop that has occurred. The [`scopeguard` crate](https://docs.rs/scopeguard/latest/scopeguard/index.html) includes additional `on_success` and `on_onwind` variants which can be used to branch on unwind behavior instead. However [in a lot of cases](https://github.com/rust-lang/rust/issues/143612#issuecomment-3053928328) this doesn’t seem necessary, and using the arm/disarm pattern seems to provide much the same functionality:

```rust
let guard = DropGuard::new((), |s| ...);  // 1. Arm the guard
other_function();                         // 2. Perform operations
guard.into_inner();                       // 3. Disarm the guard
```

`DropGuard` combined with this pattern seems like it should cover the vast majority of use cases for quick, inline destructors. It certainly seems like it should cover all existing uses in the stdlib, as well as all existing uses in crates like [hashbrown](https://github.com/search?q=repo%3Arust-lang%2Fhashbrown%20guard&type=code).

## 4.0 Acknowledgements

This implementation is based on the [mini-scopeguard crate](https://github.com/yoshuawuyts/mini-scopeguard) which in turn is based on the [scopeguard  crate](https://docs.rs/scopeguard). The implementations only differ superficially; because of the nature of the problem there is only really one obvious way to structure the solution. And the scopeguard crate got that right!

## 5.0 Conclusion

This PR adds a new type `core::mem::DropGuard` to the stdlib which adds a small convenience helper to create inline destructors with. This would bring the majority of the functionality of the `scopeguard` crate into the stdlib, which is the [49th most downloaded crate](https://crates.io/crates?sort=downloads) on crates.io (387 million downloads).

Given the actual implementation of `DropGuard` is only around 60 lines, it seems to hit that sweet spot of low-complexity / high-impact that makes for a particularly efficient stdlib addition. Which is why I’m putting this forward for consideration; thanks!
2025-07-29 16:16:41 +10:00
Yosh
68f08c5dd9
Add core::mem::DropGuard
Fix CI for drop_guard

fix CI

fix all tidy lints

fix tidy link

add first batch of feedback from review

Add second batch of feedback from review

add third batch of feedback from review

fix failing test

Update library/core/src/mem/drop_guard.rs

Co-authored-by: Ruby Lazuli <general@patchmixolydic.com>

fix doctests

Implement changes from T-Libs-API review

And start tracking based on the tracking issue.

fix tidy lint
2025-07-28 12:12:40 +02:00
Scott McMurray
173926da2b Remove [T]::array_chunks(_mut) 2025-07-27 23:03:07 -07:00
Matthias Krüger
c9541a2bf8
Rollup merge of #144331 - jplatte:matches-allow-non_exhaustive_omitted_patterns, r=Nadrieril
Disable non_exhaustive_omitted_patterns within matches! macro

Closes rust-lang/rust#117304.

I believe I can skip all of the bootstrap stuff mentioned in https://github.com/rust-lang/rust/issues/117304#issuecomment-1784414453 due to https://blog.rust-lang.org/inside-rust/2025/05/29/redesigning-the-initial-bootstrap-sequence/, right?

cc `@Jules-Bertholet`
2025-07-26 15:27:58 +02:00
Pascal S. de Kloe
7704a39685 fmt benchmarks for binary, octal and hex 2025-07-25 16:03:47 +02:00
Ralf Jung
37480bc9e6 coretests/num: use ldexp instead of hard-coding a power of 2 2025-07-23 16:33:58 +02:00
Jonas Platte
0e30629600
Add regression test for matches! + non_exhaustive_omitted_patterns lint 2025-07-23 14:35:44 +02:00
Matthias Krüger
a8c2e540ec
Rollup merge of #143604 - nxsaken:const_float_round_methods, r=RalfJung
Stabilize `const_float_round_methods`

Closes rust-lang/rust#141555, waiting for FCP.
2025-07-20 08:56:06 +02:00
Nurzhan Sakén
ca01e7de6f Stabilize const_float_round_methods 2025-07-20 00:08:58 +04:00
Rémy Rakic
4ef92bec5a fix load-bearing typo 2025-07-19 15:17:04 +00:00
Matthias Krüger
fff53f1dbb
Rollup merge of #141076 - the8472:fix-zip-panic-safety2, r=workingjubilee
fix Zip unsoundness (again)

Some history: The Zip TrustedRandomAccess specialization has tried to emulate the side-effects of the naive implementation for a long time, including backwards iteration. #82292 tried to fix unsoundness (#82291) in that side-effect-preservation code, but this introduced some panic-safety unsoundness (#86443), but the fix #86452 didn't fix it for nested Zip iterators (#137255).

Rather than piling yet another fix ontop of this heap of fixes this PR reduces the number of cases in which side-effects will be preserved; the necessary API guarantee change was approved in #83791 but we haven't made use of that so far.

fixes #137255
2025-07-19 08:55:33 +02:00
León Orell Valerian Liehr
b9fd2bccfa
Rollup merge of #143829 - a1phyr:trim_borrowed_buf, r=ChrisDenton
Trim `BorrowedCursor` API

This PR removes some method from the unstable `BorrowedCursor` type. A rational for each change can be found in the message of each commit.

I don't think that an ACP is required for this, please tell me if it is not the case.

Cc rust-lang/rust#78485 rust-lang/rust#117693
2025-07-17 03:58:32 +02:00
Samuel Tardieu
096a66d8d8
Rollup merge of #143738 - rocurley:float_tests_refactor_2, r=tgross35
Move several float tests to floats/mod.rs

This PR moves several tests to `floats/mod.rs`, as discussed in https://github.com/rust-lang/rust/issues/141726. The tests moved are:

- `test_num_f*`
- `test_infinity`
- `test_neg_infinity`
- `test_zero`
- `test_neg_zero`
- `test_one`
- `test_is_nan`
- `test_is_infinite`
- `test_is_finite`
- `test_is_normal`
- `test_classify`

Each test is its own commit, so it may be easiest to review each commit individually.

r? tgross35
2025-07-16 17:06:40 +02:00
bors
7f2065a4ba Auto merge of #142885 - a1phyr:borrowed_cursor_to_buf, r=Mark-Simulacrum
core: Add `BorrowedCursor::with_unfilled_buf`

Implementation of https://github.com/rust-lang/libs-team/issues/367.

This mainly adds `BorrowedCursor::with_unfilled_buf`, with enables using the unfilled part of a cursor as a `BorrowedBuf`.

Note that unlike the ACP, `BorrowedCursor::unfilled_buf` was moved to a `From` conversion. This is more consistent with other ways of creating a `BorrowedBuf` and hides a bit this conversion that requires unsafe code to be used correctly.

Cc rust-lang/rust#78485 rust-lang/rust#117693
2025-07-14 23:45:18 +00:00
bors
e9182f195b Auto merge of #143461 - folkertdev:cfg-select-builtin-macro, r=petrochenkov
make `cfg_select` a builtin macro

tracking issue: https://github.com/rust-lang/rust/issues/115585

This parses mostly the same as the `macro cfg_select` version, except:

1. wrapping in double brackets is no longer supported (or needed): `cfg_select {{ /* ... */ }}` is now rejected.
2. in an expression context, the rhs is no longer wrapped in a block, so that this now works:
  ```rust
  fn main() {
      println!(cfg_select! {
          unix => { "foo" }
          _ => { "bar" }
      });
  }
  ```
3. a single wildcard rule is now supported: `cfg_select { _ => 1 }` now works

I've also added an error if none of the rules evaluate to true, and warnings for any arms that follow the `_` wildcard rule.

cc `@traviscross` if I'm missing any feature that should/should not be included
r? `@petrochenkov` for the macro logic details
2025-07-13 18:34:13 +00:00
Folkert de Vries
3689b80b75
make cfg_select a builtin macro 2025-07-13 14:34:40 +02:00
Roger Curley
79769f2d5b Consolidate classify tests 2025-07-11 10:41:24 -04:00
Roger Curley
d2c1900086 Consolidate is_normal tests 2025-07-11 10:41:24 -04:00
Roger Curley
7dd2811b2a Consolidate is_finite tests 2025-07-11 10:41:24 -04:00
Roger Curley
e3d83679cb Consolidate is_infinite tests 2025-07-11 10:41:24 -04:00