Commit Graph

9538 Commits

Author SHA1 Message Date
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
bors
cb6785f73d Auto merge of #143289 - scottmcm:remove-array-chunks, r=jhpratt
Remove `[T]::array_chunks(_mut)`

Since libs-api is proposing as much in https://github.com/rust-lang/rust/issues/74985#issuecomment-3024465102

Closes rust-lang/rust#74985
Closes rust-lang/rust#76354

try-job: dist-various-1
try-job: dist-various-2
2025-07-29 02:27:52 +00:00
usamoi
71920e265c fix Atomic*::as_ptr wording 2025-07-28 20:41:24 +08: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
xonx
c340233769 fixed typo chunks->as_chunks 2025-07-28 15:05:36 +05:30
Matthias Krüger
e36b844b4e Rollup merge of #144472 - okaneco:char_bound, r=Mark-Simulacrum
str: Mark unstable `round_char_boundary` feature functions as const

Mark `floor_char_boundary`, `ceil_char_boundary` const
Simplify the implementations, reducing the number of arithmetic operations

It seems unnecessary to do the lower/upper bounds calculations and extra slicing when we can jump straight to inspecting the bytes, assuming the underlying data is valid UTF-8.

Tracking issue https://github.com/rust-lang/rust/issues/93743
2025-07-28 08:36:53 +02:00
Matthias Krüger
a9f58bff03 Rollup merge of #144072 - usamoi:docs, r=Mark-Simulacrum
update `Atomic*::from_ptr` and `Atomic*::as_ptr` docs

Since https://github.com/rust-lang/rust/pull/128778, it's allowed to perform atomic read and non-atomic read on the same atomic at the same time. Update the `Atomic*::from_ptr` and `Atomic*::as_ptr` documentation to remove expressions such as `not allowed to mix atomic and non-atomic accesses`.

see also [std::sync::atomic](https://doc.rust-lang.org/std/sync/atomic/index.html#memory-model-for-atomic-accesses)
2025-07-28 08:36:51 +02:00
Scott McMurray
173926da2b Remove [T]::array_chunks(_mut) 2025-07-27 23:03:07 -07:00
Ralf Jung
d12ecde365 constify with_exposed_provenance 2025-07-27 17:00:31 +02:00
Scott McMurray
51b0416c19 Use cast_array in core 2025-07-26 17:06:02 -07:00
Scott McMurray
7ead5764a8 Implement ptr_cast_array 2025-07-26 13:22:24 -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
Josh Triplett
56c5b1df94 Add parentheses around expression arguments to ..
This makes it easier for humans to parse, and improves the result of
potential future automatic formatting.
2025-07-25 22:02:09 -07:00
Josh Triplett
b6c54a97b3 Avoid placing // FIXME comments inside doc code blocks
This leads tools like rustfmt to get confused, because the doc code
block effectively spans two doc comments. As a result, the tools think
the first code block is unclosed, and the subsequent terminator opens a
new block.

Move the FIXME comments outside the doc code blocks, instead.
2025-07-25 22:02:09 -07:00
Josh Triplett
715088094c Improve and regularize comment placement in doc code
Because doc code does not get automatically formatted, some doc code has
creative placements of comments that automatic formatting can't handle.
Reformat those comments to make the resulting code support standard Rust
formatting without breaking; this is generally an improvement to
readability as well.

Some comments are not indented to the prevailing indent, and are instead
aligned under some bit of code. Indent them to the prevailing indent,
and put spaces *inside* the comments to align them with code.

Some comments span several lines of code (which aren't the line the
comment is about) and expect alignment. Reformat them into one comment
not broken up by unrelated intervening code.

Some comments are placed on the same line as an opening brace, placing
them effectively inside the subsequent block, such that formatting would
typically format them like a line of that block. Move those comments to
attach them to what they apply to.

Some comments are placed on the same line as a one-line braced block,
effectively attaching them to the closing brace, even though they're
about the code inside the block. Reformat to make sure the comment will
stay on the same line as the code it's commenting.
2025-07-25 22:02:09 -07:00
okaneco
7f7d343400 str: Mark unstable round_char_boundary feature functions as const
Mark `floor_char_boundary`, `ceil_char_boundary` const
Simplify the implementations, reducing the number of arithmetic operations
2025-07-25 22:09:42 -04:00
Pascal S. de Kloe
c6ac515a2b fmt of non-decimals is always non-negative due to the two's-complement output 2025-07-25 16:02:59 +02:00
Matthias Krüger
a2681f943c Rollup merge of #144314 - kornelski:pivot-safely, r=jhpratt
Hint that choose_pivot returns index in bounds

Instead of using `unsafe` in multiple places, one `hint::assert_unchecked` allows use of safe code instead.

Part of #rust-lang/rust#144326
2025-07-25 11:16:37 +02:00
Matthias Krüger
e3b07352a6 Rollup merge of #143970 - SunkenPotato:update_mem_copy_docs, r=scottmcm
Update core::mem::copy documentation

Update the documentation of `core::mem::copy` to include a `const` on the definition of the function.
2025-07-25 11:16:34 +02:00
Matthias Krüger
dd159ee24e Rollup merge of #143424 - hkBst:auto-deref, r=jhpratt
clippy fix: rely on autoderef

Changes instances of `&**self` to `self`.
2025-07-25 11:16:34 +02:00
León Orell Valerian Liehr
488fc49e05 Rollup merge of #144278 - Qelxiros:rev-into-inner, r=tgross35
add Rev::into_inner

Tracking issue: rust-lang/rust#144277
2025-07-24 15:08:25 +02:00
Jeremy Smart
6f1b56c499 add Rev::into_inner 2025-07-23 22:03:03 -04:00
Zachary S
477814a3e4 Document (internally) that Range*<&T> as RangeBounds<T> impls are intentionally not T: ?Sized, and document (publically) an alternative. 2025-07-23 15:39:03 -05:00
Jonas Platte
8a1b20ed60 Disable non_exhaustive_omitted_patterns within matches! macro 2025-07-23 14:26:06 +02:00
Kornel
01fdafc9aa Hint that choose_pivot returns index in bounds 2025-07-23 12:01:44 +01:00
Ralf Jung
de1b999ff6 atomicrmw on pointers: move integer-pointer cast hacks into backend 2025-07-23 08:32:55 +02:00
gewitternacht
623317eb5e add links to collections 2025-07-23 01:44:18 +02:00
gewitternacht
cdbcd72f34 remove trailing whitespace 2025-07-23 00:41:48 +02:00
gewitternacht
30033b45bb document assumptions about Clone and Eq traits 2025-07-22 23:16:49 +02:00
bors
c0b282f0cc Auto merge of #144205 - hkBst:flt2dec, r=workingjubilee
flt2dec: replace for loop by iter_mut

Perf is explored in https://github.com/rust-lang/rust/issues/144118, which initially showed small losses, but then also showed significant gains. Both are real, but given the smallness of the losses, this seems a good change.
2025-07-22 08:28:29 +00:00
许杰友 Jieyou Xu (Joe)
551cef9fc9 Rollup merge of #144212 - bjorn3:remove_unique_lang_item, r=oli-obk
Remove the ptr_unique lang item

Miri no longer uses it since https://github.com/rust-lang/miri/pull/4307.
2025-07-22 00:54:30 +08:00
许杰友 Jieyou Xu (Joe)
1f8b531b54 Rollup merge of #143768 - Randl:const-try, r=oli-obk
Constify Try, From, TryFrom and relevant traits
2025-07-22 00:54:26 +08:00
Evgenii Zheltonozhskii
3c76e3d002 Constify Try, From, TryFrom 2025-07-21 12:49:45 +03:00
Oli Scherer
4653b7acbd Stabilize const TypeId::of 2025-07-21 09:11:21 +00:00
Ralf Jung
d2be1c8d00 Option::as_slice: fix comment 2025-07-20 22:39:10 +02:00
Marijn Schouten
f147716e7d flt2dec: use fill instead of loop 2025-07-20 18:45:11 +00:00
Guillaume Gomez
5ba1251b55 Rollup merge of #143423 - hkBst:clippy-fix-1, r=workingjubilee
address clippy formatting nits

- int_log10.rs: change top level doc comments to outer
- collect.rs: remove empty line after doc comment
- clippy fix: markdown indentation for indented items after line break: a markdown list item continued over multiples lines, but those following lines which are part of the same item are not indented
- clippy fix: bound in one place: when there is a bound in angle brackets and another bound on the same variable in a where clause
2025-07-20 15:34:04 +02:00
Guillaume Gomez
0162cc50e3 Rollup merge of #143282 - nxsaken:strict_sub_signed, r=jhpratt
Add `uX::strict_sub_signed`

rust-lang/rust#116090 missed `strict_sub_signed`, adding it here.
Part of rust-lang/rust#118260.

r? ``@m-ou-se``
2025-07-20 15:34:04 +02:00
bjorn3
fdf8bdb7a2 Remove the ptr_unique lang item
Miri no longer uses it.
2025-07-20 09:50:58 +00:00
Matthias Krüger
72588c8eb0 Rollup merge of #144169 - RalfJung:type-id-fix, r=oli-obk
interpret: fix TypeId pointers being considered data pointers

Fixes https://github.com/rust-lang/miri/issues/4477
r? ````@oli-obk````
2025-07-20 08:56:10 +02:00
Matthias Krüger
5e5ac49bbb Rollup merge of #144111 - clarfonthey:maybe-uninit-deprecated, r=jhpratt
Remove deprecated `MaybeUninit` slice methods

These were left in to make migration a bit easier, although they should be removed now since they were never stable.
2025-07-20 08:56:08 +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
Matthias Krüger
6d7d366fd3 Rollup merge of #141260 - LuigiPiucco:volatile-null, r=RalfJung
Allow volatile access to non-Rust memory, including address 0

This PR relaxes the `ub_check` in the `read_volatile`/`write_volatile` pointer operations to allow passing null. This is needed to support processors which hard-code peripheral registers on address 0, like the AVR chip ATtiny1626. LLVM understands this as valid and handles it correctly, as tested in my [PR to add a note about it](6387c82255 (diff-81bbb96298c32fa901beb82ab3b97add27a410c01d577c1f8c01000ed2055826)) (rustc generates the same LLVM IR as expected there when this PR is applied, and consequently the same AVR assembly).

Follow-up and implementation of the discussions in:
- https://internals.rust-lang.org/t/pre-rfc-conditionally-supported-volatile-access-to-address-0/12881/7
- https://github.com/Rahix/avr-device/pull/185;
- [#t-lang > Adding the possibility of volatile access to address 0](https://rust-lang.zulipchat.com/#narrow/channel/213817-t-lang/topic/Adding.20the.20possibility.20of.20volatile.20access.20to.20address.200/with/513303502)
- https://discourse.llvm.org/t/rfc-volatile-access-to-non-dereferenceable-memory-may-be-well-defined/86303

r? ````@RalfJung````

Also fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/29 (about as good as it'll get, null will likely never be a "normal" address in Rust)
2025-07-20 08:56:05 +02:00
ltdk
56288857d8 Remove deprecated MaybeUninit slice methods 2025-07-19 22:33:15 -04:00
Nurzhan Sakén
caf4f111bc Add #[rustc_intrinsic_const_stable_indirect] to float rounding
intrinsics
2025-07-20 00:09:32 +04:00
Nurzhan Sakén
ca01e7de6f Stabilize const_float_round_methods 2025-07-20 00:08:58 +04:00
usamoi
fe42025122 update Atomic*::from_ptr and Atomic*::as_ptr docs 2025-07-19 22:17:32 +08:00
bors
12865ffd0d Auto merge of #144166 - matthiaskrgr:rollup-wccepuo, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#141076 (fix Zip unsoundness (again))
 - rust-lang/rust#142444 (adding run-make test to autodiff)
 - rust-lang/rust#143704 (Be a bit more careful around exotic cycles in in the inliner)
 - rust-lang/rust#144073 (Don't test panic=unwind in panic_main.rs on Fuchsia)
 - rust-lang/rust#144083 (miri sleep tests: increase slack)
 - rust-lang/rust#144092 (bootstrap: Detect musl hosts)
 - rust-lang/rust#144098 (Do not lint private-in-public for RPITIT)
 - rust-lang/rust#144103 (Rename `emit_unless` to `emit_unless_delay`)
 - rust-lang/rust#144108 (Ignore tests/run-make/link-eh-frame-terminator/rmake.rs when cross-compiling)
 - rust-lang/rust#144115 (fix outdated comment)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-07-19 11:10:04 +00:00
Ralf Jung
7672e4ed85 interpret: fix TypeId pointers being considered data pointers 2025-07-19 10:29:13 +02: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