Commit Graph

15226 Commits

Author SHA1 Message Date
许杰友 Jieyou Xu (Joe)
d5a04221ef
Rollup merge of #125504 - mqudsi:once_nominal, r=cuviper
Change pedantically incorrect OnceCell/OnceLock wording

While the semantic intent of a OnceCell/OnceLock is that it can only be written to once (upon init), the fact of the matter is that both these types offer a `take(&mut self) -> Option<T>` mechanism that, when successful, resets the cell to its initial state, thereby [technically allowing it to be written to again](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=415c023a6ae1ef35f371a2d3bb1aa735)

Despite the fact that this can only happen with a mutable reference (generally only used during the construction of the OnceCell/OnceLock), it would be incorrect to say that the type itself as a whole *categorically* prevents being initialized or written to more than once (since it is possible to imagine an identical type only without the `take()` method that actually fulfills that contract).

To clarify, change "that cannot be.." to "that nominally cannot.." and add a note to OnceCell about what can be done with an `&mut Self` reference.

```@rustbot``` label +A-rustdocs
2024-06-04 08:25:46 +01:00
Raoul Strackx
8db363c44b Let compiler auto impl Send for Task 2024-06-04 08:46:45 +02:00
Raoul Strackx
b8c6008fbc Store Task::p as dyn FnOnce() + Send 2024-06-04 08:46:38 +02:00
Raoul Strackx
9b2e41a218 Pass function for Thread as Send to Thread::imp 2024-06-04 08:45:48 +02:00
bors
27529d5c25 Auto merge of #125525 - joboet:tls_accessor, r=cuviper
Make TLS accessors closures that return pointers

The current TLS macros generate a function that returns an `Option<&'static T>`. This is both risky as we lie about lifetimes, and necessitates that those functions are `unsafe`. By returning a `*const T` instead, the accessor function do not have safety requirements any longer and can be made closures without hassle. This PR does exactly that!

For native TLS, the closure approach makes it trivial to select the right accessor function at compile-time, which could result in a slight speed-up (I have the hope that the accessors are now simple enough for the MIR-inliner to kick in).
2024-06-04 05:03:52 +00:00
David Carlier
fd648a3c76 std::unix::fs::get_path: using fcntl codepath for netbsd instead.
on netbsd, procfs is not as central as on linux/solaris thus
can be perfectly not mounted.
Thus using fcntl with F_GETPATH, the kernel deals with MAXPATHLEN
internally too.
2024-06-04 04:36:48 +00:00
Tim Kurdov
9436fbe00d
Fix typo in the docs of HashMap::raw_entry_mut 2024-06-03 17:35:58 +01: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
bors
8768db9912 Auto merge of #125912 - nnethercote:rustfmt-tests-mir-opt, r=oli-obk
rustfmt `tests/mir-opt`

Continuing the work started in #125759. Details in individual commit log messages.

r? `@oli-obk`
2024-06-03 10:25:12 +00:00
Tobias Bucher
45760276fd Remove stray "this" 2024-06-03 12:20:19 +02:00
Jubilee Young
9ed7cfc952 Add "OnceList" example to motivate OnceLock
While slightly verbose, it helps explain "why bother with OnceLock?"
This is a point of confusion that has been raised multiple times
shortly before and after the stabilization of LazyLock.
2024-06-02 22:53:41 -07:00
Jubilee Young
2d0ebca979 Move first OnceLock example to LazyLock
This example is spiritually an example of LazyLock, as it computes a
variable at runtime but accepts no inputs into that process.
It is also slightly simpler and thus easier to understand.
Change it to an even-more concise version and move it to LazyLock.

The example now editorializes slightly more. This may be unnecessary,
but it can be educational for the reader.
2024-06-02 22:53:41 -07:00
Jubilee Young
fdb96f2123 Differ LazyLock vs. OnceLock in std::sync overview 2024-06-02 22:53:41 -07:00
Jubilee Young
940594ff18 Explain LazyCell in core::cell overview 2024-06-02 22:53:41 -07:00
Nicholas Nethercote
ac24299636 Reformat mir! macro invocations to use braces.
The `mir!` macro has multiple parts:
- An optional return type annotation.
- A sequence of zero or more local declarations.
- A mandatory starting anonymous basic block, which is brace-delimited.
- A sequence of zero of more additional named basic blocks.

Some `mir!` invocations use braces with a "block" style, like so:
```
mir! {
    let _unit: ();
    {
	let non_copy = S(42);
	let ptr = std::ptr::addr_of_mut!(non_copy);
	// Inside `callee`, the first argument and `*ptr` are basically
	// aliasing places!
	Call(_unit = callee(Move(*ptr), ptr), ReturnTo(after_call), UnwindContinue())
    }
    after_call = {
	Return()
    }
}
```
Some invocations use parens with a "block" style, like so:
```
mir!(
    let x: [i32; 2];
    let one: i32;
    {
	x = [42, 43];
	one = 1;
	x = [one, 2];
	RET = Move(x);
	Return()
    }
)
```
And some invocations uses parens with a "tighter" style, like so:
```
mir!({
    SetDiscriminant(*b, 0);
    Return()
})
```
This last style is generally used for cases where just the mandatory
starting basic block is present. Its braces are placed next to the
parens.

This commit changes all `mir!` invocations to use braces with a "block"
style. Why?

- Consistency is good.

- The contents of the invocation is a block of code, so it's odd to use
  parens. They are more normally used for function-like macros.

- Most importantly, the next commit will enable rustfmt for
  `tests/mir-opt/`. rustfmt is more aggressive about formatting macros
  that use parens than macros that use braces. Without this commit's
  changes, rustfmt would break a couple of `mir!` macro invocations that
  use braces within `tests/mir-opt` by inserting an extraneous comma.
  E.g.:
  ```
  mir!(type RET = (i32, bool);, { // extraneous comma after ';'
      RET.0 = 1;
      RET.1 = true;
      Return()
  })
  ```
  Switching those `mir!` invocations to use braces avoids that problem,
  resulting in this, which is nicer to read as well as being valid
  syntax:
  ```
  mir! {
      type RET = (i32, bool);
      {
	  RET.0 = 1;
	  RET.1 = true;
	  Return()
      }
  }
  ```
2024-06-03 13:24:44 +10:00
Jubilee
72ea7e9220
Rollup merge of #125898 - RalfJung:typo, r=Nilstrieb
typo: depending from -> on
2024-06-02 12:58:10 -07:00
Jubilee
890770d7bc
Rollup merge of #125884 - Rua:integer_sign_cast, r=Mark-Simulacrum
Implement feature `integer_sign_cast`

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

Since this is my first time making a library addition I wasn't sure where to place the new code relative to existing code. I decided to place it near the top where there are already some other basic bitwise manipulation functions. If there is an official guideline for the ordering of functions, please let me know.
2024-06-02 12:58:08 -07:00
Jubilee
713cdcd803
Rollup merge of #121062 - RustyYato:f32-midpoint, r=the8472
Change f32::midpoint to upcast to f64

This has been verified by kani as a correct optimization

see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398

The new implementation is branchless and only differs in which NaN values are produced (if any are produced at all), which is fine to change. Aside from NaN handling, this implementation produces bitwise identical results to the original implementation.

Question: do we need a codegen test for this? I didn't add one, since the original PR #92048 didn't have any codegen tests.
2024-06-02 12:58:07 -07:00
Rua
b181e8106c Wording of the documentation 2024-06-02 21:03:24 +02:00
Ralf Jung
361c6a5c3a typo: depending from -> on 2024-06-02 18:15:50 +02:00
bors
eda9d7f987 Auto merge of #125577 - devnexen:netbsd_stack_min, r=joboet
std::pal::unix::thread fetching min stack size on netbsd.

PTHREAD_STACK_MIN is not defined however sysconf/_SC_THREAD_STACK_MIN returns it as it can vary from arch to another.
2024-06-02 15:42:33 +00:00
Rua
d23d340858 Implement feature integer_sign_cast 2024-06-02 12:01:07 +02:00
RustyYato
849c5254af Change f32::midpoint to upcast to f64
This has been verified by kani as a correct optimization

see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398

The new implementation is branchless, and only differs in which NaN
values are produced (if any are produced at all). Which is fine to change.
Aside from NaN handling, this implementation produces bitwise identical
results to the original implementation.

The new implementation is gated on targets that have a fast 64-bit
floating point implementation in hardware, and on WASM.
2024-06-01 17:29:31 -07:00
bors
12b5d3c29c Auto merge of #124294 - tspiteri:ilog-first-iter, r=the8472
Unroll first iteration of checked_ilog loop

This follows the optimization of #115913. As shown in https://github.com/rust-lang/rust/pull/115913#issuecomment-2066788006, the performance was improved in all important cases, but some regressions were introduced for the benchmarks `u32_log_random_small`, `u8_log_random` and `u8_log_random_small`.

Basically, #115913 changed the implementation from one division per iteration to one multiplication per iteration plus one division. When there are zero iterations, this is a regression from zero divisions to one division.

This PR avoids this by avoiding the division if we need zero iterations by returning `Some(0)` early. It also reduces the number of multiplications by one in all other cases.
2024-06-02 00:05:32 +00: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
e9046602c5
Rollup merge of #125730 - mu001999-contrib:clippy-fix, r=oli-obk
Apply `x clippy --fix` and `x fmt` on Rustc

<!--
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>
-->

Just run `x clippy --fix` and `x fmt`, and remove some changes like `impl Default`.
2024-05-31 17:05:24 +02:00
bors
99cb42c296 Auto merge of #124662 - zetanumbers:needs_async_drop, r=oli-obk
Implement `needs_async_drop` in rustc and optimize async drop glue

This PR expands on #121801 and implements `Ty::needs_async_drop` which works almost exactly the same as `Ty::needs_drop`, which is needed for #123948.

Also made compiler's async drop code to look more like compiler's regular drop code, which enabled me to write an optimization where types which do not use `AsyncDrop` can simply forward async drop glue to `drop_in_place`. This made size of the async block from the [async_drop test](67980dd6fb/tests/ui/async-await/async-drop.rs) to decrease by 12%.
2024-05-31 10:12:24 +00:00
Raoul Strackx
7cd732f990 Avoid mut and simplify initialization of TASK_QUEUE 2024-05-30 16:16:48 +02:00
bors
91c0823ee6 Auto merge of #124636 - tbu-:pr_env_unsafe, r=petrochenkov
Make `std::env::{set_var, remove_var}` unsafe in edition 2024

Allow calling these functions without `unsafe` blocks in editions up until 2021, but don't trigger the `unused_unsafe` lint for `unsafe` blocks containing these functions.

Fixes #27970.
Fixes #90308.
CC #124866.
2024-05-30 12:17:06 +00:00
Matthias Krüger
a4d00ff8e4
Rollup merge of #125746 - jmillikin:duration-from-weeks-typo, r=lqd
Fix copy-paste error in `Duration::from_weeks` panic message.
2024-05-30 10:23:08 +02:00
Matthias Krüger
60c2d80482
Rollup merge of #125739 - RalfJung:drop-in-place-docs, r=workingjubilee
drop_in_place: weaken the claim of equivalence with drop(ptr.read())

The two are *not* semantically equivalent in all cases, so let's not be so definite about this.

Fixes https://github.com/rust-lang/rust/issues/112015
2024-05-30 10:23:07 +02:00
Matthias Krüger
70e7b49cf2
Rollup merge of #125342 - tbu-:pr_doc_write, r=ChrisDenton
Document platform-specifics for `Read` and `Write` of `File`
2024-05-30 10:23:06 +02:00
Ralf Jung
5c68a15e41 explain what the open questions are, and add a Miri test for that 2024-05-30 09:07:06 +02:00
r0cky
dabd05bbab Apply x clippy --fix and x fmt 2024-05-30 09:51:27 +08:00
John Millikin
a8234d5f87 Fix copy-paste error in Duration::from_weeks panic message. 2024-05-30 08:40:48 +09:00
León Orell Valerian Liehr
1ae1388d2a
Rollup merge of #125733 - compiler-errors:async-fn-assoc-item, r=fmease
Add lang items for `AsyncFn*`, `Future`, `AsyncFnKindHelper`'s associated types

Adds lang items for `AsyncFnOnce::Output`, `AsyncFnOnce::CallOnceFuture`, `AsyncFnMut::CallRefFuture`, and uses them in the new solver. I'm mostly interested in doing this to help accelerate uplifting the new trait solver into a separate crate.

The old solver is kind of spaghetti, so I haven't moved that to use these lang items (i.e. it still uses `item_name`-based comparisons).

update: Also adds lang items for `Future::Output` and `AsyncFnKindHelper::Upvars`.

cc ``@lcnr``
2024-05-30 01:12:37 +02:00
Tobias Bucher
d7680e3556 Elaborate about modifying env vars in multi-threaded programs 2024-05-29 23:42:27 +02:00
Tobias Bucher
8cf4980648 Add note about safety of std::env::set_var on Windows 2024-05-29 23:42:27 +02:00
Tobias Bucher
5d8f9b4dc1 Make std::env::{set_var, remove_var} unsafe in edition 2024
Allow calling these functions without `unsafe` blocks in editions up
until 2021, but don't trigger the `unused_unsafe` lint for `unsafe`
blocks containing these functions.

Fixes #27970.
Fixes #90308.
CC #124866.
2024-05-29 23:42:27 +02:00
Ralf Jung
5c497cb3f0 drop_in_place: weaken the claim of equivalence with drop(ptr.read()) 2024-05-29 21:53:44 +02:00
Michael Goulet
a03ba7fd2d Add lang item for AsyncFnKindHelper::Upvars 2024-05-29 14:28:53 -04:00
Michael Goulet
a9c7e024c0 Add lang item for Future::Output 2024-05-29 14:22:56 -04:00
Michael Goulet
7f11d6f4bf Add lang items for AsyncFn's associated types 2024-05-29 14:09:19 -04:00
Scott McMurray
0d63e6b608 [ACP 362] genericize ptr::from_raw_parts 2024-05-29 09:34:16 -07:00
Markus Mayer
54bb08d538
Add FRAC_1_SQRT_2PI doc alias to FRAC_1_SQRT_TAU
This is create symmetry between the already existing TAU constant (2pi)
and the newly-introduced FRAC_1_SQRT_2PI, keeping the more common
name while increasing visibility.
2024-05-29 14:58:37 +02:00
Folkert
14c1f740f2
make ptr::rotate smaller when using optimize_for_size
code to reproduce https://github.com/folkertdev/optimize_for_size-slice-rotate

In the example the size of `.text` goes down from 1624 to 276 bytes.
2024-05-29 13:51:55 +02:00
Daria Sukhonina
2892302aef Add safety comment to fix tidy 2024-05-29 12:57:01 +03:00
Daria Sukhonina
7cdd95e1a6 Optimize async drop glue for some old types 2024-05-29 12:56:59 +03:00
Markus Mayer
eb72938049
Add FRAC_1_SQRT_2PI constant to f16/f32/f64/f128 2024-05-29 09:30:28 +02:00
许杰友 Jieyou Xu (Joe)
3cc59aeaae
Rollup merge of #125226 - madsmtm:fix-mac-catalyst-tests, r=workingjubilee
Make more of the test suite run on Mac Catalyst

Combined with https://github.com/rust-lang/rust/pull/125225, the only failing parts of the test suite are in `tests/rustdoc-js`, `tests/rustdoc-js-std` and `tests/debuginfo`. Tested with:
```console
./x test --target=aarch64-apple-ios-macabi library/std
./x test --target=aarch64-apple-ios-macabi --skip=tests/rustdoc-js --skip=tests/rustdoc-js-std --skip=tests/debuginfo tests
```

Will probably put up a PR later to enable _running_ on (not just compiling for) Mac Catalyst in CI, though not sure where exactly I should do so? `src/ci/github-actions/jobs.yml`?

Note that I've deliberately _not_ enabled stack overflow handlers on iOS/tvOS/watchOS/visionOS (see https://github.com/rust-lang/rust/issues/25872), but rather just skipped those tests, as it uses quite a few APIs that I'd be weary about getting rejected by the App Store (note that Swift doesn't do it on those platforms either).

r? ``@workingjubilee``

CC ``@thomcc``

``@rustbot`` label O-ios O-apple
2024-05-29 03:25:08 +01:00
许杰友 Jieyou Xu (Joe)
2d3b1e014b
Rollup merge of #124251 - scottmcm:unop-ptr-metadata, r=oli-obk
Add an intrinsic for `ptr::metadata`

The follow-up to #123840, so we can remove `PtrComponents` and `PtrRepr` from libcore entirely (well, after a bootstrap update).

As discussed in <https://rust-lang.zulipchat.com/#narrow/stream/189540-t-compiler.2Fwg-mir-opt/topic/.60ptr_metadata.60.20in.20MIR/near/435637808>, this introduces `UnOp::PtrMetadata` taking a raw pointer and returning the associated metadata value.

By no longer going through a `union`, this should also help future PRs better optimize pointer operations.

r? ``@oli-obk``
2024-05-29 03:25:07 +01:00
Scott McMurray
7150839552 Add custom mir support for PtrMetadata 2024-05-28 09:28:51 -07:00
Scott McMurray
459ce3f6bb Add an intrinsic for ptr::metadata 2024-05-28 09:28:51 -07:00
Matthias Krüger
faabc74625
Rollup merge of #125637 - nnethercote:rustfmt-fixes, r=GuillaumeGomez
rustfmt fixes

The `rmake.rs` entries in `rustfmt.toml` are causing major problems for `x fmt`. This PR removes them and does some minor related cleanups.

r? ``@GuillaumeGomez``
2024-05-28 18:04:33 +02:00
Mads Marquart
e6b9bb7b72 Make more of the test suite run on Mac Catalyst
This adds the `only-apple`/`ignore-apple` compiletest directive, and
uses that basically everywhere instead of `only-macos`/`ignore-macos`.

Some of the updates in `run-make` are a bit redundant, as they use
`ignore-cross-compile` and won't run on iOS - but using Apple in these
is still more correct, so I've made that change anyhow.
2024-05-28 12:31:33 +02:00
Mads Marquart
37ae2b68b1 Disable stack overflow handler tests on iOS-like platforms 2024-05-28 12:31:12 +02:00
Nicholas Nethercote
f1b0ca08a4 Don't format tests/run-make/*/rmake.rs.
It's reasonable to want to, but in the current implementation this
causes multiple problems.

- All the `rmake.rs` files are formatted every time even when they
  haven't changed. This is because they get whitelisted unconditionally
  in the `OverrideBuilder`, before the changed files get added.

- The way `OverrideBuilder` works, if any files gets whitelisted then no
  unmentioned files will get traversed. This is surprising, and means
  that the `rmake.rs` entries broke the use of explicit paths to `x
  fmt`, and also broke `GITHUB_ACTIONS=true git check --fmt`.

The commit removes the `rmake.rs` entries, fixes the formatting of a
couple of files that were misformatted (not previously caught due to the
`GITHUB_ACTIONS` breakage), and bans `!`-prefixed entries in
`rustfmt.toml` because they cause all these problems.
2024-05-28 19:28:46 +10:00
Jubilee
4aaf9f645e
Rollup merge of #125647 - tspiteri:track-lazy_cell_consume, r=workingjubilee
update tracking issue for lazy_cell_consume

<!--
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>
-->
2024-05-28 02:07:49 -07:00
Jubilee
941bf8bee1
Rollup merge of #125551 - clarfonthey:ip-bits, r=jhpratt
Stabilise `IpvNAddr::{BITS, to_bits, from_bits}` (`ip_bits`)

This completed FCP in #113744. (Closes #113744.)

Stabilises the following APIs:

```rust
impl Ipv4Addr {
    pub const BITS: u32 = 32;
    pub const fn from_bits(bits: u32) -> Ipv4Addr;
    pub const fn to_bits(self) -> u32;
}

impl Ipv6Addr {
    pub const BITS: u32 = 128;
    pub const fn from_bits(bits: u128) -> Ipv4Addr;
    pub const fn to_bits(self) -> u128;
}
```
2024-05-28 02:07:48 -07:00
Trevor Spiteri
402a649e75 update tracking issue for lazy_cell_consume 2024-05-28 11:02:03 +02:00
bors
c0d600385b Auto merge of #125636 - workingjubilee:bump-backtrace-0.3.72, r=workingjubilee
Bump backtrace to 0.3.72

This removes a bunch of dead code, contains critical aarch64-windows fixes, some less-critical windows-in-general improvements, adds visionOS support (and probably improves support for a bunch of Apple platforms...), and harmonizes backtrace's dependencies with rustc/std's.

See https://github.com/rust-lang/backtrace-rs/compare/0.3.71...0.3.72

r? `@ghost`
2024-05-28 04:58:04 +00:00
Jubilee Young
3ec9d8db27 Sync libstd deps with backtrace 2024-05-27 19:53:41 -07:00
Jubilee Young
00b759530e Bump backtrace to 0.3.72 2024-05-27 19:53:31 -07:00
bors
d86e122941 Auto merge of #125609 - diondokter:opt-size-char-count, r=thomcc
Always use the general case char count with `optimize_for_size`

The faster algo is really expensive, over a kilobyte if the full algo is present in a binary.
With this PR the general case algo is picked always instead of only for small strings.

In a test of mine this change makes the total binary go from 3116 bytes to 2032 bytes in opt-level 3 and from 1652 bytes to 1428 bytes in opt-level z. I've seen it much worse in real application, so the savings (especially on 'z') will be higher in many cases.

This is the second pr of this kind after #125606
2024-05-28 02:47:32 +00:00
Guillaume Gomez
6dddc888fc
Rollup merge of #124870 - Lokathor:update-result-docs, r=dtolnay
Update Result docs to the new guarantees

The `Option` docs already explain the guarantees given in [RFC 3391](https://github.com/rust-lang/rfcs/blob/master/text/3391-result_ffi_guarantees.md), so all that we need is a paragraph saying that some `Result` type combinations will also qualify.

Part of https://github.com/rust-lang/rust/issues/110503
2024-05-27 13:10:33 +02:00
Dion Dokter
05fa647dc7 Always use the general case char count 2024-05-27 12:05:00 +02:00
Dion Dokter
d32d1c1a2e Size optimize int formatting 2024-05-27 11:08:21 +02:00
Jubilee
25b079a1cf
Rollup merge of #125559 - scottmcm:simplify-shift-ubcheck, r=workingjubilee
Simplify the `unchecked_sh[lr]` ub-checks a bit

It can use the constant in the check, rather than passing it as a parameter.
2024-05-26 15:28:28 -07:00
bors
b0925697fd Auto merge of #122079 - tbu-:pr_copy_file_range_probe, r=the8472
Less syscalls for the `copy_file_range` probe

If it's obvious from the actual syscall results themselves that the syscall is supported or unsupported, don't do an extra syscall with an invalid file descriptor.

CC #122052
2024-05-26 15:48:29 +00:00
David Carlier
073e5d4a2a std::pal::unix::thread fetching min stack size on netbsd.
PTHREAD_STACK_MIN is not defined however sysconf/_SC_THREAD_STACK_MIN
returns it as it can vary from arch to another.
2024-05-26 14:35:26 +00:00
bors
785eb65377 Auto merge of #125574 - matthiaskrgr:rollup-1oljoup, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #125307 (tidy: stop special-casing tests/ui entry limit)
 - #125375 (Create a triagebot ping group for Rust for Linux)
 - #125473 (fix(opt-dist): respect existing config.toml)
 - #125508 (Stop SRoA'ing `DynMetadata` in MIR)
 - #125561 (Stabilize `slice_flatten`)
 - #125571 (f32: use constants instead of reassigning a dummy value as PI)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-26 13:09:58 +00:00
Matthias Krüger
27cdb36ec5
Rollup merge of #125571 - tesuji:dummy-pi, r=Nilstrieb
f32: use constants instead of reassigning a dummy value as PI
2024-05-26 13:43:08 +02: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
bors
a6a017d3f3 Auto merge of #125570 - tesuji:stdout-handle, r=Nilstrieb
Use STD_OUTPUT_HANDLE instead of magic number
2024-05-26 10:57:58 +00:00
Lzu Tao
96a731e5b8 f32: use constants instead of reassigning a dummy value as PI 2024-05-26 09:32:39 +00:00
Lzu Tao
b06b122d8c use proper name instead of magic number 2024-05-26 09:19:18 +00:00
Cyborus
824ffd29ee
Stabilize slice_flatten 2024-05-26 01:26:24 -04:00
bors
bd184cc3e1 Auto merge of #125070 - tbu-:pr_set_extension_panic, r=jhpratt
Panic if `PathBuf::set_extension` would add a path separator

This is likely never intended and potentially a security vulnerability if it happens.

I'd guess that it's mostly literal strings that are passed to this function in practice, so I'm guessing this doesn't break anyone.

CC #125060
2024-05-26 04:14:32 +00:00
bors
75e2c5dcd0 Auto merge of #125518 - saethlin:check-arguments-new-in-const, r=joboet
Move the checks for Arguments constructors to inline const

Thanks `@Skgland` for pointing out this opportunity: https://github.com/rust-lang/rust/pull/117804#discussion_r1612964362
2024-05-26 01:10:39 +00:00
Lokathor
9b480da367 It seems that anchor names are implicitly all lowercase 2024-05-25 17:44:48 -06:00
Scott McMurray
0c84361342 Simplify the unchecked_sh[lr] ub-checks a bit 2024-05-25 15:58:26 -07:00
Lokathor
f8279b10c3 Fix URL target, it's in the module not the type. 2024-05-25 16:46:58 -06:00
Lokathor
2b2f83e5ff github showed that weird. 2024-05-25 16:05:22 -06:00
Lokathor
2e8f14fb37 correct for copy paste errors when fixing wrapping. 2024-05-25 16:04:26 -06:00
Lokathor
22668e83f6 Resolve https://github.com/rust-lang/rust/pull/124870#issuecomment-2128824959 2024-05-25 15:46:55 -06:00
Lokathor
939f2671a0 revert to the inconsistent paragraph wrapping. 2024-05-25 15:41:18 -06:00
Matthias Krüger
80aea305d3
Rollup merge of #124667 - newpavlov:stabilize_div_duration, r=jhpratt
Stabilize `div_duration`

Closes #63139
2024-05-25 22:15:18 +02: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
Matthias Krüger
2a1b63251a
Rollup merge of #122986 - taiki-e:aix-c-char, r=Mark-Simulacrum
Fix c_char on AIX

Closes https://github.com/rust-lang/rust/issues/122985
2024-05-25 22:15:16 +02:00
Matthias Krüger
890982e47b
Rollup merge of #121377 - pitaj:lazy_cell_fn_pointer, r=dtolnay
Stabilize `LazyCell` and `LazyLock`

Closes #109736

This stabilizes the [`LazyLock`](https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html) and [`LazyCell`](https://doc.rust-lang.org/stable/std/cell/struct.LazyCell.html) types:

```rust
static HASHMAP: LazyLock<HashMap<i32, String>> = LazyLock::new(|| {
    println!("initializing");
    let mut m = HashMap::new();
    m.insert(13, "Spica".to_string());
    m.insert(74, "Hoyten".to_string());
    m
});

let lazy: LazyCell<i32> = LazyCell::new(|| {
    println!("initializing");
    92
});
```

r? libs-api
2024-05-25 22:15:16 +02:00
ltdk
0d42cf7afe Stabilise ip_bits feature 2024-05-25 15:00:59 -04:00
bors
48f00110d0 Auto merge of #121571 - clarfonthey:unchecked-math-preconditions, r=saethlin
Add assert_unsafe_precondition to unchecked_{add,sub,neg,mul,shl,shr} methods

(Old PR is haunted, opening a new one. See #117494 for previous discussion.)

This ensures that these preconditions are actually checked in debug mode, and hopefully should let people know if they messed up. I've also replaced the calls (I could find) in the code that use these intrinsics directly with those that use these methods, so that the asserts actually apply.

More discussions on people misusing these methods in the tracking issue: https://github.com/rust-lang/rust/issues/85122.
2024-05-25 18:07:32 +00:00
Matthias Krüger
1d54ba8402
Rollup merge of #125527 - programmerjake:patch-2, r=workingjubilee
Add manual Sync impl for ReentrantLockGuard

Fixes: #125526
Tracking Issue: #121440

this impl is even shown in the summary in the tracking issue, but apparently was forgotten in the actual implementation
2024-05-25 12:54:38 +02:00
Matthias Krüger
4d13c96c65
Rollup merge of #125498 - zmodem:avx512er, r=workingjubilee
Stop using the avx512er and avx512pf x86 target features

They are no longer supported by LLVM 19.

Fixes #125492
2024-05-25 12:54:35 +02:00
Matthias Krüger
e58a0a8961
Rollup merge of #125478 - Urgau:check-cfg-config-bump-stage0, r=Mark-Simulacrum
Bump bootstrap compiler to the latest beta compiler

This PR updates the bootstrap compiler, aka stage0 to the latest beta version, since it contains rust-lang/cargo#13925.

It removes those unconditional Cargo warnings:

```
warning: [...]/rust/library/core/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
warning: [...]/rust/library/std/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
warning: [...]/rust/library/alloc/Cargo.toml: unused manifest key: lints.rust.unexpected_cfgs.check-cfg
```

for all contributors/users of this repository (including CI).

I don't know if that's something we do, or if it's even advisable, feel free to close.

r? `@Mark-Simulacrum`
2024-05-25 12:54:35 +02:00
Matthias Krüger
f28d36899c
Rollup merge of #125271 - RalfJung:posix_memalign, r=workingjubilee
use posix_memalign on almost all Unix targets

Seems nice to be able to use a single common codepath for all of them. :) The `libc` crate says this symbol exists for all Unix targets. I did locally do check-builds to ensure this still builds, but I can't really test more than that.

- For redox, I found indications posix_memalign really exists [here](https://gitlab.redox-os.org/redox-os/relibc/-/merge_requests/271)
- For esp-idf, I found indications [here](c5b297a86f)
- ~~For horizon and vita (these seem to be gaming console OSes? "Horizon OS" also has some hits for a Facebook product but that seems unrelated), they seem to be based on "newlib", where posix_memalign [seems to exist](https://sourceware.org/git/?p=newlib-cygwin.git;a=commitdiff;h=3ba2c39fb2a12cd7332ef16b1b3e3df994f7c6f5).~~ Turns out no, this 20-year-old standard POSIX function is unfortunately [not supported](https://github.com/rust-lang/rust/pull/125271#issuecomment-2119221419) here.
2024-05-25 12:54:34 +02:00
Ben Kimock
9763222f59 Move the checks for Arguments constructors to inline const 2024-05-24 21:09:15 -04:00
Jacob Lifshay
f4b9ac68f3
Add manual Sync impl for ReentrantLockGuard
Fixes: #125526
2024-05-24 17:44:37 -07:00
joboet
1052d2931c
std: make TLS accessors closures that return pointers 2024-05-25 00:19:47 +02:00
Matthias Krüger
363fbb967e
Rollup merge of #125497 - meesfrensel:patch-1, r=calebzulawski
Fix some SIMD intrinsics documentation

Spotted some mistakes in the docs of some SIMD intrinsics.
2024-05-24 23:01:10 +02:00
bors
697ac29a80 Auto merge of #125499 - matthiaskrgr:rollup-84i5z5w, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #125455 (Make `clamp` inline)
 - #125477 (Run rustfmt on files that need it.)
 - #125481 (Fix the dead link in the bootstrap README)
 - #125482 (Notify kobzol after changes to `opt-dist`)
 - #125489 (Revert problematic opaque type change)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-24 18:53:03 +00:00
Hans Wennborg
3fe3157858 Stop using the avx512er and avx512pf x86 target features
They are no longer supported by LLVM 19.

Fixes #125492
2024-05-24 20:12:42 +02:00
Mahmoud Al-Qudsi
65dffc1990 Change pedantically incorrect OnceCell/OnceLock wording
While the semantic intent of a OnceCell/OnceLock is that it can only be written
to once (upon init), the fact of the matter is that both these types offer a
`take(&mut self) -> Option<T>` mechanism that, when successful, resets the cell
to its initial state, thereby technically allowing it to be written to again.

Despite the fact that this can only happen with a mutable reference (generally
only used during the construction of the OnceCell/OnceLock), it would be
incorrect to say that the type itself as a whole categorically prevents being
initialized or written to more than once (since it is possible to imagine an
identical type only without the `take()` method that actually fulfills that
contract).

To clarify, change "that cannot be.." to "that nominally cannot.." and add a
note to OnceCell about what can be done with an `&mut Self` reference.
2024-05-24 12:15:06 -05:00
Matthias Krüger
eb6297eb6f
Rollup merge of #125477 - nnethercote:missed-rustfmt, r=compiler-errors
Run rustfmt on files that need it.

Somehow these files aren't properly formatted. By default `x fmt` and `x tidy` only check files that have changed against master, so if an ill-formatted file somehow slips in it can stay that way as long as it doesn't get modified(?)

I found these when I ran `x fmt` explicitly on every `.rs` file in the repo, while working on
https://github.com/rust-lang/compiler-team/issues/750.
2024-05-24 17:48:03 +02:00
Matthias Krüger
268657b40b
Rollup merge of #125455 - blyxyas:opt-clamp, r=joboet
Make `clamp` inline

Context: rust-lang/rust-clippy#12826
This results in slightly more optimized assembly. (And most important, it's now less than lines than just manually clamping a value)
2024-05-24 17:48:02 +02:00
Mees Frensel
a85f6a6640
Fix some SIMD intrinsics documentation 2024-05-24 17:34:12 +02:00
bors
9e297bf54d Auto merge of #122494 - joboet:simplify_key_tls, r=m-ou-se
Simplify key-based thread locals

This PR simplifies key-based thread-locals by:
* unifying the macro expansion of `const` and non-`const` initializers
* reducing the amount of code in the expansion
* simply reallocating on recursive initialization instead of going through `LazyKeyInner`
* replacing `catch_unwind` with the shared `abort_on_dtor_unwind`

It does not change the initialization behaviour described in #110897.
2024-05-24 15:34:07 +00:00
bors
213ad10c8f Auto merge of #121150 - Swatinem:debug-ascii-str, r=joboet
Add a fast-path to `Debug` ASCII `&str`

Instead of going through the `EscapeDebug` machinery, we can just skip over ASCII chars that don’t need any escaping.

---

This is an alternative / a companion to https://github.com/rust-lang/rust/pull/121138.

The other PR is adding the fast path deep within `EscapeDebug`, whereas this skips as early as possible.
2024-05-24 12:23:00 +00:00
joboet
0e7e75ebca
std: clean up the TLS implementation 2024-05-24 12:28:05 +02:00
joboet
5f0531da05
std: simplify key-based thread locals 2024-05-24 11:36:50 +02:00
bors
464987730a Auto merge of #125479 - scottmcm:validate-vtable-projections, r=Nilstrieb
Validate the special layout restriction on `DynMetadata`

If you look at <https://stdrs.dev/nightly/x86_64-unknown-linux-gnu/std/ptr/struct.DynMetadata.html>, you'd think that `DynMetadata` is a struct with fields.

But it's actually not, because the lang item is special-cased in rustc_middle layout:

7601adcc76/compiler/rustc_middle/src/ty/layout.rs (L861-L864)

That explains the very confusing codegen ICEs I was getting in https://github.com/rust-lang/rust/pull/124251#issuecomment-2128543265

> Tried to extract_field 0 from primitive OperandRef(Immediate((ptr:  %5 = load ptr, ptr %4, align 8, !nonnull !3, !align !5, !noundef !3)) @ TyAndLayout { ty: DynMetadata<dyn Callsite>, layout: Layout { size: Size(8 bytes), align: AbiAndPrefAlign { abi: Align(8 bytes), pref: Align(8 bytes) }, abi: Scalar(Initialized { value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), fields: Primitive, largest_niche: Some(Niche { offset: Size(0 bytes), value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), variants: Single { index: 0 }, max_repr_align: None, unadjusted_abi_align: Align(8 bytes) } })

because there was a `Field` projection despite the layout clearly saying it's [`Primitive`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_target/abi/enum.FieldsShape.html#variant.Primitive).

Thus this PR updates the MIR validator to check for such a projection, and changes `libcore` to not ever emit any projections into `DynMetadata`, just to transmute the whole thing when it wants a pointer.
2024-05-24 08:53:27 +00:00
Scott McMurray
d83f3ca8ca Validate the special layout restriction on DynMetadata 2024-05-23 23:38:44 -07:00
Urgau
02eada8f8d Remove now outdated comment since we bumped stage0 2024-05-24 08:08:41 +02:00
Nicholas Nethercote
c1ac4a2f28 Run rustfmt on files that need it.
Somehow these files aren't properly formatted. By default `x fmt` and `x
tidy` only check files that have changed against master, so if an
ill-formatted file somehow slips in it can stay that way as long as it
doesn't get modified(?)

I found these when I ran `x fmt` explicitly on every `.rs` file in the
repo, while working on
https://github.com/rust-lang/compiler-team/issues/750.
2024-05-24 15:17:21 +10:00
bors
7601adcc76 Auto merge of #125463 - GuillaumeGomez:rollup-287wx4y, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #125263 (rust-lld: fallback to rustc's sysroot if there's no path to the linker in the target sysroot)
 - #125345 (rustc_codegen_llvm: add support for writing summary bitcode)
 - #125362 (Actually use TAIT instead of emulating it)
 - #125412 (Don't suggest adding the unexpected cfgs to the build-script it-self)
 - #125445 (Migrate `run-make/rustdoc-with-short-out-dir-option` to `rmake.rs`)
 - #125452 (Cleanup check-cfg handling in core and std)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-24 03:04:06 +00:00
ltdk
72b7171031 Add assert_unsafe_precondition to unchecked_{add,sub,neg,mul,shl,shr} methods 2024-05-23 21:02:31 -04:00
bors
78dd504f2f Auto merge of #123724 - joboet:static_tls, r=m-ou-se
Rewrite TLS on platforms without threads

The saga of #110897 continues!

r? `@m-ou-se` if you have time
2024-05-24 00:56:29 +00:00
Guillaume Gomez
a8a71d093e
Rollup merge of #125452 - Urgau:check-cfg-libraries-cleanup, r=bjorn3
Cleanup check-cfg handling in core and std

Follow-up to https://github.com/rust-lang/rust/pull/125296 where we:
 - expect any feature cfg in std, due to `#[path]` imports
 - move some check-cfg args inside the `build.rs` as per Cargo recommendation
 - and replace the fake Cargo feature `"restricted-std"` by the custom cfg `restricted_std`

Fixes https://github.com/rust-lang/rust/pull/125296#issuecomment-2127009301
r? `@bjorn3` (maybe, feel free to re-roll)
2024-05-23 23:39:29 +02:00
Guillaume Gomez
1e4bde1cb9
Rollup merge of #125362 - joboet:tait_hack, r=Nilstrieb
Actually use TAIT instead of emulating it

`core`'s `impl_fn_for_zst` macro is just a hacky way of emulating TAIT. TAIT has become stable enough to be used [in other places](e8fbd99128/library/std/src/backtrace.rs (L431)) inside the standard library, so let's use it in `core` as well.
2024-05-23 23:39:27 +02:00
bors
5baee04b63 Auto merge of #125456 - fmease:rollup-n8608gc, r=fmease
Rollup of 7 pull requests

Successful merges:

 - #122382 (Detect unused structs which implement private traits)
 - #124389 (Add a warning to proc_macro::Delimiter::None that rustc currently does not respect it.)
 - #125224 (Migrate `run-make/issue-53964` to `rmake`)
 - #125227 (Migrate `run-make/issue-30063` to `rmake`)
 - #125336 (Add dedicated definition for intrinsics)
 - #125401 (Migrate `run-make/rustdoc-scrape-examples-macros` to `rmake.rs`)
 - #125454 (Improve the doc of query associated_item)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-23 19:27:20 +00:00
Arpad Borsos
004100c222
Process a single not-ASCII-printable char per iteration
This avoids having to collect a non-ASCII-printable run before processing it.
2024-05-23 21:12:08 +02:00
León Orell Valerian Liehr
f862f6d292
Rollup merge of #124389 - CensoredUsername:master, r=petrochenkov
Add a warning to proc_macro::Delimiter::None that rustc currently does not respect it.

It does not provide the behaviour it is indicated to provide when used in a proc_macro context.

This seems to be a bug, (https://github.com/rust-lang/rust/issues/67062), but it is a long standing one, and hard to discover.

This pull request adds a warning to inform users of this issue, with a link to the relevant issue, and a version number of the last known affected rustc version.
2024-05-23 20:09:08 +02:00
bors
606afbb617 Auto merge of #117804 - saethlin:no-recursive-panics, r=joboet
Panic directly in Arguments::new* instead of recursing

This has been bothering me because it looks very silly in MIR.
2024-05-23 17:11:11 +00:00
blyxyas
d6e6918857 Make clamp inline 2024-05-23 18:45:03 +02:00
Urgau
45ad60d05a Copy core/alloc check-cfg message also in std 2024-05-23 16:08:34 +02:00
Urgau
28689850e5 Move some expected cfgs to std build.rs as per Cargo recommandation 2024-05-23 16:08:31 +02:00
Urgau
a59589b1cc Replace fake "restricted-std" Cargo feature by custom cfg 2024-05-23 15:54:02 +02:00
Ben Kimock
75f3cef756 panic_nounwind in Arguments::new* instead of recursing 2024-05-23 09:21:21 -04:00
Urgau
324b66c553 Expect any feature cfg in core and std crates 2024-05-23 15:20:25 +02:00
joboet
085b3d49c9
std: rewrite native thread-local storage 2024-05-23 13:44:55 +02:00
joboet
c398b2c193
core: use Copy in TAIT to fix clippy lint 2024-05-23 13:38:52 +02:00
Matthias Krüger
5126d4b87b
Rollup merge of #125392 - workingjubilee:unwind-a-problem-in-context, r=Amanieu
Wrap Context.ext in AssertUnwindSafe

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

Alternative to https://github.com/rust-lang/rust/pull/125377

Relevant to https://github.com/rust-lang/rust/issues/123392

I believe this approach is justifiable due to the fact that this function is unstable API and we have been considering trying to dispose of the notion of "unwind safety". Making a more long-term decision should be considered carefully as part of stabilizing `fn ext`, if ever.

r? `@Amanieu`
2024-05-23 07:41:19 +02:00
Matthias Krüger
4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`

```rs
fn main() {
    // Current lints
    for _ in Some(42) {}
    for _ in Ok::<_, i32>(42) {}

    // New lints
    for _ in &Some(42) {}
    for _ in &mut Some(42) {}
    for _ in &Ok::<_, i32>(42) {}
    for _ in &mut Ok::<_, i32>(42) {}

    // Should not lint
    for _ in Some(42).into_iter() {}
    for _ in Some(42).iter() {}
    for _ in Some(42).iter_mut() {}
    for _ in Ok::<_, i32>(42).into_iter() {}
    for _ in Ok::<_, i32>(42).iter() {}
    for _ in Ok::<_, i32>(42).iter_mut() {}
}
```

<details><summary><code>cargo build</code> diff</summary>

```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
 warning: for loop over an `Option`. This is more readably written as an `if let` statement
  --> src/main.rs:3:14
   |
 3 |     for _ in Some(42) {}
   |              ^^^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
 help: to check pattern in a loop use `while let`
   |
 3 |     while let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 3 |     if let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~ ~~~

 warning: for loop over a `Result`. This is more readably written as an `if let` statement
  --> src/main.rs:4:14
   |
 4 |     for _ in Ok::<_, i32>(42) {}
   |              ^^^^^^^^^^^^^^^^
   |
 help: to check pattern in a loop use `while let`
   |
 4 |     while let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 4 |     if let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~ ~~~

-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
-    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+  |
+7 |     for _ in &Some(42) {}
+  |              ^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+7 |     while let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+7 |     if let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+  |
+8 |     for _ in &mut Some(42) {}
+  |              ^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+8 |     while let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+8 |     if let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+  |
+9 |     for _ in &Ok::<_, i32>(42) {}
+  |              ^^^^^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+9 |     while let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+9 |     if let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+  --> src/main.rs:10:14
+   |
+10 |     for _ in &mut Ok::<_, i32>(42) {}
+   |              ^^^^^^^^^^^^^^^^^^^^^
+   |
+help: to check pattern in a loop use `while let`
+   |
+10 |     while let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+   |
+10 |     if let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

```

</details>

-----

Question:

* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
bors
9cdfe285ca Auto merge of #125423 - fmease:rollup-ne4l9y4, r=fmease
Rollup of 7 pull requests

Successful merges:

 - #125043 (reference type safety invariant docs: clarification)
 - #125306 (Force the inner coroutine of an async closure to `move` if the outer closure is `move` and `FnOnce`)
 - #125355 (Use Backtrace::force_capture instead of Backtrace::capture in rustc_log)
 - #125382 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 7))
 - #125391 (Minor serialize/span tweaks)
 - #125395 (Remove unnecessary `.md` from the documentation sidebar)
 - #125399 (Stop using `to_hir_binop` in codegen)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-22 21:51:26 +00:00
León Orell Valerian Liehr
ab9e0a72ef
Rollup merge of #125043 - RalfJung:ref-type-safety-invariant, r=scottmcm
reference type safety invariant docs: clarification

The old text could have been read as saying that you can call a function if these requirements are upheld, which is definitely not true as they are an underapproximation of the actual safety invariant.

I removed the part about functions relaxing the requirements via their documentation... this seems incoherent with saying that it may actually be unsound to ever temporarily violate the requirement. Furthermore, a function *cannot* just relax this for its return value, that would in general be unsound. And the part about "unsafe code in a safe function may assume these invariants are ensured of arguments passed by the caller" also interacts with relaxing things: clearly, if the invariant has been relaxed, unsafe code cannot rely on it any more. There may be a place to give general guidance on what kinds of function contracts can exist, but the reference type is definitely not the right place to write that down.

I also took a clarification from https://github.com/rust-lang/rust/pull/121965 that is orthogonal to the rest of that PR.

Cc ```@joshlf``` ```@scottmcm```
2024-05-22 23:41:11 +02:00
León Orell Valerian Liehr
8219fd2bc1
Rollup merge of #125296 - tesuji:checkcfg-buildstd, r=Nilstrieb,michaelwoerister
Fix `unexpected_cfgs` lint on std

closes #125291

r? rust-lang/compiler
2024-05-22 19:04:45 +02:00
León Orell Valerian Liehr
76d4bfb1c6
Rollup merge of #124896 - RalfJung:miri-intrinsic-fallback, r=oli-obk
miri: rename intrinsic_fallback_checks_ub to intrinsic_fallback_is_spec

Checking UB is not the only concern, we also have to make sure we are not losing out on non-determinism.

r? ``@oli-obk`` (not urgent, take your time)
2024-05-22 19:04:43 +02:00
bors
5d328a1f62 Auto merge of #117329 - RalfJung:offset-by-zero, r=oli-obk,scottmcm
offset: allow zero-byte offset on arbitrary pointers

As per prior `@rust-lang/opsem` [discussion](https://github.com/rust-lang/opsem-team/issues/10) and [FCP](https://github.com/rust-lang/unsafe-code-guidelines/issues/472#issuecomment-1793409130):

- Zero-sized reads and writes are allowed on all sufficiently aligned pointers, including the null pointer
- Inbounds-offset-by-zero is allowed on all pointers, including the null pointer
- `offset_from` on two pointers derived from the same allocation is always allowed when they have the same address

This removes surprising UB (in particular, even C++ allows "nullptr + 0", which we currently disallow), and it brings us one step closer to an important theoretical property for our semantics ("provenance monotonicity": if operations are valid on bytes without provenance, then adding provenance can't make them invalid).

The minimum LLVM we require (v17) includes https://reviews.llvm.org/D154051, so we can finally implement this.

The `offset_from` change is needed to maintain the equivalence with `offset`: if `let ptr2 = ptr1.offset(N)` is well-defined, then `ptr2.offset_from(ptr1)` should be well-defined and return N. Now consider the case where N is 0 and `ptr1` dangles: we want to still allow offset_from here.

I think we should change offset_from further, but that's a separate discussion.

Fixes https://github.com/rust-lang/rust/issues/65108
[Tracking issue](https://github.com/rust-lang/rust/issues/117945) | [T-lang summary](https://github.com/rust-lang/rust/pull/117329#issuecomment-1951981106)

Cc `@nikic`
2024-05-22 13:04:14 +00:00
Jubilee Young
3a21fb5cec Wrap Context.ext in AssertUnwindSafe 2024-05-21 19:05:37 -07:00
Ralf Jung
9526ce60fd improve comment wording 2024-05-21 21:13:20 +02:00
Lzu Tao
df3a32066f tidy alphabetica 2024-05-21 18:17:55 +00:00
Lzu Tao
c7d2f4592f addresss reviews 2024-05-21 18:17:55 +00:00
Lzu Tao
73602bf408 Update check-cfg lists for std 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
Lzu Tao
63fe640f5d Update check-cfg lists for core 2024-05-21 18:17:55 +00:00
joboet
fde4a22da2
core: actually use TAIT instead of emulating it 2024-05-21 15:59:48 +02: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
e6e05d51ec
Rollup merge of #125348 - tbu-:pr_doc_path_absolute, r=jhpratt
Small fixes to `std::path::absolute` docs
2024-05-21 12:47:07 +02:00
Matthias Krüger
fd975f75fa
Rollup merge of #125266 - workingjubilee:stream-plastic-love, r=RalfJung,nikic
compiler: add simd_ctpop intrinsic

Fairly straightforward addition.

cc `@rust-lang/opsem` new (extremely boring) intrinsic
2024-05-21 12:47:06 +02:00
Matthias Krüger
a8ee8d5086
Rollup merge of #125225 - madsmtm:ios-crt_externs.h, r=workingjubilee
Use functions from `crt_externs.h` on iOS/tvOS/watchOS/visionOS

Use `_NSGetEnviron`, `_NSGetArgc` and `_NSGetArgv` on iOS/tvOS/watchOS/visionOS, see each commit and the code comments for details. This allows us to unify more code with the macOS implementation, as well as avoiding linking to the `Foundation` framework (which is good for startup performance).

The biggest problem with doing this would be if it lead to App Store rejections. After doing a bunch of research on this, while [it did happen once in 2009](https://blog.unity.com/engine-platform/unity-app-store-submissions-problem-solved), I find it fairly unlikely to happen nowadays, especially considering that Apple has later _added_ `crt_externs.h` to the iOS/tvOS/watchOS/visionOS SDKs, strongly signifying the functions therein is indeed supported on those platforms (even though they lack an availability attribute).

That we've been overly cautious here has also been noted by `@thomcc` in https://github.com/rust-lang/rust/pull/117910#issuecomment-1903372350.

r? `@workingjubilee`

`@rustbot` label O-apple
2024-05-21 12:47:05 +02: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
bors
e8fbd99128 Auto merge of #124097 - compiler-errors:box-into-iter, r=WaffleLapkin
Add `IntoIterator` for `Box<[T]>` + edition 2024-specific lints

* Adds a similar method probe opt-out mechanism to the `[T;N]: IntoIterator` implementation for edition 2021.
* Adjusts the relevant lints (shadowed `.into_iter()` calls, new source of method ambiguity).
* Adds some tests.
* Took the liberty to rework the logic in the `ARRAY_INTO_ITER` lint, since it was kind of confusing.

Based mostly off of #116607.

ACP: rust-lang/libs-team#263
References #59878
Tracking for Rust 2024: https://github.com/rust-lang/rust/issues/123759

Crater run was done here: https://github.com/rust-lang/rust/pull/116607#issuecomment-1770293013
Consensus afaict was that there is too much breakage, so let's do this in an edition-dependent way much like `[T; N]: IntoIterator`.
2024-05-21 10:13:53 +00:00
Tobias Bucher
6add5c99cd Document behavior of create_dir_all wrt. empty path
The behavior makes sense because `Path::new("one_component").parent() ==
Some(Path::new(""))`, so if one naively wants to create the parent
directory for a file to be written, it simply works.

Closes #105108 by documenting the current behavior.
2024-05-21 07:56:56 +02:00
Michael Goulet
a502e7ac1d Implement BOXED_SLICE_INTO_ITER 2024-05-20 19:21:30 -04: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
73bb47eecd
Rollup merge of #125333 - hermit-os:fuse, r=workingjubilee
switch to the default implementation of `write_vectored`

HermitOS doesn't support write_vectored and switch to the default implementation of `write_vectored`.
2024-05-21 00:47:03 +02:00
Matthias Krüger
62da957c92
Rollup merge of #125123 - a1phyr:fix-read_exact, r=workingjubilee
Fix `read_exact` and `read_buf_exact` for `&[u8]` and `io:Cursor`

- Drain after `read_exact` and `read_buf_exact`
- Append to cursor in `read_buf_exact`
2024-05-21 00:47:01 +02:00
Matthias Krüger
8903de31ca
Rollup merge of #124050 - saethlin:less-sysroot-libc, r=ChrisDenton
Remove libc from MSVC targets

``@ChrisDenton`` started working on a project to remove libc from Windows MSVC targets. I'm completing that work here.

The primary change is to cfg out the dependency in `library/`. And then there's a lot of test patching. Happy to separate this more if people want.
2024-05-21 00:47:00 +02:00
Tobias Bucher
f6cf103da2 Small fixes to std::path::absolute docs 2024-05-21 00:36:52 +02:00
Stefan Lankes
d39dc0ab23 switch also the default implementation for read_vectored 2024-05-20 21:44:04 +02:00
Tobias Bucher
20fd725172 Document platform-specifics for Read and Write of File 2024-05-20 21:21:53 +02:00
Stefan Lankes
c170bf9927 switch to the default implementation of write_vectored 2024-05-20 19:24:11 +02:00
Ben Kimock
aa31281f2d Remove Windows dependency on libc 2024-05-20 11:13:31 -04:00
Benoît du Garreau
a197ff3259 Address review comments 2024-05-20 17:00:11 +02:00
Taiki Endo
c31ec4fb04 Fix c_char on AIX
Refs: https://github.com/rust-lang/rust/issues/122985
2024-05-20 22:46:13 +09: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
Arpad Borsos
aaba972e06
Switch to primarily using &str
Surprisingly, benchmarks have shown that using `&str`
instead of `&[u8]` with some `unsafe` code is actually faster.
2024-05-20 11:31:02 +02:00
Arpad Borsos
42d870ec88
Introduce printable-ASCII fast-path for impl Debug for str
Instead of having a single loop that works on utf-8 `char`s,
this splits the implementation into a loop that quickly skips over
printable ASCII, falling back to per-char iteration for other chunks.
2024-05-20 11:10:38 +02:00
Arpad Borsos
3fda931afe
Add a fast-path to Debug ASCII &str
Instead of going through the `EscapeDebug` machinery, we can just skip over ASCII chars that don’t need any escaping.
2024-05-20 10:04:45 +02:00
Arpad Borsos
0334c45bb5
Write char::DebugEscape sequences using write_str
Instead of writing each `char` of an escape sequence one by one,
this delegates to `Display`, which uses `write_str` internally
in order to write the whole escape sequence at once.
2024-05-20 10:04:44 +02:00
bors
e8ada6ab25 Auto merge of #125313 - matthiaskrgr:rollup-65etxv0, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #125034 (Weekly `cargo update`)
 - #125093 (Add `fn into_raw_with_allocator` to Rc/Arc/Weak.)
 - #125282 (Never type unsafe lint improvements)
 - #125301 (fix suggestion in E0373 for !Unpin coroutines)
 - #125302 (defrost `RUST_MIN_STACK=ice rustc hello.rs`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-20 07:58:40 +00: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
f092f73c11 Auto merge of #124560 - madsmtm:update-libc, r=Mark-Simulacrum
Update libc to 0.2.155

Motivation: To fix `-Zbuild-std` / Xargo for visionOS targets.

EDIT: Blocked on ~https://github.com/rust-lang/libc/issues/3608 / https://github.com/rust-lang/libc/pull/3609~ ~https://github.com/rust-lang/libc/pull/3682 and https://github.com/rust-lang/libc/pull/3690~ No longer blocked.
2024-05-20 05:50:24 +00:00
Mads Marquart
38ad851603 Make NULL check in argument parsing the same on all unix platforms 2024-05-20 04:54:27 +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
Matthias Krüger
c5b8c7c3b0
Rollup merge of #124992 - foresterre:example/is-terminal, r=ChrisDenton
Add example to IsTerminal::is_terminal
2024-05-19 22:50:55 +02:00
Matthias Krüger
d5bef41ee5
Rollup merge of #124948 - blyxyas:remove-repeated-words, r=compiler-errors
chore: Remove repeated words (extension of #124924)

When I saw #124924 I thought "Hey, I'm sure that there are far more than just two typos of this nature in the codebase". So here's some more typo-fixing.

Some found with regex, some found with a spellchecker. Every single one manually reviewed by me (along with hundreds of false negatives by the tools)
2024-05-19 22:50:55 +02:00
Ralf Jung
3c2d9c2dbe
fix typo
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2024-05-19 20:40:46 +02: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
Martijn
0b6baf6130 Add example to IsTerminal::is_terminal 2024-05-19 20:00:02 +02:00
bors
959a67a7f2 Auto merge of #123786 - a1phyr:cursor_unsafe, r=joboet
Remove bound checks from `BorrowedBuf` and `BorrowedCursor` methods
2024-05-19 17:16:12 +00: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
Michael Goulet
edace328b8
Rollup merge of #125252 - beetrees:patch-1, r=joboet
Add `#[inline]` to float `Debug` fallback used by `cfg(no_fp_fmt_parse)`

Fixes #125229.
2024-05-19 11:04:08 -04:00
Michael Goulet
f848505c40
Rollup merge of #124304 - hermit-os:fuse, r=joboet
revise the interpretation of ReadDir for HermitOS

HermitOS supports getdents64. As under Linux, the dirent64 entry `d_off` is not longer used, because its definition is not clear. Instead of `d_off` the entry `d_reclen` is used to determine the end of the dirent64 entry.

In addition, take up `@workingjubilee`  suggestion from the discussions in rust-lang/rust#115984 to increase the readability.

Hermit is a tier 3 platform and this PR changes only files, wich are related to the tier 3 platform.
2024-05-19 11:04:07 -04:00
Michael Goulet
0f923a48c5
Rollup merge of #123709 - tgross35:windows-cmd-docs-update, r=ChrisDenton
Update documentation related to the recent cmd.exe fix

Fix some grammar nits, change `bat` (extension) -> `batch` (file), and make line wrapping more consistent.
2024-05-19 11:04:07 -04:00
Ralf Jung
e7772f2088 use posix_memalign on most Unix targets 2024-05-19 14:58:48 +02: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
Mads Marquart
abd5d0e37b Add NULL check in argument parsing on Apple platforms 2024-05-19 04:19:15 +02: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
Jubilee Young
1914c722b5 compiler: add simd_ctpop intrinsic 2024-05-18 18:11:20 -07: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
许杰友 Jieyou Xu (Joe)
c367d99259
Rollup merge of #125251 - jonhoo:patch-1, r=Nilstrieb
Clarify how String::leak and into_boxed_str differ
2024-05-18 20:38:05 +01:00
Jon Gjengset
0beba9699c Clarify how String::leak and into_boxed_str differ 2024-05-18 19:17:43 +02:00
blyxyas
c5c820e7fb Fix typos (taking into account review comments) 2024-05-18 18:12:18 +02:00
beetrees
827711d087
Add #[inline] to float Debug fallback used by cfg(no_fp_fmt_parse) 2024-05-18 16:25:55 +01:00
Ralf Jung
dde1134c6d android: use posix_memalign for aligned allocations 2024-05-18 12:49:01 +02:00
CensoredUsername
c2d2df182a Add a warning to Delimiter::None that rustc currently does not respect it.
It does not provide the behaviour it is indicated to provide when used in
a proc_macro context.
2024-05-18 01:41:45 +02:00
Noa
53b317710d
Inline Duration construction into Duration::from_{millis,micros,nanos} 2024-05-17 18:37:59 -05:00
Mads Marquart
74012d5200 Update libc to 0.2.155 2024-05-18 00:48:57 +02:00
Mads Marquart
8f18e4fe4b Use _NSGetArgc/_NSGetArgv on iOS/tvOS/watchOS/visionOS
If we're comfortable using `_NSGetEnviron` from `crt_externs.h`, there shouldn't be an issue with using these either, and then we can merge with the macOS implementation.

This also fixes two test cases on Mac Catalyst:
- `tests/ui/command/command-argv0.rs`, maybe because `[[NSProcessInfo processInfo] arguments]` somehow converts the name of the first argument?
- `tests/ui/env-funky-keys.rs` since we no longer link to Foundation.
2024-05-17 22:11:51 +02:00
Mads Marquart
6016bad063 Use _NSGetEnviron instead of environ on iOS/tvOS/watchOS/visionOS
This should be slightly more correct, and matches the implementation in other programming languages:
- [Python's `os.environ`](https://github.com/python/cpython/blob/v3.12.3/Modules/posixmodule.c#L1562-L1566).
- [Swift's `Darwin.environ`](https://github.com/apple/swift-corelibs-foundation/blob/swift-5.10-RELEASE/CoreFoundation/Base.subproj/CFPlatform.c#L1811-L1812), though that library is bundled on the system, so they can change it if they want.
- [Dart/Flutter](https://github.com/dart-lang/sdk/blob/3.4.0/runtime/bin/platform_macos.cc#L205-L234), doesn't support environment variables on iOS.
- Node seems to not be entirely consistent with it:
  - [`process.c`](https://github.com/nodejs/node/blob/v22.1.0/deps/uv/src/unix/process.c#L38).
  - [`unix/core.c`](https://github.com/nodejs/node/blob/v22.1.0/deps/uv/src/unix/core.c#L59).
- [.NET/Xamarin](https://github.com/dotnet/runtime/blob/v8.0.5/src/native/libs/configure.cmake#L1099-L1106).
- [OpenJDK](https://github.com/openjdk/jdk/blob/jdk-23%2B22/src/java.base/unix/native/libjava/ProcessEnvironment_md.c#L31-L33).
2024-05-17 22:11:50 +02:00
Noa
35522a9e09
Don't call Duration::new unnecessarily in Duration::from_secs 2024-05-17 14:26:50 -05:00
bors
ddba1dc97e Auto merge of #125188 - tgross35:f16-f128-powi, r=Nilstrieb
Add `powi` fo `f16` and `f128`

This will unblock adding support to compiler_builtins (<https://github.com/rust-lang/compiler-builtins/pull/614>), which will then unblock adding tests for these new functions.
2024-05-17 11:24:07 +00:00
Matthias Krüger
a6862f8612
Rollup merge of #125186 - Colepng:master, r=lqd
Remove duplicate word from addr docs

This PR simply removes a duplicate word from the addr docs for *mut T.
2024-05-17 07:20:58 +02:00
Matthias Krüger
7a8d222d6b
Rollup merge of #125171 - scottmcm:rename-flatten, r=jhpratt
Rename `flatten(_mut)` → `as_flattened(_mut)`

As requested by libs-api in https://github.com/rust-lang/rust/issues/95629#issuecomment-2113081194

(This is just the rename, not the stabilization, so can land without waiting on the FCP in that other issue.)
2024-05-17 07:20:57 +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
bors
8c127df75f Auto merge of #125163 - ssukanmi:stdarch_arm_crc32, r=Amanieu
feat: update stdarch submodule for intrinsics on ARM

Submodule update for stdarch library
10 commits in c0257c1660e78c80ad1b9136fcc5555b14da5b4c..df3618d9f35165f4bc548114e511c49c29e1fd9b
2024-04-22 01:24:03 +0200 to 2024-05-14 15:52:07 +0200
- feat: stabilization for stdarch_aarch64_crc32
- Add vec_insert and vec_extract
- Remove libc dependency on Windows by using Win32 to get env vars
- Add vec_orc
- Simplify vec_andc implementation
- Silence unexpected-cfgs
- Add vec_mul
- Remove `#![feature(inline_const)]`
- Add `#[cfg_attr(miri, ignore)]` to tests of intrinsics that cannot be supported by Miri
- Implement ARM `__ssat` and `__usat` functions

r? Amanieu
2024-05-16 21:17:35 +00:00
Trevor Gross
7685734384 Add powi to f16 and f128
This will unblock adding support to compiler_builtins
(<https://github.com/rust-lang/compiler-builtins/pull/614>), which will
then unblock adding tests for these new functions.
2024-05-16 15:41:06 -05:00
Trevor Gross
a7ca099e03 Add doctests for f16 and f128 library functions where possible 2024-05-16 15:16:42 -05:00
Cole Kauder-McMurrich
d8b9717038
Remove duplicate word from addr docs 2024-05-16 16:16:38 -04:00
bors
2d89cee625 Auto merge of #124728 - beetrees:from-f16-for-f64, r=BurntSushi
Re-add `From<f16> for f64`

This impl was originally added in #122470 before being removed in #123830 due to #123831. However, the issue only affects `f32` (which currently only has one `From<{float}>` impl, `From<f32>`) as `f64` already has two `From<{float}>` impls (`From<f32>` and `From<f64>`) and is also the float literal fallback type anyway. Therefore it is safe to re-add `From<f16> for f64`.

This PR also updates the FIXME link to point to the open issue #123831 rather than the closed issue #123824.

Tracking issue: #116909

`@rustbot` label +F-f16_and_f128 +T-libs-api
2024-05-16 16:48:58 +00:00
Lukas Bergdoll
88fb5edb65 Fix linkchecker doc errors
Also includes small doc fixes.
2024-05-16 17:08:56 +02:00
Lukas Bergdoll
8300f67c6e Turn bare links into automatic links 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
1a6b0e410e Fix tidy errors 2024-05-16 17:08:55 +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
bors
4a78c00e22 Auto merge of #124959 - prorealize:update-result-documentation, r=joboet
Refactor examples and enhance documentation in result.rs

- Replaced `map` with `map_err` in the error handling example for correctness
- Reordered example code to improve readability and logical flow
- Added assertions to examples to demonstrate expected outcomes
2024-05-16 12:21:12 +00:00
Scott McMurray
facc0bb78e Rename flatten(_mut)as_flattened(_mut) 2024-05-15 23:39:33 -07:00
León Orell Valerian Liehr
c5b17ec9d2
Rollup merge of #125003 - RalfJung:aligned_alloc, r=cuviper
avoid using aligned_alloc; posix_memalign is better-behaved

Also there's no reason why wasi should be different than all the other Unixes here.
2024-05-15 22:01:18 +02:00
Olasunkanmi Olayinka
0bf8af69a2 feat: update stdarch submodule for intrinsics on ARM 2024-05-15 15:38:58 -04:00
Zachary S
376a8c0ae5 Allow for_loops_over_fallibles in test that tests &mut Result as IntoIterator. 2024-05-15 13:51:16 -05:00
León Orell Valerian Liehr
4f7d9d4ad8
Rollup merge of #125038 - ivan-shrimp:checked_sub, r=joboet
Invert comparison in `uN::checked_sub`

After #124114, LLVM no longer combines the comparison and subtraction in `uN::checked_sub` when either operand is a constant (demo: https://rust.godbolt.org/z/MaeoYbsP1). The difference is more pronounced when the expression is slightly more complex (https://rust.godbolt.org/z/4rPavsYdc).

This is due to the use of `>=` here:

ee97564e3a/library/core/src/num/uint_macros.rs (L581-L593)

For constant `C`, LLVM eagerly converts `a >= C` into `a > C - 1`, but the backend can only combine `a < C` with `a - C`, not `C - 1 < a` and `a - C`: e586556e37/llvm/lib/CodeGen/CodeGenPrepare.cpp (L1697-L1742)

This PR[^1] simply inverts the `>=` into `<` to restore the LLVM magic, and somewhat align this with the implementation of `uN::overflowing_sub` from #103299.

When the result is stored as an `Option` (rather than being branched/cmoved on), the discriminant is `self >= rhs`. This PR doesn't affect the codegen (and relevant tests) of that since LLVM will negate `self < rhs` to `self >= rhs` when necessary.

[^1]: Note to `self`: My very first contribution to publicly-used code. Hopefully like what I should learn to always be, tiny and humble.
2024-05-15 14:21:38 +02:00
León Orell Valerian Liehr
3873a74f8a
Rollup merge of #124307 - reitermarkus:escape-debug-size-hint-inline, r=joboet
Optimize character escaping.

Allow optimization of panicking branch in `EscapeDebug`, see https://github.com/rust-lang/rust/pull/121805.

r? `@joboet`
2024-05-15 14:21:37 +02:00
Renato A
e1611aa690
Update library/core/src/result.rs
Co-authored-by: joboet <jonasboettiger@icloud.com>
2024-05-15 08:07:16 -03:00
Artyom Pavlov
8da41b107d
Divide float nanoseconds instead of seconds 2024-05-15 00:38:34 +03:00
Ralf Jung
5cc020d3df avoid using aligned_alloc; posix_memalign is better-behaved 2024-05-14 19:32:11 +02:00
Benoît du Garreau
cfb04795a1 Fix read_exact and read_buf_exact for &[u8] and io:Cursor 2024-05-14 16:16:33 +02:00
Jacob Pratt
74a78af0e2
Rollup merge of #116675 - joshlf:patch-10, r=scottmcm
[ptr] Document maximum allocation size

Partially addresses https://github.com/rust-lang/unsafe-code-guidelines/issues/465
2024-05-13 21:14:15 -04: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
Matthias Krüger
b0cbd4e5f3
Rollup merge of #123817 - slanterns:seek_relative, r=dtolnay
Stabilize `seek_seek_relative`

This PR stabilizes `seek_seek_relative`:

```rust
// std::io::Seek

trait Seek {
    fn seek_relative(&mut self, offset: i64) -> Result<()>;
}
```

<br>

Tracking issue: https://github.com/rust-lang/rust/issues/117374.
Implementation PR: https://github.com/rust-lang/rust/pull/116750.

FCPs already completed in the tracking issue.

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

r? libs-api
2024-05-13 20:29:18 +02:00
Joshua Liebow-Feeser
293b5cb1ca [ptr] Document maximum allocation size 2024-05-13 11:14:45 -07:00
Lokathor
b468f21051 Don't use T with both Result and Option, improve explanation. 2024-05-13 10:36:42 -06: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
Tobias Bucher
700b3ea61b Panic if PathBuf::set_extension would add a path separator
This is likely never intended and potentially a security vulnerability
if it happens.

I'd guess that it's mostly literal strings that are passed to this
function in practice, so I'm guessing this doesn't break anyone.

CC #125060
2024-05-13 15:08:34 +02:00
Ralf Jung
5c33a5690d offset, offset_from: allow zero-byte offset on arbitrary pointers 2024-05-13 07:59:16 +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
dde8cfa597 Auto merge of #125045 - GuillaumeGomez:rollup-em6qdzw, r=GuillaumeGomez
Rollup of 4 pull requests

Successful merges:

 - #125021 (Update reference safety requirements)
 - #125022 (Migrate rustdoc scrape examples ordering)
 - #125030 (Fix some minor issues from the ui-test auto-porting)
 - #125036 (solve: all "non-structural" logging to trace)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-05-12 13:33:39 +00:00
Guillaume Gomez
5087947695
Rollup merge of #125021 - joshlf:patch-11, r=RalfJung
Update reference safety requirements

Per https://github.com/rust-lang/rust/pull/116677#issuecomment-1945495786, the language as written promises too much. This PR relaxes the language to be consistent with current semantics. If and when #117945 is implemented, we can revert to the old language.

While we're here, we also require that references be non-null.

cc ``@RalfJung``
2024-05-12 13:41:57 +02:00
bors
b71fa82d78 Auto merge of #124798 - devnexen:illumos_memalign_fix, r=RalfJung
std::alloc: use posix_memalign instead of memalign on solarish

`memalign` on Solarish requires the alignment to be at least the size of a pointer, which we did not honor. `posix_memalign` also requires that, but that code path already takes care of this requirement.

close GH-124787
2024-05-12 11:22:40 +00: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
Ralf Jung
7c76eec30f reference type safety invariant docs: clarification 2024-05-12 10:03:53 +02:00