Commit Graph

2924 Commits

Author SHA1 Message Date
Scott McMurray
62f7d5305e Update compiler_builtins to 0.1.121 2024-08-23 12:02:26 -07:00
okaneco
65abcc2bcc Implement feature string_from_utf8_lossy_owned
Implement feature for lossily converting from `Vec<u8>` to `String`
- Add `String::from_utf8_lossy_owned`
- Add `FromUtf8Error::into_utf8_lossy`
2024-08-22 23:37:52 -04:00
Amjad Alsharafi
57b164a9d2
Update compiler_builtins to 0.1.120
Signed-off-by: Amjad Alsharafi <26300843+Amjad50@users.noreply.github.com>
2024-08-22 14:26:31 +08:00
Scott McMurray
dfea11d620 Stabilize iter::repeat_n 2024-08-19 22:39:04 -07:00
The 8472
6d8f0bd930 apply #[optimize(size)] to #[cold] ones and part of the panick machinery 2024-08-14 20:50:04 +02:00
Ralf Jung
6eaf531432 add Box::as_ptr and Box::as_mut_ptr methods 2024-08-14 14:30:31 +02:00
Matthias Krüger
85180cd365
Rollup merge of #128759 - notriddle:notriddle/spec-to-string, r=workingjubilee,compiler-errors
alloc: add ToString specialization for `&&str`

Fixes #128690
2024-08-14 05:05:51 +02:00
bors
591ecb88df Auto merge of #128742 - RalfJung:miri-vtable-uniqueness, r=saethlin
miri: make vtable addresses not globally unique

Miri currently gives vtables a unique global address. That's not actually matching reality though. So this PR enables Miri to generate different addresses for the same type-trait pair.

To avoid generating an unbounded number of `AllocId` (and consuming unbounded amounts of memory), we use the "salt" technique that we also already use for giving constants non-unique addresses: the cache is keyed on a "salt" value n top of the actually relevant key, and Miri picks a random salt (currently in the range `0..16`) each time it needs to choose an `AllocId` for one of these globals -- that means we'll get up to 16 different addresses for each vtable. The salt scheme is integrated into the global allocation deduplication logic in `tcx`, and also used for functions and string literals. (So this also fixes the problem that casting the same function to a fn ptr over and over will consume unbounded memory.)

r? `@saethlin`
Fixes https://github.com/rust-lang/miri/issues/3737
2024-08-13 04:32:34 +00:00
schvv31n
027b19fa9b std::fmt::FormatterFn -> std::fmt::FromFn 2024-08-12 18:33:30 +01:00
Ralf Jung
4763d12207 ignore some vtable/fn ptr equality tests in Miri, their result is not fully predictable 2024-08-12 10:39:11 +02:00
bors
13f8a57cfb Auto merge of #126793 - saethlin:mono-rawvec, r=scottmcm
Apply "polymorphization at home" to RawVec

The idea here is to move all the logic in RawVec into functions with explicit size and alignment parameters. This should eliminate all the fussing about how tweaking RawVec code produces large swings in compile times.

This uncovered https://github.com/rust-lang/rust-clippy/issues/12979, so I've modified the relevant test in a way that tries to preserve the spirit of the test without tripping the ICE.
2024-08-12 01:47:06 +00:00
bors
04ba50e823 Auto merge of #128927 - GuillaumeGomez:rollup-ei2lr0f, r=GuillaumeGomez
Rollup of 8 pull requests

Successful merges:

 - #128273 (Improve `Ord` violation help)
 - #128807 (run-make: explaing why fmt-write-bloat is ignore-windows)
 - #128903 (rustdoc-json-types `Discriminant`: fix typo)
 - #128905 (gitignore: Add Zed and Helix editors)
 - #128908 (diagnostics: do not warn when a lifetime bound infers itself)
 - #128909 (Fix dump-ice-to-disk for RUSTC_ICE=0 users)
 - #128910 (Differentiate between methods and associated functions in diagnostics)
 - #128923 ([rustdoc] Stop showing impl items for negative impls)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-08-10 15:13:38 +00:00
Guillaume Gomez
65875b2f5a
Rollup merge of #128273 - Voultapher:improve-ord-violation-help, r=workingjubilee
Improve `Ord` violation help

Recent experience in #128083 showed that the panic message when an Ord violation is detected by the new sort implementations can be confusing. So this PR aims to improve it, together with minor bug fixes in the doc comments for sort*, sort_unstable* and select_nth_unstable*.

Is it possible to get these changes into the 1.81 release? It doesn't change behavior and would greatly help when users encounter this panic for the first time, which they may after upgrading to 1.81.

Tagging `@orlp`
2024-08-10 16:23:51 +02:00
Nadrieril
cd40769c02 Stabilize min_exhaustive_patterns 2024-08-10 12:07:17 +02:00
Ben Kimock
da15248d26 Add an optimizer hint for the capacity that with_capacity_in returns 2024-08-09 20:06:27 -04:00
Ben Kimock
4e98bc6730 Hoist IS_ZST check out of RawVecInner::from_*_in 2024-08-09 20:06:27 -04:00
Ben Kimock
d6c0ebef50 Polymorphize RawVec 2024-08-09 20:06:26 -04:00
Lukas Bergdoll
1be60b5d2b Fix linkchecker issue 2024-08-09 15:05:37 +02:00
Guillaume Gomez
6d69b2e408 Update compiler-builtins version to 0.1.118 2024-08-08 14:47:49 +02:00
Trevor Gross
1d820dc9a6
Rollup merge of #128691 - tgross35:update-builtins, r=Amanieu
Update `compiler-builtins` to 0.1.117

This includes [1] which means we can remove the (nonworking) configuration of `no-f16-f128`.

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

[1]: https://github.com/rust-lang/compiler-builtins/pull/652

try-job: dist-various-1
2024-08-07 20:49:03 -05:00
Matthias Krüger
2ee9678338
Rollup merge of #128261 - clarfonthey:iter-default, r=dtolnay
impl `Default` for collection iterators that don't already have it

There is a pretty strong precedent for implementing `Default` for collection iterators, and this does so for some where this implementation was missed.

I don't think this needs a separate ACP (since this precedent already exists, and these feel like they were just missed), however, it *will* need an FCP since these implementations are instantly stable.
2024-08-07 20:28:16 +02:00
Michael Howell
3312f5d652 alloc: make to_string_str! a bit less complex 2024-08-07 10:06:54 -07:00
Trevor Gross
51e68c3006 Update compiler-builtins to 0.1.117
This includes [1] which means we can remove the (nonworking)
configuration of `no-f16-f128`.

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

[1]: https://github.com/rust-lang/compiler-builtins/pull/652
2024-08-06 21:48:32 -05:00
Matthias Krüger
16b251be10
Rollup merge of #125048 - dingxiangfei2009:stable-deref, r=amanieu
PinCoerceUnsized trait into core

cc ``@Darksonn`` ``@wedsonaf`` ``@ojeda``

This is a PR to introduce a `PinCoerceUnsized` trait in order to make trait impls generated by the proc-macro `#[derive(SmartPointer)]`, proposed by [RFC](e17e19ac7a/text/3621-derive-smart-pointer.md (pincoerceunsized-1)), sound. There you may find explanation, justification and discussion about the alternatives.

Note that we do not seek stabilization of this `PinCoerceUnsized` trait in the near future. The stabilisation of this trait does not block the eventual stabilization process of the `#[derive(SmartPointer)]` macro. Ideally, use of `DerefPure` is more preferrable except this will actually constitute a breaking change. `PinCoerceUnsized` emerges as a solution to the said soundness hole while avoiding the breaking change. More details on the `DerefPure` option have been described in this [section](e17e19ac7a/text/3621-derive-smart-pointer.md (derefpure)) of the RFC linked above.

Earlier discussion can be found in this [Zulip stream](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/Pin.20and.20soundness.20of.20unsizing.20coercions) and [rust-for-linux thread](https://rust-lang.zulipchat.com/#narrow/stream/425075-rust-for-linux/topic/.23.5Bderive.28SmartPointer.29.5D.20and.20pin.20unsoundness.20rfc.233621).

try-job: dist-various-2
2024-08-07 00:34:11 +02:00
Michael Howell
1b587a6e76 alloc: add ToString specialization for &&str
Fixes #128690
2024-08-06 14:37:33 -07:00
Matthias Krüger
e4367cec5e
Rollup merge of #128309 - kmicklas:btreeset-cursor, r=Amanieu
Implement cursors for `BTreeSet`

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

This is a straightforward wrapping of the map API, except that map's `CursorMut` does not make sense, because there is no value to mutate. Hence, map's `CursorMutKey` is wrapped here as just `CursorMut`, since it's unambiguous for sets and we don't normally speak of "keys". On the other hand, I can see some potential for confusion with `CursorMut` meaning different things in each module. I'm happy to take suggestions to improve that.

r? ````@Amanieu````
2024-08-05 05:40:20 +02:00
Lukas Bergdoll
613155c96a Apply review comments to PartialOrd section 2024-08-03 15:10:27 +02:00
Matthias Krüger
1f700139f8
Rollup merge of #127586 - zachs18:more-must-use, r=cuviper
Add `#[must_use]` to some `into_raw*` functions.

cc #121287

r? ``@cuviper``

Adds `#[must_use = "losing the pointer will leak memory"]`[^1] to `Box::into_raw(_with_allocator)`, `Vec::into_raw_parts(_with_alloc)`, `String::into_raw_parts`[^2], and `rc::{Rc, Weak}::into_raw_with_allocator` (Rc's normal `into_raw` and all of `Arc`'s `into_raw*`s are already `must_use`).

Adds `#[must_use = "losing the raw <resource name may leak resources"]` to `IntoRawFd::into_raw_fd`, `IntoRawSocket::into_raw_socket`, and `IntoRawHandle::into_raw_handle`.

[^1]: "*will* leak memory" may be too-strong wording (since `Box`/`Vec`/`String`/`rc::Weak` might not have a backing allocation), but I left it as-is for simplicity and consistency.

[^2]: `String::into_raw_parts`'s `must_use` message is changed from the previous (possibly misleading) "`self` will be dropped if the result is not used".
2024-08-03 11:17:42 +02:00
Ken Micklas
0bc501e0ad Fix mutability in doc tests for BTreeSet cursors 2024-08-01 21:02:51 +01:00
Ken Micklas
cbdc377866 Introduce Cursor/CursorMut/CursorMutKey thrichotomy for BTreeSet like map API 2024-08-01 19:49:26 +01:00
Ken Micklas
4560770451 Fix some uses of "map" instead of "set" in BTreeSet cursor API docs 2024-08-01 19:48:23 +01:00
Ken Micklas
020476296b Share UnorderedKeyError with BTReeMap for set API 2024-08-01 19:47:57 +01:00
Lukas Bergdoll
afc404fdfc Apply review comments
- Use if the implementation of [`Ord`] for `T`
  language
- Link to total order wiki page
- Rework total order help and examples
- Improve language to be more precise and less
  prone to misunderstandings.
- Fix usage of `sort_unstable_by` in `sort_by`
  example
- Fix missing author mention
- Use more consistent example input for sort
- Use more idiomatic assert_eq! in examples
- Use more natural "comparison function" language
  instead of "comparator function"
2024-07-31 11:36:57 +02:00
Xiangfei Ding
d495b84a9a
PinCoerceUnsized trait into core 2024-07-31 17:10:55 +08:00
bors
f8060d282d Auto merge of #128083 - Mark-Simulacrum:bump-bootstrap, r=albertlarsan68
Bump bootstrap compiler to new beta

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-07-30 17:49:08 +00:00
bors
dba8e2d2c2 Auto merge of #128234 - jcsp:retain-empty-case, r=tgross35
Optimize empty case in Vec::retain

While profiling some code that happens to call Vec::retain() in a tight loop, I noticed more runtime than expected in retain, even in a bench case where the vector was always empty.  When I wrapped my call to retain in `if !myvec.is_empty()` I saw faster execution compared with doing retain on an empty vector.

On closer inspection, Vec::retain is doing set_len(0) on itself even when the vector is empty, and then resetting the length again in BackshiftOnDrop::drop.

Unscientific screengrab of a flamegraph illustrating how we end up spending time in set_len and drop:
![image](https://github.com/user-attachments/assets/ebc72ace-84a0-4432-9b6f-1b3c96d353ba)
2024-07-30 00:55:52 +00:00
bors
56c698c711 Auto merge of #128334 - matthiaskrgr:rollup-nhxdt0c, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #128182 (handle no_std targets on std builds)
 - #128277 (miri: fix offset_from behavior on wildcard pointers)
 - #128304 (Isolate the diagnostic code that expects `thir::Pat` to be printable)
 - #128307 (Clean and enable `rustdoc::unescaped_backticks` for `core/alloc/std/test/proc_macro`)
 - #128322 (CI: move RFL job forward to v6.11-rc1)
 - #128333 (Miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-29 10:05:42 +00:00
Matthias Krüger
8f7af88b33
Rollup merge of #128307 - ojeda:unescaped_backticks, r=GuillaumeGomez
Clean and enable `rustdoc::unescaped_backticks` for `core/alloc/std/test/proc_macro`

I am not sure if the lint is supposed to be "ready enough" (since it is `allow` by default), but it does catch a couple issues in `core` (`alloc`, `std`, `test` and `proc_macro` are already clean), so I propose making it `warn` in all the crates rendered in the website.

Cc: `@GuillaumeGomez`
2024-07-29 11:42:35 +02:00
John Spray
6a6824a0ab Optimize empty case in Vec::retain 2024-07-29 09:40:51 +01:00
bors
80d8270d84 Auto merge of #125016 - nicholasbishop:bishop-cb-112, r=tgross35
Update compiler_builtins to 0.1.114

The `weak-intrinsics` feature was removed from compiler_builtins in https://github.com/rust-lang/compiler-builtins/pull/598, so dropped the `compiler-builtins-weak-intrinsics` feature from alloc/std/sysroot.

In https://github.com/rust-lang/compiler-builtins/pull/593, some builtins for f16/f128 were added. These don't work for all compiler backends, so add a `compiler-builtins-no-f16-f128` feature and disable it for cranelift and gcc.
2024-07-29 07:41:33 +00:00
Matthias Krüger
0c6d2fb3dc
Rollup merge of #128310 - kmicklas:btree-map-peek-next-docs, r=tgross35
Add missing periods on `BTreeMap` cursor `peek_next` docs

Tracking issue: https://github.com/rust-lang/rust/issues/107540
2024-07-29 07:11:16 +02:00
Nicholas Bishop
ecf2963baf Update compiler_builtins to 0.1.114
The `weak-intrinsics` feature was removed from compiler_builtins in
https://github.com/rust-lang/compiler-builtins/pull/598, so dropped the
`compiler-builtins-weak-intrinsics` feature from alloc/std/sysroot.

In https://github.com/rust-lang/compiler-builtins/pull/593, some
builtins for f16/f128 were added. These don't work for all compiler
backends, so add a `compiler-builtins-no-f16-f128` feature and disable
it for cranelift and gcc. Also disable it for LLVM targets that don't
support it.
2024-07-28 20:43:07 -04:00
Miguel Ojeda
dc815df1e1 Warn on rustdoc::unescaped_backticks for core/alloc/std/test/proc_macro
They are all clean now, so enable the lint to keep them clean going forward.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-07-29 00:58:45 +02:00
Nicholas Nethercote
84ac80f192 Reformat use declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Mark Rousskov
5eca36d27a step cfg(bootstrap) 2024-07-28 14:46:29 -04:00
Guillaume Gomez
ee5956fd8a
Rollup merge of #128228 - slanterns:const_waker, r=dtolnay,oli-obk
Stabilize `const_waker`

Closes: https://github.com/rust-lang/rust/issues/102012.

For `local_waker` and `context_ext` related things, I just ~~moved them to dedicated feature gates and reused their own tracking issue (maybe it's better to open a new one later, but at least they should not be tracked under https://github.com/rust-lang/rust/issues/102012 from the beginning IMO.)~~ reused their own feature gates as suggested by ``@tgross35.``

``@rustbot`` label: +T-libs-api

r? libs-api
2024-07-28 20:07:46 +02:00
Guillaume Gomez
506a6317be
Rollup merge of #127765 - bitfield:fix_stdlib_doc_nits, r=dtolnay
Fix doc nits

Many tiny changes to stdlib doc comments to make them consistent (for example "Returns foo", rather than "Return foo"), adding missing periods, paragraph breaks, backticks for monospace style, and other minor nits.
2024-07-28 20:07:44 +02:00
Slanterns
0a6ebbaf2e
stabilize const_waker 2024-07-28 22:31:13 +08:00
Ken Micklas
0468983eae Add missing periods on BTreeMap cursor peek_next docs 2024-07-28 15:28:35 +01:00
Ken Micklas
9b165a1600 Implement cursors for BTreeSet 2024-07-28 15:25:40 +01:00
Matthias Krüger
99204047c9
Rollup merge of #128279 - slanterns:is_sorted, r=dtolnay
Stabilize `is_sorted`

Closes: https://github.com/rust-lang/rust/issues/53485.

~~Question: does~~ 8fe0c753f2/compiler/rustc_lint_defs/src/builtin.rs (L1986-L1994) ~~need a new example?~~
edit: It causes a test failure and needs to be changed anyway.

``@rustbot`` label: +T-libs-api

r? libs-api
2024-07-28 08:57:17 +02:00
Slanterns
ec0b354092
stabilize is_sorted 2024-07-28 03:11:54 +08:00
Trevor Gross
51734a8a6d
Rollup merge of #125897 - RalfJung:from-ref, r=Amanieu
from_ref, from_mut: clarify documentation

This was brought up [here](https://github.com/rust-lang/rust/issues/56604#issuecomment-2143193486). The domain of quantification is generally always constrained by the type in the type signature, and I am not sure it's always worth spelling that out explicitly as that makes things exceedingly verbose. But since this was explicitly brought up, let's clarify.
2024-07-27 13:32:56 -04:00
Lukas Bergdoll
00ce238885 Improve panic sections for sort*, sort_unstable* and select_nth_unstable*
- Move panic information into # Panics section
- Fix mentions of T: Ord that should be compare
- Add missing information
2024-07-27 16:48:42 +02:00
ltdk
0b99720497 Okay, I guess I have to give these a different feature name 2024-07-27 02:48:55 -04:00
ltdk
50835bf194 impl Default for collection iterators that don't already have it 2024-07-27 02:04:32 -04:00
John Arundel
a19472a93e Fix doc nits
Many tiny changes to stdlib doc comments to make them consistent (for example
"Returns foo", rather than "Return foo", per RFC1574), adding missing periods, paragraph
breaks, backticks for monospace style, and other minor nits.

https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#appendix-a-full-conventions-text
2024-07-26 13:26:33 +01:00
Matthias Krüger
e342efe545
Rollup merge of #128120 - compiler-errors:async-fn-name, r=oli-obk
Gate `AsyncFn*` under `async_closure` feature

T-lang has not come to a consensus on the naming of async closure callable bounds, and as part of allowing the async closures RFC merge, we agreed to place `AsyncFn` under the same gate as `async Fn` so that these syntaxes can be evaluated in parallel.

See https://github.com/rust-lang/rfcs/pull/3668#issuecomment-2246435537

r? oli-obk
2024-07-24 18:00:40 +02:00
Matthias Krüger
34abb9647c
Rollup merge of #127733 - GrigorenkoPV:don't-forget, r=Amanieu
Replace some `mem::forget`'s with `ManuallyDrop`

              > but I would like to see a larger effort to replace all uses of `mem::forget`.

_Originally posted by `@saethlin` in https://github.com/rust-lang/rust/issues/127584#issuecomment-2226087767_

So,
r? `@saethlin`

Sorry, I have finished writing all of this before I got your response.
2024-07-24 18:00:39 +02:00
Matthias Krüger
6f696257cb
Rollup merge of #127481 - a1phyr:pattern_gat, r=Amanieu
Remove generic lifetime parameter of trait `Pattern`

Use a GAT for `Searcher` associated type because this trait is always implemented for every lifetime anyway.

cc #27721
2024-07-24 05:05:32 +02:00
Matthias Krüger
0666eee2a1
Rollup merge of #125962 - Coekjan:const-binary-heap, r=Amanieu
Update tracking issue for `const_binary_heap_new_in`

This PR updates the tracking issue of `const_binary_heap_new_in` feature:
- Old issue: #112353
- New issue: #125961
2024-07-24 05:05:30 +02:00
Michael Goulet
b82f878f03 Gate AsyncFn* under async_closure feature 2024-07-23 19:56:06 -04:00
许杰友 Jieyou Xu (Joe)
9f4039fcd5
Rollup merge of #127415 - AljoschaMeyer:master, r=dtolnay
Add missing try_new_uninit_slice_in and try_new_zeroed_slice_in

The methods for fallible slice allocation in a given allocator were missing from `Box`, which was an oversight according to https://github.com/rust-lang/wg-allocators/issues/130

This PR adds them as `try_new_uninit_slice_in` and `try_new_zeroed_slice_in`. I simply copy-pasted the implementations of `try_new_uninit_slice` and `try_new_zeroed_slice` and adusted doc comment, typings, and the allocator it uses internally.

Also adds missing punctuation to the doc comments of `try_new_uninit_slice` and `try_new_zeroed_slice`.

Related issue is https://github.com/rust-lang/rust/issues/32838 (Allocator traits and std::heap) *I think*. Also relevant is https://github.com/rust-lang/rust/issues/63291, but I did not add the corresponding `#[unstable]` proc macro, since `try_new_uninit_slice` and `try_new_zeroed_slice` are also not annotated with it.
2024-07-22 16:44:03 +08:00
Aljoscha Meyer
351fe27354
Use given allocator instad of Global 2024-07-22 08:17:46 +02:00
Nicholas Nethercote
7f0ccfe69d Adjust some comments on individual use declarations.
When we do the big `use` reformatting there are a tiny number of cases
where rustfmt moves a comment from one `use` item to another in an
undesirable way. This commit pre-emptively rearranges things to prevent
this from happening.
2024-07-17 08:05:39 +10:00
Pavel Grigorenko
f6fe7e49a2 lib: replace some mem::forget's with ManuallyDrop 2024-07-15 22:01:09 +03:00
Benoît du Garreau
772315de7c Remove generic lifetime parameter of trait Pattern
Use a GAT for `Searcher` associated type because this trait is always
implemented for every lifetime anyway.
2024-07-15 12:12:44 +02:00
Jubilee
285d45d299
Rollup merge of #127446 - zachs18:miri-stdlib-leaks-core-alloc, r=Mark-Simulacrum
Remove memory leaks in doctests in `core`, `alloc`, and `std`

cc `@RalfJung`  https://github.com/rust-lang/rust/issues/126067 https://github.com/rust-lang/miri/issues/3670

Should be no actual *documentation* changes[^1], all added/modified lines in the doctests are hidden with `#`,

This PR splits the existing memory leaks in doctests in `core`, `alloc`, and `std` into two general categories:

1. "Non-focused" memory leaks that are incidental to the thing being documented, and/or are easy to remove, i.e. they are only there because preventing the leak would make the doctest less clear and/or concise.
    - These doctests simply have a comment like `# // Prevent leaks for Miri.` above the added line that removes the memory leak.
    - [^2]Some of these would perhaps be better as part of the public documentation part of the doctest, to clarify that a memory leak can happen if it is not otherwise mentioned explicitly in the documentation  (specifically the ones in `(A)Rc::increment_strong_count(_in)`).
2. "Focused" memory leaks that are intentional and documented, and/or are possibly fragile to remove.
    - These doctests have a `# // FIXME` comment above the line that removes the memory leak, with a note that once `-Zmiri-disable-leak-check` can be applied at test granularity, these tests should be "un-unleakified" and have `-Zmiri-disable-leak-check` enabled.
    - Some of these are possibly fragile (e.g. unleaking the result of `Vec::leak`) and thus should definitely not be made part of the documentation.

This should be all of the leaks currently in `core` and `alloc`. I only found one leak in `std`, and it was in the first category (excluding the modules `@RalfJung` mentioned in https://github.com/rust-lang/rust/issues/126067 , and reducing the number of iterations of [one test](https://github.com/rust-lang/rust/blob/master/library/std/src/sync/once_lock.rs#L49-L94) from 1000 to 10)

[^1]: assuming [^2] is not added
[^2]: backlink
2024-07-13 20:18:23 -07:00
Matthias Krüger
65ea92d4a1
Rollup merge of #124980 - zachs18:rc-allocator, r=Amanieu
Generalize `fn allocator` for Rc/Arc.

Split out from #119761

- For `Rc`/`Arc`, the existing associated `fn`s are changed to allow unsized pointees.
 - For `Weak`s, new methods are added.

`````@rustbot````` label +A-allocators
2024-07-12 14:37:56 +02:00
Zachary S
0d49862998 Clarify/add must_use messages for more into_raw* functions of alloc types. 2024-07-10 13:05:03 -05:00
Matthias Krüger
aae262cafa
Rollup merge of #127554 - ferrocene:tshepang-add-missing-attribute, r=pietroalbini
do not run test where it cannot run

This was seen on Ferrocene, where we have a custom test target that does not have unwind support
2024-07-10 17:54:26 +02:00
Tshepang Mbambo
af3aa36d60
do not run test where it cannot run
This was seen on Ferrocene, where we have a custom test target that does not have unwind support
2024-07-10 01:00:55 +02:00
Matthias Krüger
5b6eb28bda
Rollup merge of #127355 - aceArt-GmbH:126475, r=oli-obk
Mark format! with must_use hint

Uses unstable feature https://github.com/rust-lang/rust/issues/94745

Part of #126475

First contribution to rust, please let me know if the blessing of tests is correct
Thanks `@bjorn3` for the help
2024-07-08 16:28:15 +02:00
Matthias Krüger
c4ee2df539
Rollup merge of #120248 - WaffleLapkin:bonk-ptr-object-casts, r=compiler-errors,oli-obk,lnicola
Make casts of pointers to trait objects stricter

This is an attempt to `fix` https://github.com/rust-lang/rust/issues/120222 and https://github.com/rust-lang/rust/issues/120217.

This is done by adding restrictions on casting pointers to trait objects.

Before this PR the rules were as follows:

> When casting `*const X<dyn A>` -> `*const Y<dyn B>`, principal traits in `A` and `B` must refer to the same trait definition (or no trait).

With this PR the rules are changed to

> When casting `*const X<dyn Src>` -> `*const Y<dyn Dst>`
> - if `Dst` has a principal trait `DstP`,
>   - `Src` must have a principal trait `SrcP`
>   - `dyn SrcP` and `dyn DstP` must be the same type (modulo the trait object lifetime, `dyn T+'a` -> `dyn T+'b` is allowed)
>   - Auto traits in `Dst` must be a subset of auto traits in `Src`
>     - Not adhering to this is currently a FCW (warn-by-default + `FutureReleaseErrorReportInDeps`), instead of an error
> - if `Src` has a principal trait `Dst` must as well
>   - this restriction will be removed in a follow up PR

This ensures that
1. Principal trait's generic arguments match (no `*const dyn Tr<A>` -> `*const dyn Tr<B>` casts, which are a problem for [#120222](https://github.com/rust-lang/rust/issues/120222))
2. Principal trait's lifetime arguments match (no `*const dyn Tr<'a>` -> `*const dyn Tr<'b>` casts, which are a problem for [#120217](https://github.com/rust-lang/rust/issues/120217))
3. No auto traits can be _added_ (this is a problem for arbitrary self types, see [this comment](https://github.com/rust-lang/rust/pull/120248#discussion_r1463835350))

Some notes:
 - We only care about the metadata/last field, so you can still cast `*const dyn T` to `*const WithHeader<dyn T>`, etc
- The lifetime of the trait object itself (`dyn A + 'lt`) is not checked, so you can still cast `*mut FnOnce() + '_` to `*mut FnOnce() + 'static`, etc
  - This feels fishy, but I couldn't come up with a reason it must be checked

The diagnostics are currently not great, to say the least, but as far as I can tell this correctly fixes the issues.

cc `@oli-obk` `@compiler-errors` `@lcnr`
2024-07-08 16:28:15 +02:00
许杰友 Jieyou Xu (Joe)
e76b01775c
Rollup merge of #127367 - ChrisDenton:run-sync, r=Nilstrieb
Run alloc sync tests

I was browsing the code and this struck me as weird. We're not running some doc tests because, the comment says, Windows builders deadlock. That should absolutely not happen, at least with our current implementation. And if it does happen I'd like to know.

Just to be sure though I'll do some try builds.

try-job: x86_64-msvc
try-job: i686-msvc
try-job: i686-mingw
try-job: x86_64-mingw
2024-07-08 13:04:31 +08:00
bors
0ca92de473 Auto merge of #127454 - matthiaskrgr:rollup-k3vfen2, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #127179 (Print `TypeId` as hex for debugging)
 - #127189 (LinkedList's Cursor: method to get a ref to the cursor's list)
 - #127236 (doc: update config file path in platform-support/wasm32-wasip1-threads.md)
 - #127297 (Improve std::Path's Hash quality by avoiding prefix collisions)
 - #127308 (Attribute cleanups)
 - #127354 (Describe Sized requirements for mem::offset_of)
 - #127409 (Emit a wrap expr span_bug only if context is not tainted)
 - #127447 (once_lock: make test not take as long in Miri)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-07 16:29:52 +00:00
Matthias Krüger
94d07befe7
Rollup merge of #127189 - GrigorenkoPV:linkedlist-cursor-list, r=Nilstrieb
LinkedList's Cursor: method to get a ref to the cursor's list

We're already providing `.back()` & `.front()`, for which we hold onto a reference to the parent list, so why not share it? Useful for when you got `LinkedList` -> `CursorMut` -> `Cursor` and cannot take another ref to the list, even though you should be able to. This seems to be completely safe & sound.

The name is, of course, bikesheddable.
2024-07-07 14:21:59 +02:00
Chayim Refael Friedman
54556f49d3 Specialize TrustedLen for Iterator::unzip()
Don't check the capacity every time (and also for `Extend` for tuples, as this is how `unzip()` is implemented).

I did this with an unsafe method on `Extend` that doesn't check for growth (`extend_one_unchecked()`). I've marked it as perma-unstable currently, although we may want to expose it in the future so collections outside of std can benefit from it. Then specialize `Extend for (A, B)` for `TrustedLen` to call it.

It may seem that an alternative way of implementing this is to have a semi-public trait (`#[doc(hidden)]` public, so collections outside of core can implement it) for `extend()` inside tuples, and specialize it from collections. However, it is impossible due to limitations of `min_specialization`.

A concern that may arise with the current approach is that implementing `extend_one_unchecked()` correctly must also incur implementing `extend_reserve()`, otherwise you can have UB. This is a somewhat non-local safety invariant. However, I believe this is fine, since to have actual UB you must have unsafe code inside your `extend_one_unchecked()` that makes incorrect assumption, *and* not implement `extend_reserve()`. I've also documented this requirement.
2024-07-07 06:58:52 +03:00
Zachary S
e0ed696d2f Mitigate focused memory leaks in alloc doctests for Miri.
If/when `-Zmiri-disable-leak-check` is able to be used at test-granularity, it should applied to these tests instead of unleaking.
2024-07-06 22:35:19 -05:00
Zachary S
93e3c00670 Remove non-focused memory leaks in alloc doctests for Miri. 2024-07-06 22:24:00 -05:00
Aljoscha Meyer
497ef49805
Fix them doc examples some more
Apologies for the many attempts, my dev loop for this consists of editing on github, committing, and then waiting for the CI failure log to yell at me.
2024-07-06 19:13:53 +02:00
Aljoscha Meyer
6b5da82d12
Fix doc examples 2024-07-06 18:50:03 +02:00
Aljoscha Meyer
9bfdeb592c
Run formatter on alloc/src/boxed.rs 2024-07-06 14:38:00 +02:00
lukas
3e9c9a05a8 Mark format! with must_use hint 2024-07-06 14:24:20 +02:00
Aljoscha Meyer
2c14dd3b12
Add missing try_new_uninit_slice_in and try_new_zeroed_slice_in
The methods for fallible slice allocation in a given allocator were missing, which was an oversight according to https://github.com/rust-lang/wg-allocators/issues/130

This PR adds them as `try_new_uninit_slice_in` and `try_new_zeroed_slice_in`.

Also adds missing punctuation to the doc comments of ` try_new_uninit_slice` and `try_new_zeroed_slice`
2024-07-06 09:09:10 +02:00
Chris Denton
7566f41209
Run alloc sync tests 2024-07-05 14:48:39 +00:00
Maybe Waffle
5645e8e285 Add more checks for pointers with vtable meta
The rules for casting `*mut X<dyn A>` -> `*mut Y<dyn B>` are as follows:
- If `B` has a principal
  - `A` must have exactly the same principal (including generics)
  - Auto traits of `B` must be a subset of autotraits in `A`

Note that `X<_>` and `Y<_>` can be identity, or arbitrary structs with last field being the dyn type.
The lifetime of the trait object itself (`dyn ... + 'a`) is not checked.

This prevents a few soundness issues with `#![feature(arbitrary_self_types)]` and trait upcasting.
Namely, these checks make sure that vtable is always valid for the pointee.
2024-07-04 17:56:09 +02:00
Jacob Pratt
db592253a6
Rollup merge of #123588 - tgross35:stabilize-assert_unchecked, r=dtolnay
Stabilize `hint::assert_unchecked`

Make the following API stable, including const:

```rust
// core::hint, std::hint

pub const unsafe fn assert_unchecked(p: bool);
```

This PR also reworks some of the documentation and adds an example.

Tracking issue: https://github.com/rust-lang/rust/issues/119131
FCP: https://github.com/rust-lang/rust/issues/119131#issuecomment-1906394087. The docs update should resolve the remaining concern.
2024-07-03 03:03:13 -04:00
Scott McMurray
23c8ed14c9 Avoid MIR bloat in inlining
In 126578 we ended up with more binary size increases than expected.

This change attempts to avoid inlining large things into small things, to avoid that kind of increase, in cases when top-down inlining will still be able to do that inlining later.
2024-07-01 05:17:13 -07:00
bors
b8d7dd8d69 Auto merge of #127026 - Urgau:cleanup-bootstrap-check-cfg, r=Kobzol
Cleanup bootstrap check-cfg

This PR cleanup many custom `check-cfg` in bootstrap that have been accumulated over the years.

As well as updating some outdated comments.
2024-06-30 22:27:29 +00:00
Pavel Grigorenko
23e5468a09 LinkedList's Cursor: method to get a ref to the cursor's list 2024-07-01 00:22:09 +03:00
Matthias Krüger
2c228260dc
Rollup merge of #126970 - DaniPopes:simplify-str-clone_into, r=cuviper
Simplify `str::clone_into`

Removes an `unsafe` in favor of just using `String` methods.
2024-06-28 08:34:09 +02:00
Urgau
f026e0bfc1 Cleanup bootstrap check-cfg 2024-06-27 11:30:03 +02:00
Jacob Pratt
d3debc0037
Rollup merge of #126929 - nnethercote:rm-__rust_force_expr, r=oli-obk
Remove `__rust_force_expr`.

This was added (with a different name) to improve an error message. It is no longer needed -- removing it changes the error message, but overall I think the new message is no worse:
- the mention of `#` in the first line is a little worse,
- but the extra context makes it very clear what the problem is, perhaps even clearer than the old message,
- and the removal of the note about the `expr` fragment (an internal detail of `__rust_force_expr`) is an improvement.

Overall I think the error is quite clear and still far better than the old message that prompted #61933, which didn't even mention patterns.

The motivation for this is #124141, which will cause pasted metavariables to be tokenized and reparsed instead of the AST node being cached. This change in behaviour occasionally has a non-zero perf cost, and `__rust_force_expr` causes the tokenize/reparse step to occur twice. Removing `__rust_force_expr` greatly reduces the extra overhead for the `deep-vector` benchmark.

r? ```@oli-obk```
2024-06-27 02:06:19 -04:00
DaniPopes
d5ff4f4f65
Simplify str::clone_into
Removes an `unsafe` in favor of just using `String` methods.
2024-06-25 22:34:41 +02:00
Matthias Krüger
58bbade921
Rollup merge of #126302 - mu001999-contrib:ignore/default, r=michaelwoerister
Detect unused structs which derived Default

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->

Fixes #98871
2024-06-25 21:33:41 +02:00
mu001999
6997b6876d Detect unused structs which derived Default 2024-06-25 23:29:44 +08:00
Nicholas Nethercote
9828e960ab Remove __rust_force_expr.
This was added (with a different name) to improve an error message. It
is no longer needed -- removing it changes the error message, but overall
I think the new message is no worse:
- the mention of `#` in the first line is a little worse,
- but the extra context makes it very clear what the problem is, perhaps
  even clearer than the old message,
- and the removal of the note about the `expr` fragment (an internal
  detail of `__rust_force_expr`) is an improvement.

Overall I think the error is quite clear and still far better than the
old message that prompted #61933, which didn't even mention patterns.

The motivation for this is #124141, which will cause pasted
metavariables to be tokenized and reparsed instead of the AST node being
cached. This change in behaviour occasionally has a non-zero perf cost,
and `__rust_force_expr` causes the tokenize/reparse step to occur twice.
Removing `__rust_force_expr` greatly reduces the extra overhead for the
`deep-vector` benchmark.
2024-06-25 14:35:09 +10:00
Kevin Reid
13fca73f49 Replace MaybeUninit::uninit_array() with array repeat expression.
This is possible now that inline const blocks are stable; the idea was
even mentioned as an alternative when `uninit_array()` was added:
<https://github.com/rust-lang/rust/pull/65580#issuecomment-544200681>

> if it’s stabilized soon enough maybe it’s not worth having a
> standard library method that will be replaceable with
> `let buffer = [MaybeUninit::<T>::uninit(); $N];`

Const array repetition and inline const blocks are now stable (in the
next release), so that circumstance has come to pass, and we no longer
have reason to want `uninit_array()` other than convenience. Therefore,
let’s evaluate the inconvenience by not using `uninit_array()` in
the standard library, before potentially deleting it entirely.
2024-06-24 10:23:50 -07:00
bors
a0f01c3c10 Auto merge of #126838 - matthiaskrgr:rollup-qkop22o, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #126140 (Rename `std::fs::try_exists` to  `std::fs::exists` and stabilize fs_try_exists)
 - #126318 (Add a `x perf` command for integrating bootstrap with `rustc-perf`)
 - #126552 (Remove use of const traits (and `feature(effects)`) from stdlib)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-06-22 18:48:10 +00:00
bors
f944afe380 Auto merge of #116113 - kpreid:arcmut, r=dtolnay
Generalize `{Rc,Arc}::make_mut()` to unsized types.

* `{Rc,Arc}::make_mut()` now accept any type implementing the new unstable trait `core::clone::CloneToUninit`.
* `CloneToUninit` is implemented for `T: Clone` and for `[T] where T: Clone`.
* `CloneToUninit` is a generalization of the existing internal trait `alloc::alloc::WriteCloneIntoRaw`.
* New feature gate: `clone_to_uninit`

This allows performing `make_mut()` on `Rc<[T]>` and `Arc<[T]>`, which was not previously possible.

---

Previous PR description, now obsolete:

>  Add `{Rc, Arc}::make_mut_slice()`
>
> These functions behave identically to `make_mut()`, but operate on `Arc<[T]>` instead of `Arc<T>`.
>
> This allows performing the operation on slices, which was not previously possible because `make_mut()` requires `T: Clone` (and slices, being `!Sized`, do not and currently cannot implement `Clone`).
>
> Feature gate: `make_mut_slice`

try-job: test-various
2024-06-22 16:35:29 +00:00
Kevin Reid
88c3db57e4 Generalize {Rc,Arc}::make_mut() to unsized types.
This requires introducing a new internal type `RcUninit` (and
`ArcUninit`), which can own an `RcBox<T>` without requiring it to be
initialized, sized, or a slice. This is similar to `UniqueRc`, but
`UniqueRc` doesn't support the allocator parameter, and there is no
`UniqueArc`.
2024-06-22 08:08:00 -07:00
Kevin Reid
a9a4830d25 Replace WriteCloneIntoRaw with CloneToUninit. 2024-06-22 08:08:00 -07:00
Deadbeef
3b14b756d8 Remove feature(effects) from the standard library 2024-06-21 09:23:24 +00:00
bors
684b3553f7 Auto merge of #124032 - Voultapher:a-new-sort, r=thomcc
Replace sort implementations

This PR replaces the sort implementations with tailor-made ones that strike a balance of run-time, compile-time and binary-size, yielding run-time and compile-time improvements. Regressing binary-size for `slice::sort` while improving it for `slice::sort_unstable`. All while upholding the existing soft and hard safety guarantees, and even extending the soft guarantees, detecting strict weak ordering violations with a high chance and reporting it to users via a panic.

* `slice::sort` -> driftsort [design document](https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md), includes detailed benchmarks and analysis.

* `slice::sort_unstable` -> ipnsort [design document](https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md), includes detailed benchmarks and analysis.

#### Why should we change the sort implementations?

In the [2023 Rust survey](https://blog.rust-lang.org/2024/02/19/2023-Rust-Annual-Survey-2023-results.html#challenges), one of the questions was: "In your opinion, how should work on the following aspects of Rust be prioritized?". The second place was "Runtime performance" and the third one "Compile Times". This PR aims to improve both.

#### Why is this one big PR and not multiple?

* The current documentation gives performance recommendations for `slice::sort` and `slice::sort_unstable`. If for example only one of them were to be changed, this advice would be misleading for some Rust versions. By replacing them atomically, the advice remains largely unchanged, and users don't have to change their code.
* driftsort and ipnsort share a substantial part of their implementations.
* The implementation of `select_nth_unstable` uses internals of `slice::sort_unstable`, which makes it impractical to split changes.

---

This PR is a collaboration with `@orlp.`
2024-06-20 20:40:43 +00:00
Lukas Bergdoll
a895ef77f0 Fix wrong big O star bracing in the doc comments 2024-06-20 18:07:04 +02:00
bors
1ca578e68e Auto merge of #126736 - matthiaskrgr:rollup-rb20oe3, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #126380 (Add std Xtensa targets support)
 - #126636 (Resolve Clippy `f16` and `f128` `unimplemented!`/`FIXME`s )
 - #126659 (More status-quo tests for the `#[coverage(..)]` attribute)
 - #126711 (Make Option::as_[mut_]slice const)
 - #126717 (Clean up some comments near `use` declarations)
 - #126719 (Fix assertion failure for some `Expect` diagnostics.)
 - #126730 (Add opaque type corner case test)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-06-20 13:36:42 +00:00
Trevor Gross
5745c220e6 Stabilize hint_assert_unchecked
Make both `hint_assert_unchecked` and `const_hint_assert_unchecked`
stable as `hint_assert_unchecked`.
2024-06-19 19:31:41 -04:00
Nicholas Nethercote
665821cb60 Add blank lines after module-level //! comments.
Most modules have such a blank line, but some don't. Inserting the blank
line makes it clearer that the `//!` comments are describing the entire
module, rather than the `use` declaration(s) that immediately follows.
2024-06-20 09:23:20 +10:00
Nicholas Nethercote
09006d6a88 Convert some module-level // and /// comments to //!.
This makes their intent and expected location clearer. We see some
examples where these comments were not clearly separate from `use`
declarations, which made it hard to understand what the comment is
describing.
2024-06-20 09:23:18 +10:00
Gary Guo
ebdfcd93a3 Stabilise c_unwind 2024-06-19 13:54:51 +01:00
Lukas Bergdoll
732616998c Revert panic_safe test changes
The changes made only a limited improvement for the current small
miri coverage and in general test coverage of the sort implementations.
But they exploded test times from ~13s to ~240s, which is not deemed
worth it.
2024-06-17 22:05:35 +02:00
lukaslueg
893f95f1f7
Update Arc::try_unwrap() docs
Clarify the language wrt `race condition` not meaning `memory unsafety`.
2024-06-16 09:07:08 +02:00
Matthias Krüger
b55cabe636
Rollup merge of #126285 - kpreid:unique-rc, r=dtolnay
`UniqueRc`: support allocators and `T: ?Sized`.

Added the following (all unstable):

* Defaulted type pararameter `A: Allocator`.
* `UniqueRc::new_in()`.
* `T:  ?Sized` where possible.
* `impl CoerceUnsized for UniqueRc`.

These changes are motivated by supporting the implementation of unsized `Rc::make_mut()` (PR #116113), but are also intended to be obvious generalizations of `UniqueRc` to support the things `Rc` does.

r? ``````@the8472``````
2024-06-14 12:23:37 +02:00
Kevin Reid
27ecb71635 UniqueRc: support allocators and T: ?Sized.
Added the following (all unstable):

* Defaulted type pararameter `A: Allocator`.
* `UniqueRc::new_in()`.
* `T:  ?Sized` where possible.
* `impl CoerceUnsized for UniqueRc`.
* Drive-by doc polish: links and periods at the end of sentences.

These changes are motivated by supporting the implementation of unsized
`Rc::make_mut()` (PR #116113), but are also intended to be obvious
generalizations of `UniqueRc` to support the things `Rc` does.
2024-06-11 15:16:47 -07:00
Pietro Albini
cd2ed56502
remove cfg(bootstrap) 2024-06-11 16:52:04 +02:00
Pietro Albini
be9e27e490
replace version placeholder 2024-06-11 16:52:02 +02:00
León Orell Valerian Liehr
cbda797b77
Rollup merge of #125951 - slanterns:error_in_core_stabilization, r=Amanieu
Stabilize `error_in_core`

Closes: https://github.com/rust-lang/rust/issues/103765.

`@rustbot` label: +T-libs-api

r? libs-api
2024-06-08 04:25:44 +02:00
Matthias Krüger
0acb5b8513
Rollup merge of #124012 - slanterns:as_slice_stabilize, r=BurntSushi
Stabilize `binary_heap_as_slice`

This PR stabilizes `binary_heap_as_slice`:

```rust
// std::collections::BinaryHeap

impl BinaryHeap<T> {
    pub fn as_slice(&self) -> &[T]
}
```

<br>

Tracking issue: https://github.com/rust-lang/rust/issues/83659.
Implementation PR: https://github.com/rust-lang/rust/pull/82331.

FCPs already completed in the tracking issue.

Closes https://github.com/rust-lang/rust/issues/83659.

r? libs-api
2024-06-07 20:14:27 +02:00
Slanterns
76065f5b27
Stabilize error_in_core 2024-06-07 08:30:00 +08:00
Ralf Jung
05b7f282e8 less garbage, more examples 2024-06-06 08:25:04 +02:00
Jubilee
448159c8e6
Rollup merge of #125982 - xTachyon:fix-linked-list, r=jhpratt
Make deleting on LinkedList aware of the allocator

Fixed #125950
2024-06-05 01:14:33 -07:00
Jubilee
9ccc7b78ec
Rollup merge of #123168 - joshtriplett:size-of-prelude, r=Amanieu
Add `size_of` and `size_of_val` and `align_of` and `align_of_val` to the prelude

(Note: need to update the PR to add `align_of` and `align_of_val`, and remove the second commit with the myriad changes to appease the lint.)

Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.

The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.
2024-06-05 01:14:29 -07:00
Andrei Damian
2bad3d1392 Make deleting on LinkedList aware of the allocator 2024-06-04 18:49:13 +03:00
coekjan
c713caff6d
update tracking issue for const_binary_heap_new_in 2024-06-04 16:14:46 +08:00
Lukas Wirth
d392c50ca3 Ignore vec_deque_alloc_error::test_shrink_to_unwind test on non-unwind targets 2024-06-03 13:46:56 +02:00
coekjan
7cee7c664b
stablize const_binary_heap_constructor & create an unstable feature const_binary_heap_new_in for BinaryHeap::new_in 2024-06-01 12:44:19 +08:00
Matthias Krüger
f775fffac5
Rollup merge of #125561 - Cyborus04:stabilize-slice-flatten, r=scottmcm
Stabilize `slice_flatten`
2024-05-26 13:43:07 +02:00
Cyborus
824ffd29ee
Stabilize slice_flatten 2024-05-26 01:26:24 -04:00
Matthias Krüger
7fb81229d3
Rollup merge of #123803 - Sp00ph:shrink_to_fix, r=Mark-Simulacrum
Fix `VecDeque::shrink_to` UB when `handle_alloc_error` unwinds.

Fixes #123369

For `VecDeque` it's relatively simple to restore the buffer into a consistent state so this PR does just that.

Note that with its current implementation, `shrink_to` may change the internal arrangement of elements in the buffer, so e.g. `[D, <uninit>, A, B, C]` will become `[<uninit>, A, B, C, D]` and `[<uninit>, <uninit>, A, B, C]` may become `[B, C, <uninit>, <uninit>, A]` if `shrink_to` unwinds. This shouldn't be an issue though as we don't make any guarantees about the stability of the internal buffer arrangement (and this case is impossible to hit on stable anyways).

This PR also includes a test with code adapted from #123369 which fails without the new `shrink_to` code. Does this suffice or do we maybe need more exhaustive tests like in #108475?

cc `@Amanieu`

`@rustbot` label +T-libs
2024-05-25 22:15:17 +02:00
Urgau
02eada8f8d Remove now outdated comment since we bumped stage0 2024-05-24 08:08:41 +02:00
Lzu Tao
c7d2f4592f addresss reviews 2024-05-21 18:17:55 +00:00
Lzu Tao
0734ae22f5 Update check-cfg lists for alloc 2024-05-21 18:17:55 +00:00
bors
6715446db6 Auto merge of #125358 - matthiaskrgr:rollup-mx841tg, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #124570 (Miscellaneous cleanups)
 - #124772 (Refactor documentation for Apple targets)
 - #125011 (Add opt-for-size core lib feature flag)
 - #125218 (Migrate `run-make/no-intermediate-extras` to new `rmake.rs`)
 - #125225 (Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS)
 - #125266 (compiler: add simd_ctpop intrinsic)
 - #125348 (Small fixes to `std::path::absolute` docs)

Failed merges:

 - #125296 (Fix `unexpected_cfgs` lint on std)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-21 12:50:09 +00:00
Matthias Krüger
4abf179b14
Rollup merge of #125011 - diondokter:opt-for-size, r=Amanieu,kobzol
Add opt-for-size core lib feature flag

Adds a feature flag to the core library that enables the possibility to have smaller implementations for certain algorithms.

So far, the core lib has traded performance for binary size. This is likely what most people want since they have big simd-capable machines. However, people on small machines, like embedded devices, don't enjoy the potential speedup of the bigger algorithms, but do have to pay for them. These microcontrollers often only have 16-1024kB of flash memory.

This PR is the result of some talks with project members like `@Amanieu` at RustNL.
There are some open questions of how this is eventually stabilized, but it's a similar question as with the existing `panic_immediate_abort` feature.

Speaking as someone from the embedded side, we'd rather have this unstable for a while as opposed to not having it at all. In the meantime we can try to use it and also add additional PRs to the core lib that uses the feature flag in areas where we find benefit.

Open questions from my side:
- Is this a good feature name?
  - `panic_immediate_abort` is fairly verbose, so I went with something equally verbose
  - It's easy to refactor later
- I've added the feature to `std` and `alloc` as well as they might benefit too. Do we agree?
  - I expect these to get less usage out of the flag since most size-constraint projects don't use these libraries often.
2024-05-21 12:47:04 +02:00
Michael Goulet
1a81092531 Add the impls for Box<[T]>: IntoIterator
Co-authored-by: ltdk <usr@ltdk.xyz>
2024-05-20 19:21:30 -04:00
Matthias Krüger
d1da2387a4
Rollup merge of #125283 - zachs18:arc-default-shared, r=dtolnay
Use a single static for all default slice Arcs.

Also adds debug_asserts in Drop for Weak/Arc that the shared static is not being "dropped"/"deallocated".

As per https://github.com/rust-lang/rust/pull/124640#pullrequestreview-2064962003

r? dtolnay
2024-05-20 14:26:53 +02:00
Matthias Krüger
7389416284
Rollup merge of #125093 - zachs18:rc-into-raw-with-allocator-only, r=Mark-Simulacrum
Add `fn into_raw_with_allocator` to Rc/Arc/Weak.

Split out from #119761

Add `fn into_raw_with_allocator` for `Rc`/`rc::Weak`[^1]/`Arc`/`sync::Weak`.
* Pairs with `from_raw_in` (which already exists on all 4 types).
* Name matches `Box::into_raw_with_allocator`.
* Associated fns on `Rc`/`Arc`, methods on `Weak`s.

<details> <summary>Future PR/ACP</summary>

As a follow-on to this PR, I plan to make a PR/ACP later to move `into_raw(_parts)` from `Container<_, A: Allocator>` to only `Container<_, Global>` (where `Container` = `Vec`/`Box`/`Rc`/`rc::Weak`/`Arc`/`sync::Weak`) so that users of non-`Global` allocators have to explicitly handle the allocator when using `into_raw`-like APIs.

The current behaviors of stdlib containers are inconsistent with respect to what happens to the allocator when `into_raw` is called (which does not return the allocator)

| Type | `into_raw` currently callable with | behavior of `into_raw`|
| --- | --- | --- |
| `Box` | any allocator | allocator is [dropped](https://doc.rust-lang.org/nightly/src/alloc/boxed.rs.html#1060) |
| `Vec` | any allocator | allocator is [forgotten](https://doc.rust-lang.org/nightly/src/alloc/vec/mod.rs.html#884) |
| `Arc`/`Rc`/`Weak` | any allocator | allocator is [forgotten](https://doc.rust-lang.org/src/alloc/sync.rs.html#1487)(Arc) [(sync::Weak)](https://doc.rust-lang.org/src/alloc/sync.rs.html#2726) [(Rc)](https://doc.rust-lang.org/src/alloc/rc.rs.html#1352) [(rc::Weak)](https://doc.rust-lang.org/src/alloc/rc.rs.html#2993) |

In my opinion, neither implicitly dropping nor implicitly forgetting the allocator is ideal; dropping it could immediately invalidate the returned pointer, and forgetting it could unintentionally leak memory. My (to-be) proposed solution is to just forbid calling `into_raw(_parts)` on containers with non-`Global` allocators, and require calling `into_raw_with_allocator`(/`Vec::into_raw_parts_with_alloc`)

</details>

[^1]:  Technically, `rc::Weak::into_raw_with_allocator` is not newly added, as it was modified and renamed from `rc::Weak::into_raw_and_alloc`.
2024-05-20 08:31:41 +02:00
bors
12075f04e6 Auto merge of #123878 - jwong101:inplacecollect, r=jhpratt
optimize inplace collection of Vec

This PR has the following changes:

1. Using `usize::unchecked_mul` in 79424056b0/library/alloc/src/vec/in_place_collect.rs (L262) as LLVM, does not know that the operation can't wrap, since that's the size of the original allocation.

Given the following:

```rust

pub struct Foo([usize; 3]);

pub fn unwrap_copy(v: Vec<Foo>) -> Vec<[usize; 3]> {
    v.into_iter().map(|f| f.0).collect()
}
```

<details>
<summary>Before this commit:</summary>

```llvm
define void `@unwrap_copy(ptr` noalias nocapture noundef writeonly sret([24 x i8]) align 8 dereferenceable(24) %_0, ptr noalias nocapture noundef readonly align 8 dereferenceable(24) %iter) {
start:
  %me.sroa.0.0.copyload.i = load i64, ptr %iter, align 8
  %me.sroa.4.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 8
  %me.sroa.4.0.copyload.i = load ptr, ptr %me.sroa.4.0.self.sroa_idx.i, align 8
  %me.sroa.5.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 16
  %me.sroa.5.0.copyload.i = load i64, ptr %me.sroa.5.0.self.sroa_idx.i, align 8
  %_19.i.idx = mul nsw i64 %me.sroa.5.0.copyload.i, 24
  %0 = udiv i64 %_19.i.idx, 24

; Unnecessary calculation
  %_16.i.i = mul i64 %me.sroa.0.0.copyload.i, 24
  %dst_cap.i.i = udiv i64 %_16.i.i, 24

  store i64 %dst_cap.i.i, ptr %_0, align 8
  %1 = getelementptr inbounds i8, ptr %_0, i64 8
  store ptr %me.sroa.4.0.copyload.i, ptr %1, align 8
  %2 = getelementptr inbounds i8, ptr %_0, i64 16
  store i64 %0, ptr %2, align 8
  ret void
}
```
</details>

<details>
<summary>After:</summary>

```llvm
define void `@unwrap_copy(ptr` noalias nocapture noundef writeonly sret([24 x i8]) align 8 dereferenceable(24) %_0, ptr noalias nocapture noundef readonly align 8 dereferenceable(24) %iter) {
start:
  %me.sroa.0.0.copyload.i = load i64, ptr %iter, align 8
  %me.sroa.4.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 8
  %me.sroa.4.0.copyload.i = load ptr, ptr %me.sroa.4.0.self.sroa_idx.i, align 8
  %me.sroa.5.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 16
  %me.sroa.5.0.copyload.i = load i64, ptr %me.sroa.5.0.self.sroa_idx.i, align 8
  %_19.i.idx = mul nsw i64 %me.sroa.5.0.copyload.i, 24
  %0 = udiv i64 %_19.i.idx, 24
  store i64 %me.sroa.0.0.copyload.i, ptr %_0, align 8
  %1 = getelementptr inbounds i8, ptr %_0, i64 8
  store ptr %me.sroa.4.0.copyload.i, ptr %1, align 8
  %2 = getelementptr inbounds i8, ptr %_0, i64 16
  store i64 %0, ptr %2, align 8, !alias.scope !9, !noalias !14
  ret void
}
```
</details>

Note that there is still one more `mul,udiv` pair that I couldn't get
rid of. The root cause is the same issue as https://github.com/rust-lang/rust/issues/121239, the `nuw` gets
stripped off of `ptr::sub_ptr`.

2.

`Iterator::try_fold` gets called on the underlying Iterator in
`SpecInPlaceCollect::collect_in_place` whenever it does not implement
`TrustedRandomAccess`. For types that impl `Drop`, LLVM currently can't
tell that the drop can never occur, when using the default
`Iterator::try_fold` implementation.

For example, given the following code from #120493

```rust
#[repr(transparent)]
struct WrappedClone {
    inner: String
}

#[no_mangle]
pub fn unwrap_clone(list: Vec<WrappedClone>) -> Vec<String> {
    list.into_iter().map(|s| s.inner).collect()
}
```

<details>
<summary>The asm for the `unwrap_clone` method is currently:</summary>

```asm
unwrap_clone:
        push    rbp
        push    r15
        push    r14
        push    r13
        push    r12
        push    rbx
        push    rax
        mov     rbx, rdi
        mov     r12, qword ptr [rsi]
        mov     rdi, qword ptr [rsi + 8]
        mov     rax, qword ptr [rsi + 16]
        movabs  rsi, -6148914691236517205
        mov     r14, r12
        test    rax, rax
        je      .LBB0_10
        lea     rcx, [rax + 2*rax]
        lea     r14, [r12 + 8*rcx]
        shl     rax, 3
        lea     rax, [rax + 2*rax]
        xor     ecx, ecx
.LBB0_2:
        cmp     qword ptr [r12 + rcx], 0
        je      .LBB0_4
        add     rcx, 24
        cmp     rax, rcx
        jne     .LBB0_2
        jmp     .LBB0_10
.LBB0_4:
        lea     rdx, [rax - 24]
        lea     r14, [r12 + rcx]
        cmp     rdx, rcx
        je      .LBB0_10
        mov     qword ptr [rsp], rdi
        sub     rax, rcx
        add     rax, -24
        mul     rsi
        mov     r15, rdx
        lea     rbp, [r12 + rcx]
        add     rbp, 32
        shr     r15, 4
        mov     r13, qword ptr [rip + __rust_dealloc@GOTPCREL]
        jmp     .LBB0_6
.LBB0_8:
        add     rbp, 24
        dec     r15
        je      .LBB0_9
.LBB0_6:
        mov     rsi, qword ptr [rbp]
        test    rsi, rsi
        je      .LBB0_8
        mov     rdi, qword ptr [rbp - 8]
        mov     edx, 1
        call    r13
        jmp     .LBB0_8
.LBB0_9:
        mov     rdi, qword ptr [rsp]
        movabs  rsi, -6148914691236517205
.LBB0_10:
        sub     r14, r12
        mov     rax, r14
        mul     rsi
        shr     rdx, 4
        mov     qword ptr [rbx], r12
        mov     qword ptr [rbx + 8], rdi
        mov     qword ptr [rbx + 16], rdx
        mov     rax, rbx
        add     rsp, 8
        pop     rbx
        pop     r12
        pop     r13
        pop     r14
        pop     r15
        pop     rbp
        ret
```
</details>

<details>
<summary>After this PR:</summary>

```asm
unwrap_clone:
	mov	rax, rdi
	movups	xmm0, xmmword ptr [rsi]
	mov	rcx, qword ptr [rsi + 16]
	movups	xmmword ptr [rdi], xmm0
	mov	qword ptr [rdi + 16], rcx
	ret
```
</details>

Fixes https://github.com/rust-lang/rust/issues/120493
2024-05-20 00:51:12 +00:00
Zachary S
3299823d62 Fix typo in assert message 2024-05-19 13:29:45 -05:00
Zachary S
58f8ed122a cfg-out unused code under no_global_oom_handling 2024-05-19 13:27:17 -05:00
Zachary S
6fae171e54 fmt 2024-05-19 13:21:53 -05:00
Zachary S
2dacd70e1e Fix stacked borrows violation 2024-05-19 11:42:35 -05:00
Zachary S
e6396bca01 Use a single static for all default slice Arcs.
Also adds debug_asserts in Drop for Weak/Arc that the shared static is not being "dropped"/"deallocated".
2024-05-19 11:02:22 -05:00
bors
496f7310c8 Auto merge of #124640 - Billy-Sheppard:master, r=dtolnay
Fix #124275: Implemented Default for `Arc<str>`

With added implementations.

```
GOOD    Arc<CStr>
BROKEN  Arc<OsStr> // removed
GOOD    Rc<str>
GOOD    Rc<CStr>
BROKEN  Rc<OsStr> // removed

GOOD    Rc<[T]>
GOOD    Arc<[T]>
```

For discussion of https://github.com/rust-lang/rust/pull/124367#issuecomment-2091940137.

Key pain points currently:
> I've had a guess at the best locations/feature attrs for them but they might not be correct.

> However I'm unclear how to get the OsStr impl to compile, which file should they go in to avoid the error below? Is it possible, perhaps with some special std rust lib magic?
2024-05-19 06:25:20 +00:00
bors
bfa3635df9 Auto merge of #99969 - calebsander:feature/collect-box-str, r=dtolnay
alloc: implement FromIterator for Box<str>

`Box<[T]>` implements `FromIterator<T>` using `Vec<T>` + `into_boxed_slice()`.
Add analogous `FromIterator` implementations for `Box<str>`
matching the current implementations for `String`.
Remove the `Global` allocator requirement for `FromIterator<Box<str>>` too.

ACP: https://github.com/rust-lang/libs-team/issues/196
2024-05-19 02:13:06 +00:00
Joshua Wong
65e302fc36 use Result::into_ok on infallible result. 2024-05-18 19:15:21 -05:00
Joshua Wong
9d6b93c3e6 specialize Iterator::fold for vec::IntoIter
LLVM currently adds a redundant check for the returned option, in addition
to the `self.ptr != self.end` check when using the default
`Iterator::fold` method that calls `vec::IntoIter::next` in a loop.
2024-05-18 18:30:20 -05:00
Joshua Wong
6165dca6db optimize in_place_collect with vec::IntoIter::try_fold
`Iterator::try_fold` gets called on the underlying Iterator in
`SpecInPlaceCollect::collect_in_place` whenever it does not implement
`TrustedRandomAccess`. For types that impl `Drop`, LLVM currently can't
tell that the drop can never occur, when using the default
`Iterator::try_fold` implementation.

For example, the asm from the `unwrap_clone` method is currently:

```
unwrap_clone:
        push    rbp
        push    r15
        push    r14
        push    r13
        push    r12
        push    rbx
        push    rax
        mov     rbx, rdi
        mov     r12, qword ptr [rsi]
        mov     rdi, qword ptr [rsi + 8]
        mov     rax, qword ptr [rsi + 16]
        movabs  rsi, -6148914691236517205
        mov     r14, r12
        test    rax, rax
        je      .LBB0_10
        lea     rcx, [rax + 2*rax]
        lea     r14, [r12 + 8*rcx]
        shl     rax, 3
        lea     rax, [rax + 2*rax]
        xor     ecx, ecx
.LBB0_2:
        cmp     qword ptr [r12 + rcx], 0
        je      .LBB0_4
        add     rcx, 24
        cmp     rax, rcx
        jne     .LBB0_2
        jmp     .LBB0_10
.LBB0_4:
        lea     rdx, [rax - 24]
        lea     r14, [r12 + rcx]
        cmp     rdx, rcx
        je      .LBB0_10
        mov     qword ptr [rsp], rdi
        sub     rax, rcx
        add     rax, -24
        mul     rsi
        mov     r15, rdx
        lea     rbp, [r12 + rcx]
        add     rbp, 32
        shr     r15, 4
        mov     r13, qword ptr [rip + __rust_dealloc@GOTPCREL]
        jmp     .LBB0_6
.LBB0_8:
        add     rbp, 24
        dec     r15
        je      .LBB0_9
.LBB0_6:
        mov     rsi, qword ptr [rbp]
        test    rsi, rsi
        je      .LBB0_8
        mov     rdi, qword ptr [rbp - 8]
        mov     edx, 1
        call    r13
        jmp     .LBB0_8
.LBB0_9:
        mov     rdi, qword ptr [rsp]
        movabs  rsi, -6148914691236517205
.LBB0_10:
        sub     r14, r12
        mov     rax, r14
        mul     rsi
        shr     rdx, 4
        mov     qword ptr [rbx], r12
        mov     qword ptr [rbx + 8], rdi
        mov     qword ptr [rbx + 16], rdx
        mov     rax, rbx
        add     rsp, 8
        pop     rbx
        pop     r12
        pop     r13
        pop     r14
        pop     r15
        pop     rbp
        ret
```

After this PR:

```
unwrap_clone:
	mov	rax, rdi
	movups	xmm0, xmmword ptr [rsi]
	mov	rcx, qword ptr [rsi + 16]
	movups	xmmword ptr [rdi], xmm0
	mov	qword ptr [rdi + 16], rcx
	ret
```

Fixes #120493
2024-05-18 18:30:20 -05:00
Joshua Wong
c585541e67 optimize in-place collection of Vec
LLVM does not know that the multiplication never overflows, which causes
it to generate unnecessary instructions. Use `usize::unchecked_mul`, so
that it can fold the `dst_cap` calculation when `size_of::<I::SRC>() ==
size_of::<T>()`.

Running:

```
rustc -C llvm-args=-x86-asm-syntax=intel -O src/lib.rs --emit asm`
```

```rust

pub struct Foo([usize; 3]);

pub fn unwrap_copy(v: Vec<Foo>) -> Vec<[usize; 3]> {
    v.into_iter().map(|f| f.0).collect()
}
```

Before this commit:

```
define void @unwrap_copy(ptr noalias nocapture noundef writeonly sret([24 x i8]) align 8 dereferenceable(24) %_0, ptr noalias nocapture noundef readonly align 8 dereferenceable(24) %iter) {
start:
  %me.sroa.0.0.copyload.i = load i64, ptr %iter, align 8
  %me.sroa.4.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 8
  %me.sroa.4.0.copyload.i = load ptr, ptr %me.sroa.4.0.self.sroa_idx.i, align 8
  %me.sroa.5.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 16
  %me.sroa.5.0.copyload.i = load i64, ptr %me.sroa.5.0.self.sroa_idx.i, align 8
  %_19.i.idx = mul nsw i64 %me.sroa.5.0.copyload.i, 24
  %0 = udiv i64 %_19.i.idx, 24
  %_16.i.i = mul i64 %me.sroa.0.0.copyload.i, 24
  %dst_cap.i.i = udiv i64 %_16.i.i, 24
  store i64 %dst_cap.i.i, ptr %_0, align 8
  %1 = getelementptr inbounds i8, ptr %_0, i64 8
  store ptr %me.sroa.4.0.copyload.i, ptr %1, align 8
  %2 = getelementptr inbounds i8, ptr %_0, i64 16
  store i64 %0, ptr %2, align 8
  ret void
}
```

After:

```
define void @unwrap_copy(ptr noalias nocapture noundef writeonly sret([24 x i8]) align 8 dereferenceable(24) %_0, ptr noalias nocapture noundef readonly align 8 dereferenceable(24) %iter) {
start:
  %me.sroa.0.0.copyload.i = load i64, ptr %iter, align 8
  %me.sroa.4.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 8
  %me.sroa.4.0.copyload.i = load ptr, ptr %me.sroa.4.0.self.sroa_idx.i, align 8
  %me.sroa.5.0.self.sroa_idx.i = getelementptr inbounds i8, ptr %iter, i64 16
  %me.sroa.5.0.copyload.i = load i64, ptr %me.sroa.5.0.self.sroa_idx.i, align 8
  %_19.i.idx = mul nsw i64 %me.sroa.5.0.copyload.i, 24
  %0 = udiv i64 %_19.i.idx, 24
  store i64 %me.sroa.0.0.copyload.i, ptr %_0, align 8
  %1 = getelementptr inbounds i8, ptr %_0, i64 8
  store ptr %me.sroa.4.0.copyload.i, ptr %1, align 8
  %2 = getelementptr inbounds i8, ptr %_0, i64 16
  store i64 %0, ptr %2, align 8, !alias.scope !9, !noalias !14
  ret void
}
```

Note that there is still one more `mul,udiv` pair that I couldn't get
rid of. The root cause is the same issue as #121239, the `nuw` gets
stripped off of `ptr::sub_ptr`.
2024-05-18 18:30:20 -05:00
Jon Gjengset
0beba9699c Clarify how String::leak and into_boxed_str differ 2024-05-18 19:17:43 +02:00
Zachary S
c895f6e958 Access alloc field directly in Arc/Rc::into_raw_with_allocator.
... since fn allocator doesn't exist yet.
2024-05-16 21:09:05 -05:00
Lukas Bergdoll
88fb5edb65 Fix linkchecker doc errors
Also includes small doc fixes.
2024-05-16 17:08:56 +02:00
Lukas Bergdoll
d20b1190cf Move BufGuard impl outside of function 2024-05-16 17:08:56 +02:00
Lukas Bergdoll
e49be415cd Replace sort implementations
- `slice::sort` -> driftsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/driftsort_introduction/text.md

- `slice::sort_unstable` -> ipnsort
  https://github.com/Voultapher/sort-research-rs/blob/main/writeup/ipnsort_introduction/text.md

Replaces the sort implementations with tailor made ones that strike a
balance of run-time, compile-time and binary-size, yielding run-time and
compile-time improvements. Regressing binary-size for `slice::sort`
while improving it for `slice::sort_unstable`. All while upholding the
existing soft and hard safety guarantees, and even extending the soft
guarantees, detecting strict weak ordering violations with a high chance
and reporting it to users via a panic.

In addition the implementation of `select_nth_unstable` is also adapted
as it uses `slice::sort_unstable` internals.
2024-05-16 17:08:55 +02:00
Zachary S
28cb2d7dfb Add fn into_raw_with_allocator to Rc/Arc/Weak. 2024-05-13 17:49:41 -05:00
Dion Dokter
b8b68983f3
Forward alloc features to core 2024-05-13 22:20:32 +02:00
Josh Triplett
a5a60d75a8 Add size_of, size_of_val, align_of, and align_of_val to the prelude
Many, many projects use `size_of` to get the size of a type. However,
it's also often equally easy to hardcode a size (e.g. `8` instead of
`size_of::<u64>()`). Minimizing friction in the use of `size_of` helps
ensure that people use it and make code more self-documenting.

The name `size_of` is unambiguous: the name alone, without any prefix or
path, is self-explanatory and unmistakeable for any other functionality.
Adding it to the prelude cannot produce any name conflicts, as any local
definition will silently shadow the one from the prelude. Thus, we don't
need to wait for a new edition prelude to add it.

Add `size_of_val`, `align_of`, and `align_of_val` as well, with similar
justification: widely useful, self-explanatory, unmistakeable for
anything else, won't produce conflicts.
2024-05-13 15:11:28 +02:00
Zachary S
f27d1e114c Use shared statics for the ArcInner for Arc<str, CStr>::default, and for Arc<[T]>::default where alignof(T) <= 16. 2024-05-12 20:29:08 -05:00
Zachary S
0b3ebb546f Add note about possible allocation-sharing to Arc/Rc<str/[T]/CStr>::default. 2024-05-12 20:27:29 -05:00
Billy Sheppard
5c6326ad79 added Default impls
reorganised attrs

removed OsStr impls

added backticks
2024-05-12 20:27:28 -05:00
bors
4fd98a4b1b Auto merge of #125012 - RalfJung:format-error, r=Mark-Simulacrum,workingjubilee
io::Write::write_fmt: panic if the formatter fails when the stream does not fail

Follow-up to https://github.com/rust-lang/rust/pull/124954
2024-05-12 08:34:32 +00:00
Matthias Krüger
e3fca20eae
Rollup merge of #124981 - zachs18:rc-allocator-generalize-1, r=Mark-Simulacrum
Relax allocator requirements on some Rc/Arc APIs.

Split out from #119761

* Remove `A: Clone` bound from `Rc::assume_init`(s), `Rc::downcast`, and `Rc::downcast_unchecked` (`Arc` methods were already relaxed by #120445)
* Make `From<Rc<[T; N]>> for Rc<[T]>` allocator-aware (`Arc`'s already is).
* Remove `A: Clone` from `Rc/Arc::unwrap_or_clone`

Internal changes:

* Made `Arc::internal_into_inner_with_allocator` method into `Arc::into_inner_with_allocator` associated fn.
* Add private `Rc::into_inner_with_allocator` (to match Arc), so other fns don't have to juggle `ManuallyDrop`.
2024-05-11 23:43:25 +02:00
Ralf Jung
e00f27b7be io::Write::write_fmt: panic if the formatter fails when the stream does not fail 2024-05-11 15:13:18 +02:00
Dion Dokter
579266a6be Add flag to std and alloc too 2024-05-11 14:20:03 +02:00
Zachary S
8d8eb505b0 Relax A: Clone requirement on Rc/Arc::unwrap_or_clone. 2024-05-10 14:34:19 -05:00
Zachary S
d6122f1924 Relax allocator requirements on some Rc APIs.
* Remove A: Clone bound from Rc::assume_init, Rc::downcast, and Rc::downcast_unchecked.
* Make From<Rc<[T; N]>> for Rc<[T]> allocator-aware.

Internal changes:

* Made Arc::internal_into_inner_with_allocator method into Arc::into_inner_with_allocator associated fn.
* Add private Rc::into_inner_with_allocator (to match Arc), so other fns don't have to juggle ManuallyDrop.
2024-05-10 14:11:23 -05:00
Zachary S
a1ad6346d6 Add fn allocator method to rc/sync::Weak. Relax Rc<T>/Arc<T>::allocator to allow unsized T. 2024-05-10 13:44:19 -05:00
Kevin Reid
c21c5baad9 Document proper usage of fmt::Error and fmt()'s Result.
Documentation of these properties previously existed in a lone paragraph
in the `fmt` module's documentation:
<https://doc.rust-lang.org/1.78.0/std/fmt/index.html#formatting-traits>
However, users looking to implement a formatting trait won't necessarily
look there. Therefore, let's add the critical information (that
formatting per se is infallible) to all the involved items.
2024-05-09 17:58:38 -07:00
Marcondiro
bbdf97254a
fix #124714 str.to_lowercase sigma handling 2024-05-08 17:05:10 +02:00
Markus Everling
5cb53bc34d Move test_shrink_to_unwind to its own file.
This way, no other test can be tripped up by `test_shrink_to_unwind` changing the alloc error hook.
2024-05-07 19:43:54 +00:00
Markus Everling
ffe8510e3d Fix VecDeque::shrink_to UB when handle_alloc_error unwinds.
Luckily it's comparatively simple to just restore the `VecDeque` into a valid state on unwinds.
2024-05-07 19:30:34 +00:00
Caleb Sander
c92c228260 alloc: implement FromIterator for Box<str>
Box<[T]> implements FromIterator<T> using Vec<T> + into_boxed_slice().
Add analogous FromIterator implementations for Box<str>
matching the current implementations for String.
Remove the Global allocator requirement for FromIterator<Box<str>> too.
2024-05-05 10:29:57 -07:00
Guillaume Gomez
d3e042dc4e
Rollup merge of #124749 - RossSmyth:stable_range, r=davidtwco
Stabilize exclusive_range_pattern (v2)

This PR is identical to #124459, which was approved and merged but then removed from master by a force-push due to a [CI bug](https://rust-lang.zulipchat.com/#narrow/stream/242791-t-infra/topic/ci.20broken.3F).

r? ghost

Original PR description:

---

Stabilization report: https://github.com/rust-lang/rust/issues/37854#issuecomment-1842398130
FCP: https://github.com/rust-lang/rust/issues/37854#issuecomment-1872520294

Stabilization was blocked by a lint that was merged here: #118879

Documentation PR is here: rust-lang/reference#1484

`@rustbot` label +F-exclusive_range_pattern +T-lang
2024-05-05 16:42:48 +02:00
Matthias Krüger
1ff247c404
Rollup merge of #124593 - GKFX:cstr-literals-in-api-docs, r=workingjubilee
Describe and use CStr literals in CStr and CString docs

Mention CStr literals in the description of both types, and use them in some of the code samples for CStr. This is intended to make C string literals more discoverable.

Additionally, I don't think the orange "This example is not tested" warnings are very encouraging, so I have made the examples on `CStr` build.
2024-05-03 20:33:46 +02:00
Matthias Krüger
d7a8936b78
Rollup merge of #124441 - bravequickcleverfibreyarn:string.rs, r=Amanieu
String.truncate comment microfix (greater or equal)

String.truncate calls Vec.truncate, in turn, and that states "is greater or equal to". Beside common sense.
2024-05-03 06:04:20 +02:00
Matthias Krüger
e17a222a0a
Rollup merge of #123480 - Nadrieril:impl-all-derefpures, r=compiler-errors
deref patterns: impl `DerefPure` for more std types

Context: [deref patterns](https://github.com/rust-lang/rust/issues/87121). The requirements of `DerefPure` aren't precise yet, but these types unambiguously satisfy them.

Interestingly, a hypothetical `impl DerefMut for Cow` that does a `Clone` would *not* be eligible for `DerefPure` if we allow mixing deref patterns with normal patterns. If the following is exhaustive then the `DerefMut` would cause UB:
```rust
match &mut Cow::Borrowed(&()) {
    Cow::Owned(_) => ..., // Doesn't match
    deref!(_x) if false => ..., // Causes the variant to switch to `Owned`
    Cow::Borrowed(_) => ..., // Doesn't match
    // We reach unreachable
}
```
2024-05-03 06:04:19 +02:00
Ross Smyth
6967d1c0fc Stabilize exclusive_range 2024-05-02 19:42:31 -04:00
Mark Rousskov
a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
Mark Rousskov
bd7d328807 Replace version placeholders for 1.79 2024-05-01 21:01:51 -04:00
George Bateman
e610a52a62
Describe and use CStr literals in CStr and CString docs 2024-05-01 19:59:00 +01:00
Trevor Gross
e0f8202ed5 Stabilize non_null_convenience
Fully stabilize the following API, including const where applicable:

    impl <T> NonNull<T> {
        pub const unsafe fn offset(self, count: isize) -> Self;
        pub const unsafe fn add(self, count: usize) -> Self;
        pub const unsafe fn sub(self, count: usize) -> Self;
        pub const unsafe fn offset_from(self, origin: NonNull<T>) -> isize;
        pub const unsafe fn read(self) -> T;
        pub unsafe fn read_volatile(self) -> T;
        pub const unsafe fn read_unaligned(self) -> T;
        pub unsafe fn write_volatile(self, val: T);
        pub unsafe fn replace(self, src: T) -> T;
    }

    impl<T: ?Sized> NonNull<T> {
        pub const unsafe fn byte_offset(self, count: isize) -> Self;
        pub const unsafe fn byte_add(self, count: usize) -> Self;
        pub const unsafe fn byte_sub(self, count: usize) -> Self;
        pub const unsafe fn byte_offset_from<U: ?Sized>(self, origin: NonNull<U>) -> isize;
        pub unsafe fn drop_in_place(self);
    }

Stabilize the following without const:

    impl <T> NonNull<T> {
        // const under `const_intrinsic_copy`
        pub const unsafe fn copy_to(self, dest: NonNull<T>, count: usize);
        pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull<T>, count: usize);
        pub const unsafe fn copy_from(self, src: NonNull<T>, count: usize);
        pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull<T>, count: usize);

        // const under `const_ptr_write`
        pub const unsafe fn write(self, val: T);
        pub const unsafe fn write_bytes(self, val: u8, count: usize);
        pub const unsafe fn write_unaligned(self, val: T);

        // const under `const_swap`
        pub const unsafe fn swap(self, with: NonNull<T>);

        // const under `const_align_offset`
        pub const fn align_offset(self, align: usize) -> usize;

        // const under `const_pointer_is_aligned`
        pub const fn is_aligned(self) -> bool;
    }

Left the following unstable:

    impl <T> NonNull<T> {
        // moved gate to `ptr_sub_ptr`
        pub const unsafe fn sub_ptr(self, subtracted: NonNull<T>) -> usize;
    }

    impl <T: ?Sized> NonNull<T> {
        // moved gate to `pointer_is_aligned_to`
        pub const fn is_aligned_to(self, align: usize) -> bool;
    }

Fixes: https://github.com/rust-lang/rust/issues/117691
2024-04-28 16:19:53 -05:00
JirCep
f840da757f WS fix. 2024-04-27 17:18:25 +02:00
JirCep
825a3b1f09 String.truncate calls Vec.truncate, in turn, and that states
"is greater or equal to". Beside common sense.
2024-04-27 16:57:20 +02:00
bors
61a1dbd751 Auto merge of #124432 - zetanumbers:non_copy_into_raw_with_alloc, r=Nilstrieb
Relax `A: Clone` bound for `rc::Weak::into_raw_and_alloc`

Makes this method to behave the same way as [`Box::into_raw_with_allocator`](https://doc.rust-lang.org/1.77.2/alloc/boxed/struct.Box.html#method.into_raw_with_allocator) and [`Vec::into_raw_parts_with_alloc`](https://doc.rust-lang.org/1.77.2/alloc/vec/struct.Vec.html#method.into_raw_parts_with_alloc).

I have also noticed the inconsistent presence and naming, should probably be addressed in the future.
2024-04-27 13:41:45 +00:00
Daria Sukhonina
255a1e9554 Relax A: Clone bound for rc::Weak::into_raw_and_alloc 2024-04-27 12:21:23 +03:00
bors
4d570eea02 Auto merge of #123909 - dtolnay:utf8chunks, r=joboet
Stabilize `Utf8Chunks`

Pending FCP in https://github.com/rust-lang/rust/issues/99543.

This PR includes the proposed modification in https://github.com/rust-lang/libs-team/issues/190 as agreed in https://github.com/rust-lang/rust/issues/99543#issuecomment-2050406568.
2024-04-26 17:41:24 +00:00
David Tolnay
61cf00464e
Stabilize Utf8Chunks 2024-04-24 15:27:47 -07:00
Thomas Lindae
d3bbdcf26c fix typo in binary_heap docs 2024-04-24 22:59:39 +02:00
Gary Guo
94c1920497 Stabilise inline_const 2024-04-24 13:12:25 +01:00
Markus Reiter
33e68aadc9
Stabilize generic NonZero. 2024-04-22 18:48:47 +02:00
Mark Rousskov
f1ae5314be Avoid reloading Vec::len across grow_one in push
This saves an extra load from memory.
2024-04-20 21:07:00 -04:00
Matthias Krüger
21deaed4a1
Rollup merge of #122201 - coolreader18:doc-clone_from, r=dtolnay
Document overrides of `clone_from()` in core/std

As mentioned in https://github.com/rust-lang/rust/pull/96979#discussion_r1379502413

Specifically, when an override doesn't just forward to an inner type, document the behavior and that it's preferred over simply assigning a clone of source. Also, change instances where the second parameter is "other" to "source".

I reused some of the wording over and over for similar impls, but I'm not sure that the wording is actually *good*. Would appreciate feedback about that.

Also, now some of these seem to provide pretty specific guarantees about behavior (e.g. will reuse the exact same allocation iff the len is the same), but I was basing it off of the docs for [`Box::clone_from`](https://doc.rust-lang.org/1.75.0/std/boxed/struct.Box.html#method.clone_from-1) - I'm not sure if providing those strong guarantees is actually good or not.
2024-04-17 18:01:37 +02:00
Noa
87db7c32a7
Address comments 2024-04-17 00:18:04 -05:00
Slanterns
d5d56d00e7
Stabilize BinaryHeap::as_slice 2024-04-16 20:58:45 +08:00
Ralf Jung
8606efa5d2 Box::into_raw: make Miri understand that this is a box-to-raw cast 2024-04-16 14:18:06 +02:00
Jacob Pratt
0518ecc700
Rollup merge of #123868 - eduardosm:stabilize-slice_ptr_len, r=jhpratt
Stabilize (const_)slice_ptr_len and (const_)slice_ptr_is_empty_nonnull

Stabilized API:

```rust
impl<T> *mut [T] {
    pub const fn len(self) -> usize;
    pub const fn is_empty(self) -> bool;
}

impl<T> *const [T] {
    pub const fn len(self) -> usize;
    pub const fn is_empty(self) -> bool;
}

impl<T> NonNull<[T]> {
    pub const fn is_empty(self) -> bool;
}
```

FCP completed in tracking issue: https://github.com/rust-lang/rust/issues/71146
2024-04-13 00:18:46 -04:00
Jacob Pratt
8533144f97
Rollup merge of #123835 - saethlin:vec-from-nonnull, r=the8472
Avoid more NonNull-raw-NonNull roundtrips in Vec

r? the8472

The standard library in general has a lot of these round-trips from niched types to their raw innards and back. Such round-trips have overhead in debug builds since https://github.com/rust-lang/rust/pull/120594. I removed some such round-trips in that initial PR and I've been meaning to come back and hunt down more such examples (this is the last item on https://github.com/rust-lang/rust/issues/120848).
2024-04-13 00:18:46 -04:00
Ben Kimock
f7d54fa6cb Avoid more NonNull-raw-NonNull roundtrips in Vec 2024-04-12 18:14:29 -04:00
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