Commit Graph

12889 Commits

Author SHA1 Message Date
Matthias Krüger
787f1a65df
Rollup merge of #118299 - frewsxcv:patch-2, r=cuviper
Update `OnceLock` documentation to give a concrete 'lazy static' example, and expand on the existing example.
2023-11-28 09:28:37 +01:00
Matthias Krüger
4704d49629
Rollup merge of #118236 - ksw2000:update_mod_comment, r=cuviper
Update mod comment

The comment of `ASCII_CASE_MASK` on line 477  is `If 6th bit is set ascii is lower case.` but the original comment of `*self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)` was `Toggle the fifth bit if this is a lowercase letter`
2023-11-28 09:28:36 +01:00
Matthias Krüger
4af1f99740
Rollup merge of #115331 - the8472:chars_advance, r=cuviper
optimize str::iter::Chars::advance_by

```
OLD:
    str::iter::chars_advance_by_0001  0.00ns/iter  +/- 0.00ns
    str::iter::chars_advance_by_0010 13.00ns/iter  +/- 1.00ns
    str::iter::chars_advance_by_1000  1.20µs/iter +/- 15.00ns

NEW:
    str::iter::chars_advance_by_0001  0.00ns/iter +/- 0.00ns
    str::iter::chars_advance_by_0010  6.00ns/iter +/- 0.00ns
    str::iter::chars_advance_by_1000 75.00ns/iter +/- 1.00ns
```
2023-11-28 09:28:36 +01:00
r0cky
c751bfa015 Add proper cfgs 2023-11-28 09:02:34 +08:00
Zalathar
00d5f18954 Fix comments for unsigned non-zero checked_add, saturating_add
For these two methods, `other` is an ordinary unsigned integer, so it can be zero.

Since the sum of non-zero and zero is always non-zero, the safety argument
holds even when `other` is zero.
2023-11-28 11:52:30 +11:00
The 8472
40cf1f9257 optimize str::iter::Chars::advance_by
this avoids part of the char decoding work by not looking at utf8 continuation bytes
2023-11-27 22:06:35 +01:00
The 8472
3f55e8665c benchmarks for Chars::advance_by 2023-11-27 22:06:35 +01:00
Ralf Jung
8de5bd0f6e use the usual attributes for panic_misaligned_pointer_dereference 2023-11-27 11:10:32 +01:00
Ralf Jung
2a48a7750a make sure panic_nounwind_fmt can still be fully inlined (e.g. for panic_immediate_abort) 2023-11-27 11:07:57 +01:00
bors
a19161043a Auto merge of #118321 - WaffleLapkin:unspace-fn-pointer-fake-variadic, r=notriddle
rustdoc: Remove space from fake-variadic fn ptr impls

before: `for fn (T₁, T₂, …, Tₙ) -> Ret`
after: `for fn(T₁, T₂, …, Tₙ) -> Ret`

I don't think we usually have spaces there, so it looks weird.

cc `@notriddle` since you added the space in https://github.com/rust-lang/rust/pull/98180 (or rather, added the feature with a space included).
2023-11-27 06:16:15 +00:00
DaniPopes
9ae3213fcb
Simplify Default for tuples 2023-11-27 06:11:25 +01:00
bors
601a42713c Auto merge of #118313 - WaffleLapkin:fixup_comments_in_some_nonzero_ops, r=thomcc
Improve some comments for non-zero ops

This makes them a bit more explicit/correct.
2023-11-27 04:18:54 +00:00
bors
1bcbb7c93b Auto merge of #117697 - WaffleLapkin:non-null-convenience-ops, r=Amanieu
Non null convenience ops

Based on https://github.com/rust-lang/libs-team/issues/251.

I went through all of the methods on `*mut` and added every method, which does not require additional safety conditions, to `NonNull`. (exceptions: `guaranteed_eq`, `guaranteed_ne`, `with_metadata_of`, it's unclear if they are useful here...)

I'm also not sure what types should the "second pointer parameter" be. `*mut`/`*const` might be more permissible, but given that `NonNull` doesn't coerce to them, it might also be annoying. For now I chose the "use `NonNull` everywhere" path, but I'm not sure it's the correct one...

<sub>I'm eepy, so I probably messed up somewhere while copying...</sub>

cc `@scottmcm`
r? libs-api
2023-11-26 18:41:55 +00:00
The 8472
bc7dd5fa6d unify read_to_end and io::copy impls for reading into a Vec 2023-11-26 18:13:36 +01:00
Maybe Waffle
e1b4e8a257 Add is_aligned{,_to} convenience methods to NonNull 2023-11-26 16:01:31 +00:00
Maybe Waffle
2bcaa9760e Add align_offset convenience method to NonNull 2023-11-26 16:01:30 +00:00
Maybe Waffle
4cc46df98c Add replace and swap convenience methods to NonNull 2023-11-26 16:01:30 +00:00
Maybe Waffle
4bcdd3bd92 Add offset_from-ish convenience methods to NonNull 2023-11-26 16:01:30 +00:00
Maybe Waffle
ebdc79497f Add offset-ish convenience methods to NonNull 2023-11-26 16:01:30 +00:00
Maybe Waffle
36a587fb62 Add read/write/copy convenience methods to NonNull 2023-11-26 15:57:01 +00:00
Maybe Waffle
1a3c5c40ca rustdoc: Remove space from fake-variadic fn ptr impls
before: `for fn (T₁, T₂, …, Tₙ) -> Ret`
after: `for fn(T₁, T₂, …, Tₙ) -> Ret`
2023-11-26 15:01:42 +00:00
Guillaume Gomez
c67613bef9
Rollup merge of #118302 - mu001999:dead_code/clean, r=cjgillot
Clean dead codes

Clean dead codes detected by #118257
2023-11-26 15:44:54 +01:00
Caleb Zulawski
4d9607869a Update std::simd usage and test outputs 2023-11-26 09:02:25 -05:00
Caleb Zulawski
f0f795d1a8 Use inner docs to fix links 2023-11-26 08:50:47 -05:00
Caleb Zulawski
89b9388af5 Fix library tests 2023-11-26 08:50:39 -05:00
Caleb Zulawski
830b387e17 Merge commit 'e0e9a4517f9fc021283514da387e70a56061bd3e' into sync-portable-simd-2023-11-19 2023-11-26 08:50:06 -05:00
Maybe Waffle
234e9500a4 Use usize::repeat_u8 instead of implementing repeat_byte in memchr.rs 2023-11-26 12:27:56 +00:00
Maybe Waffle
865ab921ab Rename {collections=>alloc}{tests,benches} 2023-11-26 12:04:56 +00:00
Maybe Waffle
c860ba1994 Improve some comments for non-zero ops 2023-11-26 11:47:08 +00:00
bors
9529a5d265 Auto merge of #110303 - nbdd0121:master, r=Mark-Simulacrum
Add `debug_assert_nounwind` and convert `assert_unsafe_precondition`

`assert_unsafe_precondition` checks non-CTFE-evaluable conditions in runtime and performs no-op in compile time, while many of its current usage can be checked during const eval.
2023-11-26 06:44:03 +00:00
r0cky
91aee2de15 Clean dead codes 2023-11-26 09:25:07 +08:00
Gary Guo
81cd49ddde Address review feedback 2023-11-25 23:58:51 +00:00
Gary Guo
97c1502066 Convert many assert_unsafe_precondition to debug_assert_nounwind 2023-11-25 23:58:51 +00:00
Gary Guo
4ccec4558f Add debug_assert_nounwind 2023-11-25 23:58:51 +00:00
Michael Goulet
fcb9fcc28c
Rollup merge of #117968 - Urgau:stabilize-ptr-addr-eq, r=dtolnay
Stabilize `ptr::addr_eq`

This PR stabilize the `ptr_addr_eq` library feature, representing:

```rust
// core::ptr

pub fn addr_eq<T: ?Sized, U: ?Sized>(p: *const T, q: *const U) -> bool;
```

FCP has already started [on the tracking issue](https://github.com/rust-lang/rust/issues/116324#issuecomment-1813008697) and is waiting on the final period comment.

Note: stabilizing this feature is somewhat of requirement for a new T-lang lint, cf. https://github.com/rust-lang/rust/pull/117758#issuecomment-1813183686.
2023-11-25 17:23:33 -05:00
Corey Farwell
a8a5704f1b
Update OnceLock documentation to give a concrete 'lazy static' example, and expand on existing example. 2023-11-25 16:30:43 -05:00
AngelicosPhosphoros
0c6901a487 Add more benchmarks of Vec::dedup
They are for more specific cases than old benches.
Also, better usage of blackbox
2023-11-25 02:08:43 +01:00
bors
37b2813a7b Auto merge of #118138 - Nilstrieb:one-previous-error, r=WaffleLapkin
Fixes error count display is different when there's only one error left

Supersedes #114759

### What did I do?

I did the small change in `rustc_errors` by hand. Then I did the other changes in `/compiler` by hand, those were just find replace on `*.rs` in the workspace. The changes in run-make are find replace for `run-make` in the workspace.

All other changes are blessed using `x test TEST --bless`. I blessed the tests that were blessed in #114759.

### how to review this nightmare

ping bors with an `r+`. You should check that my logic is sound and maybe quickly scroll through the diff, but fully verifying it seems fairly hard to impossible. I did my best to do this correctly.

Thank you `@adrianEffe` for bringing this up and your initial implementation.

cc `@flip1995,` you said you want to do a subtree sync asap
cc `@RalfJung` maybe you want to do a quick subtree sync afterwards as well for Miri

r? `@WaffleLapkin`
2023-11-24 21:40:54 +00:00
Ralf Jung
73042206dd remove the memcpy-on-equal-ptrs assumption 2023-11-24 21:32:16 +01:00
Nilstrieb
41e8d152dc Show number in error message even for one error
Co-authored-by: Adrian <adrian.iosdev@gmail.com>
2023-11-24 19:15:52 +01:00
Michael Goulet
9c1b029559
Rollup merge of #118238 - RalfJung:memcpy, r=Mark-Simulacrum
memcpy assumptions: update GCC link

GCC now has this documented on an official website, not just in the bugtracker.
2023-11-24 07:29:12 -08:00
bors
b06258cde4 Auto merge of #118228 - Mark-Simulacrum:alloc-opt, r=scottmcm
Indicate that multiplication in Layout::array cannot overflow

Since https://github.com/rust-lang/rust/pull/113113, we have added a check that skips calling into the allocator at all if `capacity == 0`. The global, default allocator will not actually try to allocate though; it returns a dangling pointer explicitly. However, these two checks are not merged/deduplicated by LLVM and so we're comparing to zero twice whenever vectors are allocated/grown. Probably cheap, but also potentially expensive in code size and seems like an unfortunate miss.

This removes that extra check by telling LLVM that the multiplication as part of Layout::array can't overflow, turning the original non-zero value into a zero value afterwards. In my checks locally this successfully drops the duplicate comparisons.

See https://rust.godbolt.org/z/b6nPP9dcK for a code example.

```rust
pub fn foo(elements: usize) -> Vec<u32> {
    Vec::with_capacity(elements)
}
```

r? `@scottmcm` since you touched this in a32305a80f - curious if you have thoughts on doing this / can confirm my model of this being correct.
2023-11-24 11:19:34 +00:00
Ralf Jung
a5dff378f5 memcpy assumptions: update GCC link 2023-11-24 11:15:53 +01:00
Kashiwa
1928d82385 correct grammar 2023-11-24 17:23:49 +08:00
bors
f74f700952 Auto merge of #118232 - matthiaskrgr:rollup-x8crvm0, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #116807 (Improve rewind documentation)
 - #117656 (Update windows-bindgen and define `INVALID_HANDLE_VALUE` ourselves)
 - #117940 (chore: remove unnecessary drop)
 - #118028 (Document behavior of `<dyn Any as Any>::type_id()`)
 - #118060 (Use an absolute path to the NUL device)
 - #118224 (Sort unstable items last in rustdoc, instead of first)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-24 09:21:23 +00:00
Kashiwa
e9f628e109 Update comment for consistent context logic. 2023-11-24 17:18:44 +08:00
Ralf Jung
a8162673e3 also add is_empty to const raw slices 2023-11-24 08:25:01 +01:00
Matthias Krüger
b2d6480f53
Rollup merge of #118060 - ChrisDenton:abs-device-path, r=thomcc
Use an absolute path to the NUL device

While a bare "NUL" *should* be redirected to the NUL device, especially in this simple case, let's be explicit that we aren't opening a file called "NUL" and instead open it directly.

This will also set a good example for people copying std code.

r? libs
2023-11-24 08:23:53 +01:00
Matthias Krüger
c3216e2a3a
Rollup merge of #118028 - Jules-Bertholet:dyn-any-doc, r=thomcc
Document behavior of `<dyn Any as Any>::type_id()`

See also #57893

`@rustbot` label A-docs T-libs
2023-11-24 08:23:53 +01:00
Matthias Krüger
f38de06ce6
Rollup merge of #117940 - zhiqiangxu:remove_redundant_drop, r=thomcc
chore: remove unnecessary drop

 No need to manually drop since it's implicit.
2023-11-24 08:23:52 +01:00
Matthias Krüger
7e3ec1b0e2
Rollup merge of #117656 - ChrisDenton:invalid, r=thomcc
Update windows-bindgen and define `INVALID_HANDLE_VALUE` ourselves

We generate bindings to the Windows API via the `windows-bindgen` crate, which is ultimately what's also used to generate the `windows-sys` and `windows` crates. However, there currently is some custom sauce just for std which makes it a bit different from the vanilla bindings. I would love for us to reduce and eventually remove the differences entirely so that std is using the exact same bindings as everyone else. Maybe in the future we can even just have a normal dependency on `windows-sys`.

This PR removes one of those special things. Our definition of `INVALID_HANDLE_VALUE` relies on an experimental nightly feature for strict provenance, so lets bring that back in house. It also excludes it from the codegen step though that isn't strictly necessary as we override it in any case.

This PR also updates windows-bingen to 0.52.0.
2023-11-24 08:23:52 +01:00
Matthias Krüger
b8657093d6
Rollup merge of #116807 - seanlinsley:patch-2, r=thomcc
Improve rewind documentation

The persistent use of an internal cursor for readers is expected for buffer data types that aren't read all at once, but for files it leads to the confusing situation where calling `read_to_end` on the same file handle multiple times only returns the contents of the file for the first call. This PR adds a note to the documentation clarifying that in that case, `rewind()` must first be called.

I'm unsure if this is the right location for the docs update. Maybe it should also be duplicated on `File`?
2023-11-24 08:23:51 +01:00
bors
8abf920985 Auto merge of #117722 - okaneco:binarysearch, r=thomcc
Refactor `binary_search_by` to use conditional moves

Refactor the if/else checking on `cmp::Ordering` variants to a "branchless" reassignment of left and right.

This change results in fewer branches and instructions.
https://rust.godbolt.org/z/698eYffTx

---

I saw consistent benchmark improvements locally. Performance of worst case seems about the same, maybe slightly faster for the L3 test.

Current
```
slice::binary_search_l1             43.00ns/iter +/- 3.00ns
slice::binary_search_l1_with_dups   25.00ns/iter +/- 0.00ns
slice::binary_search_l1_worst_case  10.00ns/iter +/- 0.00ns
slice::binary_search_l2             64.00ns/iter +/- 1.00ns
slice::binary_search_l2_with_dups   42.00ns/iter +/- 0.00ns
slice::binary_search_l2_worst_case  16.00ns/iter +/- 0.00ns
slice::binary_search_l3            132.00ns/iter +/- 2.00ns
slice::binary_search_l3_with_dups  108.00ns/iter +/- 2.00ns
slice::binary_search_l3_worst_case  33.00ns/iter +/- 3.00ns
```
This PR
```
slice::binary_search_l1            21.00ns/iter +/- 0.00ns
slice::binary_search_l1_with_dups  14.00ns/iter +/- 0.00ns
slice::binary_search_l1_worst_case  9.00ns/iter +/- 0.00ns
slice::binary_search_l2            34.00ns/iter +/- 0.00ns
slice::binary_search_l2_with_dups  23.00ns/iter +/- 0.00ns
slice::binary_search_l2_worst_case 16.00ns/iter +/- 0.00ns
slice::binary_search_l3            92.00ns/iter +/- 3.00ns
slice::binary_search_l3_with_dups  63.00ns/iter +/- 1.00ns
slice::binary_search_l3_worst_case 29.00ns/iter +/- 0.00ns
```
2023-11-24 07:23:04 +00:00
Mark Rousskov
b81e788d16 Indicate that multiplication in Layout::array cannot overflow
This allows LLVM to optimize comparisons to zero before & after the
multiplication into one, saving on code size and eliminating an (always
true) branch from most Vec allocations.
2023-11-23 22:05:45 -05:00
bors
e68f935117 Auto merge of #98943 - WilliamVenner:feat/bufread_skip_until, r=dtolnay
Add `BufRead::skip_until`

Alternative version of `BufRead::read_until` that simply discards data, rather than copying it into a buffer.

Useful for situations like skipping irrelevant data in a binary file format that is NUL-terminated.

<details>
<summary>Benchmark</summary>

```
running 2 tests
test bench_read_until ... bench:         123 ns/iter (+/- 6)
test bench_skip_until ... bench:          66 ns/iter (+/- 3)
```

```rs
#![feature(test)]
extern crate test;
use test::Bencher;

use std::io::{ErrorKind, BufRead};

fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize, std::io::Error> {
    let mut read = 0;
    loop {
        let (done, used) = {
            let available = match r.fill_buf() {
                Ok(n) => n,
                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            };
            match memchr::memchr(delim, available) {
                Some(i) => (true, i + 1),
                None => (false, available.len()),
            }
        };
        r.consume(used);
        read += used;
        if done || used == 0 {
            return Ok(read);
        }
    }
}

const STR: &[u8] = b"Ferris\0Hello, world!\0";

#[bench]
fn bench_skip_until(b: &mut Bencher) {
    b.iter(|| {
        let mut io = std::io::Cursor::new(test::black_box(STR));
        skip_until(&mut io, b'\0').unwrap();
        let mut hello = Vec::with_capacity(b"Hello, world!\0".len());
        let num_bytes = io.read_until(b'\0', &mut hello).unwrap();
        assert_eq!(num_bytes, b"Hello, world!\0".len());
        assert_eq!(hello, b"Hello, world!\0");
    });
}

#[bench]
fn bench_read_until(b: &mut Bencher) {
    b.iter(|| {
        let mut io = std::io::Cursor::new(test::black_box(STR));
        io.read_until(b'\0', &mut Vec::new()).unwrap();
        let mut hello = Vec::with_capacity(b"Hello, world!\0".len());
        let num_bytes = io.read_until(b'\0', &mut hello).unwrap();
        assert_eq!(num_bytes, b"Hello, world!\0".len());
        assert_eq!(hello, b"Hello, world!\0");
    });
}
```
</details>
2023-11-23 22:28:14 +00:00
David Tolnay
52c07b9564
Fix tracking issue of Windows ExitCodeExt 2023-11-23 11:16:10 -08:00
bohan
fc87d6e23d add track_caller for arith ops 2023-11-24 00:54:06 +08:00
bors
193466525d Auto merge of #115159 - solid-rs:patch/kmc-solid/io-safety, r=workingjubilee
kmc-solid: I/O safety

Adds the I/O safety API (#87329) for socket file descriptors in [`*-kmc-solid_*`](https://doc.rust-lang.org/nightly/rustc/platform-support/kmc-solid.html) Tier 3 targets. All new public items are gated by the `solid_ext` library feature.

This PR adds the following public types and traits:

    std::os::solid::io::AsFd
    std::os::solid::io::BorrowedFd
    std::os::solid::io::OwnedFd

    std::os::solid::prelude::AsFd (re-export)
    std::os::solid::prelude::BorrowedFd (re-export)
    std::os::solid::prelude::OwnedFd (re-export)

And trait implementations:

    From<std::net::TcpListener> for std::os::solid::io::OwnedFd
    From<std::net::TcpStream> for std::os::solid::io::OwnedFd
    From<std::net::UdpSocket> for std::os::solid::io::OwnedFd
    From<std::os::solid::io::OwnedFd> for std::net::TcpListener
    From<std::os::solid::io::OwnedFd> for std::net::TcpStream
    From<std::os::solid::io::OwnedFd> for std::net::UdpSocket
    std::fmt::Debug for std::os::solid::io::BorrowedFd<'_>
    std::fmt::Debug for std::os::solid::io::OwnedFd
    std::io::IsTerminal for std::os::solid::io::BorrowedFd<'_>
    std::io::IsTerminal for std::os::solid::io::OwnedFd
    std::os::fd::AsRawFd for std::os::solid::io::BorrowedFd<'_>
    std::os::fd::AsRawFd for std::os::solid::io::OwnedFd
    std::os::fd::FromRawFd for std::os::solid::io::OwnedFd
    std::os::fd::IntoRawFd for std::os::solid::io::OwnedFd
    std::os::solid::io::AsFd for &impl std::os::solid::io::AsFd
    std::os::solid::io::AsFd for &mut impl std::os::solid::io::AsFd
    std::os::solid::io::AsFd for Arc<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for Box<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for Rc<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for std::net::TcpListener
    std::os::solid::io::AsFd for std::net::TcpStream
    std::os::solid::io::AsFd for std::net::UdpSocket
    std::os::solid::io::AsFd for std::os::solid::io::BorrowedFd<'_>
    std::os::solid::io::AsFd for std::os::solid::io::OwnedFd

Taking advantage of the above change, this PR also refactors the internal details of `std::sys::solid::net` to match the design of other targets, e.g., by redefining `Socket` as a newtype of `OwnedFd`.
2023-11-23 04:24:09 +00:00
Max Heller
84b3c84223
add missing period in std::process::Command docs 2023-11-22 20:04:43 -05:00
bors
c387f012b1 Auto merge of #118154 - ChrisDenton:win-clippy, r=scottmcm
Fix some clippy lints for library/std/src/sys/windows

These issues were shown by running `x clippy` on `library/std` and filtering for `windows/` paths. I think running clippy on the full std would be great but I wanted to start smaller and with something that's hopefully easier to review. It'd be good to eventually run clippy in CI but that's a bigger conversation.

I've created separate commits for each clippy lint fixed (with the commit title set to the lint name) and reviewed the changes myself. Most of the fixes here are trivial.

r? libs
2023-11-23 00:30:15 +00:00
Ralf Jung
74834a9d74 also make 'core_intrinsics' internal 2023-11-22 20:00:56 +01:00
Ralf Jung
79ad512ec0 warn against using intrinsics that leave the scope of our memory model 2023-11-22 19:32:11 +01:00
Chris Denton
b9fe367b99
x fmt library/std 2023-11-22 13:17:02 +00:00
Chris Denton
6c8ebf174c
redundant_slicing 2023-11-22 13:17:02 +00:00
Chris Denton
852c038393
cmp_null
comparing with null is better expressed by the `.is_null()` method
2023-11-22 13:17:02 +00:00
Chris Denton
c15adf6557
manual_range_contains 2023-11-22 13:17:01 +00:00
Chris Denton
d7e1f1cc08
op_ref
taken reference of right operand
2023-11-22 13:00:30 +00:00
Chris Denton
4c084c576a
manual_map
manual implementation of `Option::map`
2023-11-22 13:00:30 +00:00
Chris Denton
8c85c5b7f4
unnecessary_lazy_evaluations
unnecessary closure used with `bool::then`
2023-11-22 13:00:29 +00:00
Chris Denton
220217af13
redundant_closure 2023-11-22 13:00:29 +00:00
Chris Denton
b962ae1324
duration_subsec
calling `subsec_micros()` is more concise than this calculation
2023-11-22 13:00:29 +00:00
Chris Denton
9e42456a0d
unnecessary_cast
casting to the same type is unnecessary
2023-11-22 13:00:29 +00:00
Chris Denton
24542639aa
needless_borrow
this expression creates a reference which is immediately dereferenced by the compiler
2023-11-22 13:00:29 +00:00
Chris Denton
42734599bd
needless_borrows_for_generic_args
the borrowed expression implements the required traits
2023-11-22 13:00:28 +00:00
Chris Denton
fe255695f9
manual_slice_size_calculation 2023-11-22 13:00:28 +00:00
Chris Denton
bfbeb3ebd9
unnecessary_mut_passed
This is where our Windows API bindings previously (and incorrectly) used `*mut` instead of `*const` pointers. Now that the bindings have been corrected, the mutable references (which auto-convert to `*mut`) are unnecessary and we can use shared references.
2023-11-22 13:00:28 +00:00
Chris Denton
6c22e57c39
useless_conversion 2023-11-22 13:00:28 +00:00
Chris Denton
533de2bc41
needless_return
unneeded `return` statement
2023-11-22 13:00:28 +00:00
Urgau
4c2d6de70e Stabilize RFC3324 dyn upcasting coercion
Aka trait_upcasting feature.

And also adjust the `deref_into_dyn_supertrait` lint.
2023-11-22 13:56:36 +01:00
Chris Denton
ad12be3668
allow clippy style in windows/c.rs
We intentional use the Windows API style here.
2023-11-22 00:14:46 +00:00
roblabla
08803eb4c8 Update backtrace submodule 2023-11-21 16:33:42 +01:00
bors
e24e5af787 Auto merge of #117619 - elomatreb:add-duration-abs-diff, r=thomcc
Add `Duration::abs_diff`

This adds a `Duration::abs_diff` method analogous to the existing one on the primitive integers.

ACP: https://github.com/rust-lang/libs-team/issues/291
Tracking Issue: https://github.com/rust-lang/rust/issues/117618
2023-11-21 13:09:49 +00:00
Nilstrieb
bfc2675362
Rollup merge of #118094 - JarvisCraft:SpecFromElem-for-empty-tuple, r=thomcc
feat: specialize `SpecFromElem` for `()`

# Description

This PR adds a specialization `SpecFromElem for ()` which allows to significantly reduce `vec![(), N]` time in debug builds (specifically, tests) turning it from observable $O(n)$ to $O(1)$.

# Observing the change

The problem this PR aims to fix explicitly is slow `vec![(), N]` on big `N`s which may appear in tests (see [Background section](#Background) for more details).

The minimal example to see the problem:

```rust
#![feature(test)]

extern crate test;

#[cfg(test)]
mod tests {
    const HUGE_SIZE: usize = i32::MAX as usize + 1;

    #[bench]
    fn bench_vec_literal(b: &mut test::Bencher) {
        b.iter(|| vec![(); HUGE_SIZE]);
    }

    #[bench]
    fn bench_vec_repeat(b: &mut test::Bencher) {
        b.iter(|| [(); 1].repeat(HUGE_SIZE));
    }
}
```
<details><summary>Output</summary>
<p>

```bash
cargo +nightly test -- --report-time -Zunstable-options
   Compiling huge-zst-vec-literal-bench v0.1.0 (/home/progrm_jarvis/RustroverProjects/huge-zst-vec-literal-bench)
    Finished test [unoptimized + debuginfo] target(s) in 0.31s
     Running unittests src/lib.rs (target/debug/deps/huge_zst_vec_literal_bench-e43b1ef287ba8b36)

running 2 tests
test tests::bench_vec_repeat  ... ok <0.000s>
test tests::bench_vec_literal ... ok <14.382s>

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 14.38s

   Doc-tests huge-zst-vec-literal-bench

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```
</p>
</details>

> [!IMPORTANT]
> This problem is only observable in Debug (unoptimized) builds, while Release (optimized) ones do not observe this problem. It still is worth fixing it, IMO, since the original scenario observes the problem in tests for which optimizations are disabled by default and it seems unreasonable to override this for the whole project while the problem is very local.

# Background

While working on a crate for a custom data format which has an `i32::MAX` limit on its list's sizes, I wrote the following test to ensure that this invariant is upheld:

```rust
#[test]
fn lists_should_have_i32_size() {
    assert!(
        RawNbtList::try_from(vec![(); i32::MAX as usize]).is_ok(),
        "lists should permit the size up to {}",
        i32::MAX
    );
    assert!(
        RawNbtList::try_from(vec![(); i32::MAX as usize + 1]).is_err(),
        "lists should have the size of at most {}",
        i32::MAX
    );
}
```

Soon I discovered that this takes $\approx 3--4s$ per assertion on my machine, almost all of which is spent on `vec![..]`.
While this would be logical for a non-ZST vector (which would require actual $O(n)$ allocation), here `()` was used intentionally considering that for ZSTs size-changing operations should anyway be $O(1)$ (at least from allocator perspective). Yet, this "overhead" is logical if we consider that in general case `clone()` (which is used by `Vec` literal) may have a non-trivial implementation and thus each element has to actually be visited (even if they occupy no space).

In my specific case, the following (contextual) equivalent solved the issue:

```rust
#[test]
fn lists_should_have_i32_size() {
    assert!(
        RawNbtList::try_from([(); 1].repeat(i32::MAX as usize)).is_ok(),
        "lists should permit the size up to {}",
        i32::MAX
    );
    assert!(
        RawNbtList::try_from([(); 1].repeat(i32::MAX as usize + 1)).is_err(),
        "lists should have the size of at most {}",
        i32::MAX
    );
}
```

which works since `repeat` explicitly uses `T: Copy` and so does not have to think about non-trivial `Clone`.

But it still may be counter-intuitive for users to observe such long time on the "canonical" vec literal thus the PR.

# Generic solution

This change is explicitly non-generic. Initially I considered it possible to implement in generically, but this would require the specialization to have the following type requirements:
-  the type must be a ZST: easily done via
  ```rust
  if core::mem::size_of::<T>() == 0 {
    todo!("specialization")
  }
  ```
  or
  ```rust
  use core::mem::SizedTypeProperties;
  if T::IS_ZST {
    todo!("specialization")
  }
  ```
- :white_check_mark`: the type must implement `Copy`: implementable non-conflictable via a separate specialization:
  ```rust
  trait IsCopyZst: Sized {
    fn is_copy_zst() -> bool;
  }
  impl<T> IsCopyZst for T {
    fn is_copy_zst() -> bool {
        false
    }
  }
  impl<T: Copy> IsCopyZst for T {
    fn is_copy_zst() -> bool {
        Self::IS_ZST
    }
  }
  ```
-  the type should have a trivial `Clone` implementation: since `vec![t; n]` is specified to use `clone()`, we can only use this "performance optimization" when we are guaranteed that `clone()` does nothing except for copying.

The latter is the real blocker for a generic fix since I am unaware of any way to get this information in a compiler-guaranteed way.

While there may be a fix for this (my friend `@CertainLach` has suggested a potential solution by an perma-unstable fn in `Clone` like `is_trivially_cloneable()` defaulting to `false` and only overridable by `rustc` on derive), this is surely out of this PRs scope.
2023-11-21 09:06:29 +01:00
Nilstrieb
6bb671e7e8
Rollup merge of #117790 - rcvalle:rust-cfi-fix-000000, r=workingjubilee
CFI: Add missing use core::ffi::c_int

Adds missing use core::ffi::c_int for when sanitizer_cfi_normalize_integers is defined.
2023-11-21 09:06:27 +01:00
Petr Portnov
72a8633ee8
docs(GH-118094): make docs a bit more explicit
Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:35:04 +03:00
Petr Portnov
91fcdde51b
chore(GH-118094): explicitly mark _elem as unused
Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:33:55 +03:00
Petr Portnov
2fd9442afc
feat: specialize SpecFromElem for ()
While a better approach would be to implement it for all ZSTs
which are `Copy` and have trivial `Clone`,
the last property cannot be detected for now.

Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:29:09 +03:00
Michael Goulet
6d33e900d8
Rollup merge of #117957 - the8472:pidfd-wait, r=Mark-Simulacrum
if available use a Child's pidfd for kill/wait

This should get us closer to stabilization of pidfds since they now do something useful. And they're `CLOEXEC` now.

```
$ strace -ffe clone,sendmsg,recvmsg,execve,kill,pidfd_open,pidfd_send_signal,waitpid,waitid ./x test std --no-doc -- pidfd

[...]
running 1 tests
strace: Process 816007 attached
[pid 816007] pidfd_open(816006, 0)      = 3
[pid 816007] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f0c6b787990) = 816008
strace: Process 816008 attached
[pid 816007] recvmsg(3,  <unfinished ...>
[pid 816008] pidfd_open(816008, 0)      = 3
[pid 816008] sendmsg(4, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[3]}], msg_controllen=24, msg_flags=0}, 0) = 0
[pid 816007] <... recvmsg resumed>{msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[4]}], msg_controllen=24, msg_flags=MSG_CMSG_CLOEXEC}, MSG_CMSG_CLOEXEC) = 0
[pid 816008] execve("/usr/bin/false", ["false"], 0x7ffcf2100048 /* 105 vars */) = 0
[pid 816007] waitid(P_PIDFD, 4,  <unfinished ...>
[pid 816008] +++ exited with 1 +++
[pid 816007] <... waitid resumed>{si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=816008, si_uid=1001, si_status=1, si_utime=0, si_stime=0}, WEXITED, NULL) = 0
[pid 816007] --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=816008, si_uid=1001, si_status=1, si_utime=0, si_stime=0} ---
[pid 816007] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLDstrace: Process 816009 attached
, child_tidptr=0x7f0c6b787990) = 816009
[pid 816007] recvmsg(3,  <unfinished ...>
[pid 816009] pidfd_open(816009, 0)      = 3
[pid 816009] sendmsg(5, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[3]}], msg_controllen=24, msg_flags=0}, 0) = 0
[pid 816007] <... recvmsg resumed>{msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[5]}], msg_controllen=24, msg_flags=MSG_CMSG_CLOEXEC}, MSG_CMSG_CLOEXEC) = 0
[pid 816009] execve("/usr/bin/sleep", ["sleep", "1000"], 0x7ffcf2100048 /* 105 vars */) = 0
[pid 816007] waitid(P_PIDFD, 5, {}, WNOHANG|WEXITED, NULL) = 0
[pid 816007] pidfd_send_signal(5, SIGKILL, NULL, 0) = 0
[pid 816007] waitid(P_PIDFD, 5,  <unfinished ...>
[pid 816009] +++ killed by SIGKILL +++
[pid 816007] <... waitid resumed>{si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=816009, si_uid=1001, si_status=SIGKILL, si_utime=0, si_stime=0}, WEXITED, NULL) = 0
[pid 816007] --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=816009, si_uid=1001, si_status=SIGKILL, si_utime=0, si_stime=0} ---
[pid 816007] +++ exited with 0 +++
```
2023-11-19 19:14:34 -08:00
Chris Denton
3a486c1feb
Use an absolute path to the NUL device
While a bare "NUL" *should* be redirected to the NUL device, especially in this simple case, let's be explicit that we aren't opening a file called "NUL" and instead open it directly.

This will also set a good example for people copying std code.
2023-11-19 16:24:39 +00:00
The 8472
f34e7f4768 Don't set cmsg fields in msghdr if we have no cmsg to send 2023-11-19 15:19:47 +01:00
bors
d052f6fde6 Auto merge of #117895 - mzohreva:mz/fix-sgx-backtrace, r=Mark-Simulacrum
Adjust frame IP in backtraces relative to image base for SGX target

This is followup to https://github.com/rust-lang/backtrace-rs/pull/566.

The backtraces printed by `panic!` or generated by `std::backtrace::Backtrace` in SGX target are not usable. The frame addresses need to be relative to image base address so they can be used for symbol resolution. Here's an example panic backtrace generated before this change:

```
$ cargo r --target x86_64-fortanix-unknown-sgx
...
stack backtrace:
   0:     0x7f8fe401d3a5 - <unknown>
   1:     0x7f8fe4034780 - <unknown>
   2:     0x7f8fe401c5a3 - <unknown>
   3:     0x7f8fe401d1f5 - <unknown>
   4:     0x7f8fe401e6f6 - <unknown>
```
Here's the same panic after this change:
```
$ cargo +stage1 r --target x86_64-fortanix-unknown-sgx
stack backtrace:
   0:            0x198bf - <unknown>
   1:            0x3d181 - <unknown>
   2:            0x26164 - <unknown>
   3:            0x19705 - <unknown>
   4:            0x1ef36 - <unknown>
```
cc `@jethrogb` and `@workingjubilee`
2023-11-19 03:00:18 +00:00
Takayuki Maeda
baf3059f4e
Rollup merge of #116750 - fintelia:seek_seek_relative, r=Mark-Simulacrum
Add Seek::seek_relative

The `BufReader` struct has a `seek_relative` method because its `Seek::seek` implementation involved dumping the internal buffer (https://github.com/rust-lang/rust/issues/31100).

Unfortunately, there isn't really a good way to take advantage of that method in generic code. This PR adds the same method to the main `Seek` trait with the straightforward default method, and an override for `BufReader` that calls its implementation.

_Also discussed in [this](https://internals.rust-lang.org/t/add-seek-seek-relative/19546) internals.rust-lang.org thread._
2023-11-19 04:14:40 +09:00
bors
33688d2467 Auto merge of #117525 - GKFX:remove_option_payload_ptr, r=petrochenkov
Remove option_payload_ptr; redundant to offset_of

The `option_payload_ptr` intrinsic is no longer required as `offset_of` supports traversing enums (#114208). This PR removes it in order to dogfood offset_of (as suggested at https://github.com/rust-lang/rust/issues/106655#issuecomment-1790907626). However, it will not build until those changes reach beta (which I think is within the next 8 days?) so I've opened it as a draft.
2023-11-18 12:45:42 +00:00
George Bateman
58ea02e872
Update based on petrochenkov's review 2023-11-18 10:50:47 +00:00
bors
6416e2e675 Auto merge of #115412 - eswartz:docs/total_cmp-test-result-in-docs, r=scottmcm
Expose tests for {f32,f64}.total_cmp in docs

Expose tests for {f32,f64}.total_cmp in docs

Uncomment the helpful `assert_eq!` line, which is stripped out completely in docs, and leaves the reader to mentally play through the algorithm, or go to the playground and add a println!, to see what the result will be.

(If these tests are known to fail on some platforms, is there some mechanism to conditionalize this or escape the test so the `assert_eq!` source will be visible on the web? I am a newbie, which is why I was reading docs ;)
2023-11-18 08:49:03 +00:00
bors
61d3b263a7 Auto merge of #115249 - clarfonthey:alignment, r=scottmcm
impl more traits for ptr::Alignment, add mask method

Changes:

* Adds `rustc_const_unstable` attributes where missing
* Makes `log2` method const
* Adds `mask` method
* Implements `Default`, which is equivalent to `Alignment::MIN`

No longer included in PR:

* Removes indirection of `AlignmentEnum` type alias (this was intentional)
* Implements `Display`, `Binary`, `Octal`, `LowerHex`, and `UpperHex` (should go through libs-api instead)
* Controversially implements `LowerExp` and `UpperExp` using `p` instead of `e` to indicate a power of 2 (also should go through libs-api)

Tracking issue for `ptr::Alignment`: #102070
2023-11-18 06:51:15 +00:00
ltdk
114873dc19 impl more traits for ptr::Alignment, add mask method 2023-11-18 00:05:28 -05:00
bors
e6dade96f4 Auto merge of #117825 - fee1-dead-contrib:corefx, r=petrochenkov
Reenable effects in libcore

With #116670, #117531, and #117171, I think we would be comfortable with re-enabling the effects feature for more testing in libcore.

r? `@oli-obk`
cc `@fmease`
cc #110395
2023-11-18 04:56:31 +00:00
bors
1a740c3816 Auto merge of #117138 - zachs18:rwlock_guard_debug_unsized, r=dtolnay
Add T: ?Sized to `RwLockReadGuard` and `RwLockWriteGuard`'s Debug impls.

For context, `MutexGuard` has `+ ?Sized` on its `Debug` impl, and all three have `+ ?Sized` on their `Display` impls.

It looks like the `?Sized` was just missed when the impls were added (the impl for `MutexGuard` was added in the same PR (https://github.com/rust-lang/rust/pull/38006) with support for `T: Debug + ?Sized`, and `RwLock*Guard`s did allow `T: ?Sized` types already); the `Display` impls were added later (https://github.com/rust-lang/rust/pull/42822) with support for `T: Debug + ?Sized` types.

I think this needs a T-libs-api FCP? I'm not sure if this also needs an ACP. If so I can make one.

These are changes to (stable) trait impls on stable types so will be insta-stable.

`@rustbot` label +T-libs-api
2023-11-18 00:59:19 +00:00
Jules Bertholet
db62921159
Document behavior of <dyn Any as Any>::type_id()
See also #57893
2023-11-17 19:54:37 -05:00