Commit graph

4289 commits

Author SHA1 Message Date
Dylan DPC
1db7f690b1
Rollup merge of #103570 - lukas-code:stabilize-ilog, r=scottmcm
Stabilize integer logarithms

Stabilizes feature `int_log`.

I've also made the functions const stable, because they don't depend on any unstable const features. `rustc_allow_const_fn_unstable` is just there for `Option::expect`, which could be replaced with a `match` and `panic!`. cc ``@rust-lang/wg-const-eval``

closes https://github.com/rust-lang/rust/issues/70887 (tracking issue)

~~blocked on FCP finishing: https://github.com/rust-lang/rust/issues/70887#issuecomment-1289028216~~
FCP finished: https://github.com/rust-lang/rust/issues/70887#issuecomment-1302121266
2022-11-09 19:21:21 +05:30
onestacked
f6658479a8 const Compare Tuples 2022-11-09 09:52:04 +01:00
Jakob Degen
ba359d8a51 Add support for custom MIR parsing 2022-11-08 23:13:15 -08:00
Guillaume Gomez
02db37a18a
Rollup merge of #104113 - ink-feather-org:fix_const_fn_ref_impls, r=compiler-errors
Fix `const_fn_trait_ref_impl`, add test for it

#99943 broke `#[feature(const_fn_trait_ref_impl)]`, this PR fixes this and adds a test for it.

r? ````@fee1-dead````
2022-11-08 20:40:51 +01:00
Guillaume Gomez
c39cf7acaa
Rollup merge of #104109 - yancyribbens:add-mutable-to-comment-for-align-to-mut, r=thomcc
rustdoc: Add mutable to the description

`mutable` is missing from the description.  Currently the description for [align_to](https://github.com/rust-lang/rust/blob/master/library/core/src/slice/mod.rs#L3498) is the same as [align_to_mut](https://github.com/rust-lang/rust/blob/master/library/core/src/slice/mod.rs#L3559)
2022-11-08 20:40:51 +01:00
onestacked
56e59bcb27 Test const Hash, fix nits 2022-11-08 17:39:40 +01:00
The 8472
3925fc0c8e document and improve array Guard type
The type is unsafe and now exposed to the whole crate.
Document it properly and add an unsafe method so the
caller can make it visible that something unsafe is happening.
2022-11-08 00:13:26 +01:00
The 8472
43c353fff7 simplification: do not process the ArrayChunks remainder in fold() 2022-11-07 21:44:25 +01:00
The 8472
cfcce8e684 specialize iter::ArrayChunks::fold for TrustedRandomAccess iters
This is fairly safe use of TRA since it consumes the iterator so
no struct in an unsafe state will be left exposed to user code
2022-11-07 21:44:25 +01:00
The 8472
eb3f001d37 make the array initialization guard available to other modules 2022-11-07 21:44:25 +01:00
The 8472
b00666ed09 add benchmark for iter::ArrayChunks::fold specialization
This also updates the existing iter::Copied::next_chunk benchmark so
that the thing it benches doesn't get masked by the ArrayChunks specialization
2022-11-07 21:44:24 +01:00
onestacked
0c9896bfaa Fix const_fn_trait_ref_impl, add test for it 2022-11-07 17:41:58 +01:00
yancy
f67ee43fe3 rustdoc: Add mutable to the description 2022-11-07 17:02:48 +01:00
yancy
d62582f92a rustdoc: Add mutable to the description 2022-11-07 16:51:23 +01:00
onestacked
cebce1e616 Removed unnecessary Trait bound 2022-11-07 15:34:43 +01:00
Mark Rousskov
01a2a57ac9 Fix rebase errors 2022-11-06 17:38:47 -05:00
Mark Rousskov
40290505fb cfg-step code 2022-11-06 17:21:21 -05:00
Mark Rousskov
455a7bc685 Bump version placeholders to release 2022-11-06 17:11:02 -05:00
Alex Saveau
28ea002340
Add small clarification around using pointers derived from references
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-11-06 12:09:55 -08:00
bors
7eef946fc0 Auto merge of #99943 - compiler-errors:tuple-trait, r=jackh726
Implement `std::marker::Tuple`, use it in `extern "rust-call"` and `Fn`-family traits

Implements rust-lang/compiler-team#537

I made a few opinionated decisions in this implementation, specifically:
1. Enforcing `extern "rust-call"` on fn items during wfcheck,
2. Enforcing this for all functions (not just ones that have bodies),
3. Gating this `Tuple` marker trait behind its own feature, instead of grouping it into (e.g.) `unboxed_closures`.

Still needing to be done:
1. Enforce that `extern "rust-call"` `fn`-ptrs are well-formed only if they have 1/2 args and the second one implements `Tuple`. (Doing this would fix ICE in #66696.)
2. Deny all explicit/user `impl`s of the `Tuple` trait, kinda like `Sized`.
3. Fixing `Tuple` trait built-in impl for chalk, so that chalkification tests are un-broken.

Open questions:
1. Does this need t-lang or t-libs signoff?

Fixes #99820
2022-11-06 17:48:33 +00:00
onestacked
dc1f1a8e97 Added const_hash tracking issue id 2022-11-06 18:01:44 +01:00
onestacked
5f9899b289 Made Sip const Hasher 2022-11-06 17:46:38 +01:00
Ralf Jung
6b7f6b98c7 remove no-longer-needed work-arounds from the standard library 2022-11-06 14:20:09 +01:00
Matthias Krüger
d93b5200d5
Rollup merge of #104002 - RalfJung:unsafecell-new, r=JohnTitor
fix a comment in UnsafeCell::new

There are several safe methods that access the inner value: `into_inner` has existed since forever and `get_mut` also exists since recently. So this comment seems just wrong. But `&self` methods return raw pointers and thus require unsafe code (though the methods themselves are still safe).
2022-11-06 08:35:27 +01:00
Michael Goulet
d9891563d3 Merge conflicts and rebase onto master 2022-11-05 18:05:44 +00:00
Michael Goulet
2786acce98 Enforce Tuple trait on Fn traits 2022-11-05 17:34:47 +00:00
Ralf Jung
dad327090a fix a comment in UnsafeCell::new 2022-11-05 12:27:43 +01:00
Dylan DPC
47e6304e32
Rollup merge of #103995 - SUPERCILEX:typos, r=Dylan-DPC
Small round of typo fixes
2022-11-05 11:31:30 +05:30
Alex Saveau
849d89b031
Small round of typo fixes
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-11-04 20:06:18 -07:00
onestacked
3ea4165a77 Make BuildHasher const_trait 2022-11-04 21:30:47 +01:00
onestacked
1bcf9fae03 Made Hash and Hasher const_trait 2022-11-04 21:30:46 +01:00
Matthias Krüger
428dd011ca
Rollup merge of #103680 - RalfJung:cstr-links, r=JohnTitor
CStr: add some doc links
2022-11-04 12:18:00 +01:00
Neutron3529
d81a0e9e2d
update comment 2022-11-04 15:37:33 +08:00
Neutron3529
aafe6db079
fix the overflow warning.
benchmark result:
```
$ cargo bench
   Compiling div-euclid v0.1.0 (/me/div-euclid)
    Finished bench [optimized] target(s) in 1.01s
     Running unittests src/lib.rs (target/release/deps/div_euclid-7a4530ca7817d1ef)

running 7 tests
test tests::it_works ... ignored
test tests::bench_aaabs     ... bench:  10,498,793 ns/iter (+/- 104,360)
test tests::bench_aadefault ... bench:  11,061,862 ns/iter (+/- 94,107)
test tests::bench_abs       ... bench:  10,477,193 ns/iter (+/- 81,942)
test tests::bench_default   ... bench:  10,622,983 ns/iter (+/- 25,119)
test tests::bench_zzabs     ... bench:  10,481,971 ns/iter (+/- 43,787)
test tests::bench_zzdefault ... bench:  11,074,976 ns/iter (+/- 29,633)

test result: ok. 0 passed; 0 failed; 1 ignored; 6 measured; 0 filtered out; finished in 19.35s
```
benchmark code:
```rust
#![feature(test)]
extern crate test;

#[inline(always)]
fn rem_euclid(a:i32,rhs:i32)->i32{
    let r = a % rhs;
    if r < 0 {
        // if rhs is `integer::MIN`, rhs.wrapping_abs() == rhs.wrapping_abs,
        // thus r.wrapping_add(rhs.wrapping_abs()) == r.wrapping_add(rhs) == r - rhs,
        // which suits our need.
        // otherwise, rhs.wrapping_abs() == -rhs, which won't overflow since r is negative.
        r.wrapping_add(rhs.wrapping_abs())
    } else {
        r
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;
    use rand::prelude::*;
    use rand::rngs::SmallRng;
    const N:i32=1000;
    #[test]
    fn it_works() {
        let a: i32 = 7; // or any other integer type
        let b = 4;

        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();

        for i in &d {
            for j in &n {
                assert_eq!(i.rem_euclid(*j),rem_euclid(*i,*j));
            }
        }

        assert_eq!(rem_euclid(a,b), 3);
        assert_eq!(rem_euclid(-a,b), 1);
        assert_eq!(rem_euclid(a,-b), 3);
        assert_eq!(rem_euclid(-a,-b), 1);
    }


    #[bench]
    fn bench_aaabs(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_aadefault(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }

    #[bench]
    fn bench_abs(b: &mut Bencher) {
        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_default(b: &mut Bencher) {
        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }

    #[bench]
    fn bench_zzabs(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_zzdefault(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }
}
```
2022-11-03 17:08:10 +08:00
Neutron3529
3ad4d24751
Optimize the code to run faster.
such code is copy from
https://github.com/rust-lang/rust/blob/master/library/std/src/f32.rs
and
https://github.com/rust-lang/rust/blob/master/library/std/src/f64.rs
using r+rhs.abs() is faster than calc it directly.
Bench result:
```
$ cargo bench
   Compiling div-euclid v0.1.0 (/me/div-euclid)
    Finished bench [optimized] target(s) in 1.01s
     Running unittests src/lib.rs (target/release/deps/div_euclid-7a4530ca7817d1ef)

running 7 tests
test tests::it_works ... ignored
test tests::bench_aaabs     ... bench:  10,498,793 ns/iter (+/- 104,360)
test tests::bench_aadefault ... bench:  11,061,862 ns/iter (+/- 94,107)
test tests::bench_abs       ... bench:  10,477,193 ns/iter (+/- 81,942)
test tests::bench_default   ... bench:  10,622,983 ns/iter (+/- 25,119)
test tests::bench_zzabs     ... bench:  10,481,971 ns/iter (+/- 43,787)
test tests::bench_zzdefault ... bench:  11,074,976 ns/iter (+/- 29,633)

test result: ok. 0 passed; 0 failed; 1 ignored; 6 measured; 0 filtered out; finished in 19.35s
```
bench code:
```
#![feature(test)]
extern crate test;

fn rem_euclid(a:i32,rhs:i32)->i32{
    let r = a % rhs;
    if r < 0 { r + rhs.abs() } else { r }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;
    use rand::prelude::*;
    use rand::rngs::SmallRng;
    const N:i32=1000;
    #[test]
    fn it_works() {
        let a: i32 = 7; // or any other integer type
        let b = 4;

        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();

        for i in &d {
            for j in &n {
                assert_eq!(i.rem_euclid(*j),rem_euclid(*i,*j));
            }
        }

        assert_eq!(rem_euclid(a,b), 3);
        assert_eq!(rem_euclid(-a,b), 1);
        assert_eq!(rem_euclid(a,-b), 3);
        assert_eq!(rem_euclid(-a,-b), 1);
    }


    #[bench]
    fn bench_aaabs(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_aadefault(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }

    #[bench]
    fn bench_abs(b: &mut Bencher) {
        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_default(b: &mut Bencher) {
        let d:Vec<i32>=(-N..=N).collect();
        let n:Vec<i32>=(-N..0).chain(1..=N).collect();
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }

    #[bench]
    fn bench_zzabs(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=rem_euclid(*i,*j);
                }
            }
            res
        });
    }
    #[bench]
    fn bench_zzdefault(b: &mut Bencher) {
        let mut d:Vec<i32>=(-N..=N).collect();
        let mut n:Vec<i32>=(-N..0).chain(1..=N).collect();
        let mut rng=SmallRng::from_seed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,21]);
        d.shuffle(&mut rng);
        n.shuffle(&mut rng);
        d.shuffle(&mut rng);
        b.iter(||{
            let mut res=0;
            for i in &d {
                for j in &n {
                    res+=i.rem_euclid(*j);
                }
            }
            res
        });
    }
}
```
2022-11-03 16:35:37 +08:00
Sky
1d971b1322
Add tracking issue for const_arguments_as_str 2022-11-02 16:24:16 -04:00
Dylan DPC
bbd3a10663
Rollup merge of #103774 - compiler-errors:dyn-trait-in-type-name, r=eholk
Format `dyn Trait` better in `type_name` intrinsic

Noticed this in #103764 (though not related to that PR at all!)

```rust
trait Foo {
    type Bar;
}

fn main() {
    println!(
        "`dyn Fn(i32, i32) -> i32` => `{}`",
        std::any::type_name::<dyn Fn(i32, i32) -> i32>()
    );
    println!(
        "`dyn Foo<Bar = i32> + Send + Sync` => `{}`",
        std::any::type_name::<dyn Foo<Bar = i32> + Send + Sync>()
    );
}
```

```
`dyn Fn(i32, i32) -> i32` => `dyn core::ops::function::Fn<(i32, i32)>+Output = i32`
`dyn Foo<Bar = i32> + Send + Sync` => `dyn playground::Foo+Bar = i32+core::marker::Sync+core::marker::Send`
```

Just reuse `pretty_print_dyn_existential` which already makes an attempt to make its output stable.
2022-11-02 22:32:03 +05:30
Manish Goregaokar
d4bd794f5e
Rollup merge of #103084 - inquisitivecrystal:control-flow, r=scottmcm
Derive `Eq` and `Hash` for `ControlFlow`

There's really no reason for `ControlFlow` not to derive these traits. This is the part of #96416 that no one objected to, but that PR seems stale. The `Eq` derive was also [requested](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/.60ControlFlow.3A.20Eq.60/near/303610659) by `@lcnr` on Zulip to allow for pattern matching.

This change requires an FCP because it's insta-stable.

Closes #96416.
2022-11-01 20:00:37 -04:00
Michael Goulet
e24df2778f Format dyn Trait better in type_name intrinsic 2022-11-01 20:41:47 +00:00
Dylan DPC
20528baac4
Rollup merge of #103729 - RalfJung:align-of-val-packed, r=oli-obk
interpret: fix align_of_val on packed types

Fixes https://github.com/rust-lang/miri/issues/2632

r? `@oli-obk`
2022-11-01 14:12:26 +05:30
Amanieu d'Antras
56074b5231 Rewrite implementation of #[alloc_error_handler]
The new implementation doesn't use weak lang items and instead changes
`#[alloc_error_handler]` to an attribute macro just like
`#[global_allocator]`.

The attribute will generate the `__rg_oom` function which is called by
the compiler-generated `__rust_alloc_error_handler`. If no `__rg_oom`
function is defined in any crate then the compiler shim will call
`__rdl_oom` in the alloc crate which will simply panic.

This also fixes link errors with `-C link-dead-code` with
`default_alloc_error_handler`: `__rg_oom` was previously defined in the
alloc crate and would attempt to reference the `oom` lang item, even if
it didn't exist. This worked as long as `__rg_oom` was excluded from
linking since it was not called.

This is a prerequisite for the stabilization of
`default_alloc_error_handler` (#102318).
2022-10-31 16:32:57 +00:00
Dylan DPC
d80bcf8316
Rollup merge of #103766 - lukas-code:error-in-core, r=Dylan-DPC
Add tracking issue to `error_in_core`

This was merged in https://github.com/rust-lang/rust/pull/99917 without a tracking issue, so I'm creating one now: https://github.com/rust-lang/rust/issues/103765
2022-10-31 14:52:57 +05:30
Lukas Markeffsky
f56d3c3140 Add tracking issue to error_in_core 2022-10-30 17:26:46 +01:00
Matthias Krüger
e4821d743b
Rollup merge of #103715 - tshepang:consistency, r=Dylan-DPC
use consistent terminology

I did not see other traits using the "interface" word
2022-10-30 00:09:25 +02:00
Matthias Krüger
22e320b2c9
Rollup merge of #100006 - jyn514:update-copy, r=dtolnay
Make `core::mem::copy` const

cc https://github.com/rust-lang/rust/issues/98262, https://github.com/rust-lang/libs-team/issues/78
2022-10-30 00:09:23 +02:00
Ralf Jung
d366471e58 interpret: fix align_of_val on packed types 2022-10-29 15:58:32 +02:00
Tshepang Mbambo
a36a37e5a8 use consistent terminology
I did not see other traits using the "interface" word
2022-10-29 09:23:12 +02:00
Matthias Krüger
b3ca68f9e9
Rollup merge of #102961 - reitermarkus:const-cstr-from-ptr, r=oli-obk
Make `CStr::from_ptr` `const`.

Should be included in https://github.com/rust-lang/rust/issues/101719.

cc ``@WaffleLapkin``
2022-10-29 08:57:34 +02:00
bors
7174231ae6 Auto merge of #102737 - RalfJung:poll_fn_pin, r=Mark-Simulacrum
poll_fn and Unpin: fix pinning

See [IRLO](https://internals.rust-lang.org/t/surprising-soundness-trouble-around-pollfn/17484) for details: currently `poll_fn` is very subtle to use, since it does not pin the closure, so creating a `Pin::get_unchcked(&mut capture)` inside the closure is unsound. This leads to actual miscompilations with `futures::join!`.

IMO the proper fix is to pin the closure when the future is pinned, which is achieved by changing the `Unpin` implementation. This is a breaking change though. 1.64.0 was *just* released, so maybe this is still okay?

The alternative would be to add some strong comments to the docs saying that closure captures are *not pinned* and doing `Pin::get_unchecked` on them is unsound.
2022-10-28 23:27:33 +00:00
Maybe Waffle
d3b51926f8 Simplify implementation of various pointer methods 2022-10-28 23:06:29 +04:00
Maybe Waffle
6c54745784 Make pointer::with_metadata_of const (+simplify implementation) 2022-10-28 23:05:22 +04:00
Maybe Waffle
8498e3a9bb Add examples for pointer::mask 2022-10-28 19:48:38 +04:00
Markus Reiter
b3f9277a17
Remove unneeded attribute. 2022-10-28 14:17:34 +02:00
Ralf Jung
a6c3f6ce1d CStr: add some doc links 2022-10-28 10:24:14 +02:00
Matthias Krüger
c75e6f559f
Rollup merge of #103394 - Pointerbender:unsafecell-docs, r=Amanieu
Clarify documentation about the memory layout of `UnsafeCell`

This PR addresses a [comment](https://github.com/rust-lang/rust/pull/101717#issuecomment-1279908390) by `@RalfJung` in PR #101717 to further clarify the documentation of `UnsafeCell<T>`. The previous PR was merged already before we had a chance to correct this, hence this second PR :)

To goal of this PR is:

1. Split the paragraph about the memory layout of `UnsafeCell<T>` and the usage of `UnsafeCell::(raw_)get()` into two paragraphs, so that it is easier to digest for the reader.
2. Slightly simplify the previously added examples in order to reduce redundancy between the new examples and the examples that already [existed](ddd119b2fe/library/core/src/cell.rs (L1858-L1908)) before these 2 PRs (which remained untouched by both PRs).
2022-10-27 15:03:56 +02:00
Matthias Krüger
6d43dfb7bb
Rollup merge of #103110 - RalfJung:manual-send, r=thomcc
remove redundant Send impl for references

Also explain why the other instance is not redundant, move it next to the trait they are implementing, and out of the redundant module. This seems to go back all the way to 35ca50bd56, not sure why the module was added.

The instance for `&mut` is the default instance we get anyway, and we don't have anything similar for `Sync`, so IMO we should be consistent and not have the redundant instance here, either.
2022-10-27 15:03:55 +02:00
Matthias Krüger
0cd87148d9
Rollup merge of #103106 - saethlin:from_exposed_docs, r=thomcc
Try to say that memory outside the AM is always exposed

cc ``@Gankra`` ``@thomcc``

I want to confidently tell people that they can use `from_exposed_addr` to get a pointer for doing MMIO and/or other hardware interactions done with volatile reads/writes at particular addresses outside the Rust AM. Currently, the docs indicate that would be UB.

With this change, now the docs indicate that this is intended to be a valid use of `from_exposed_addr`.

r? ``@RalfJung``
2022-10-27 09:25:09 +02:00
Matthias Krüger
2937621aa7
Rollup merge of #103035 - saethlin:assert_unsafe_precondition3, r=thomcc
Even nicer errors from assert_unsafe_precondition

For example, now running `cargo test` with this patch I get things like:
```
$ cargo +stage1 test
    Finished test [unoptimized + debuginfo] target(s) in 0.01s
     Running unittests src/lib.rs (target/debug/deps/malloc_buf-9d105ddf86862995)

running 5 tests
thread 'tests::test_null_buf' panicked at 'unsafe precondition violated: is_aligned_and_not_null(data) &&
    crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize', /home/ben/rust/library/core/src/slice/raw.rs:93:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread panicked while panicking. aborting.
error: test failed, to rerun pass `--lib`

Caused by:
  process didn't exit successfully: `/tmp/malloc_buf-1.0.0/target/debug/deps/malloc_buf-9d105ddf86862995` (signal: 6, SIGABRT: process abort signal)
```

This is still not perfect, but these are better for another PR:
* `stringify!` is trying to do clever pretty-printing on the `expr` inside `assert_unsafe_precondition` and can even add a newline.
* It would be nice to print a bit more information about where the problem is. Perhaps this is `cfg_attr(debug_assertions, track_caller)`, or perhaps it the function name added to `Location`.

cc ``@RalfJung`` this is what I was thinking of for https://github.com/rust-lang/rust/pull/102732#discussion_r989068907
2022-10-27 09:25:08 +02:00
Pointerbender
166d8b8c2b add "Memory layout" subsection to documentation of UnsafeCell for additional clarity 2022-10-27 06:32:36 +02:00
Ben Kimock
458aaa5a23 Print the precondition we violated, and visible through output capture
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-26 22:09:17 -04:00
Yuki Okushi
77145c042d
Rollup merge of #103580 - lukas-code:guaranteed_ne, r=GuillaumeGomez
Fix typo in docs for `guaranteed_ne`

`==` -> `!=`
2022-10-27 08:30:58 +09:00
Yuki Okushi
26ad51ff87
Rollup merge of #103567 - RalfJung:ptr-eq-dyn-trait, r=dtolnay
ptr::eq: clarify that comparing dyn Trait is fragile

Also remove the dyn trait example from `ptr::eq` since those tests are not actually guaranteed to pass due to how unstable vtable comparison is.

Cc ``@rust-lang/libs-api``
Cc discussion following https://github.com/rust-lang/rust/pull/80505
2022-10-27 08:30:57 +09:00
Lukas Markeffsky
cce46e9ae2 Fix typo in docs for guaranteed_ne 2022-10-26 16:50:08 +02:00
Ben Kimock
bd947632b5
Update library/core/src/ptr/mod.rs
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-26 07:14:20 -07:00
Ralf Jung
1946a1842e explicitly mention that both components of wide prts are compared 2022-10-26 14:20:31 +02:00
Lukas Markeffsky
9e36fd926c stabilize int_log 2022-10-26 11:58:33 +02:00
Ralf Jung
99a74afa5f ptr::eq: clarify that comparing dyn Trait is fragile 2022-10-26 11:15:14 +02:00
Dylan DPC
8ed3a80b9a
Rollup merge of #103287 - saethlin:faster-len-check, r=thomcc
Use a faster allocation size check in slice::from_raw_parts

I've been perusing through the codegen changes that result from turning on the standard library debug assertions. The previous check in here uses saturating arithmetic, which in my experience sometimes makes LLVM just fail to optimize things around the saturating operation.

Here is a demo of the codegen difference: https://godbolt.org/z/WMEqrjajW
Before:
```asm
example::len_check_old:
        mov     rax, rdi
        mov     ecx, 3
        mul     rcx
        setno   cl
        test    rax, rax
        setns   al
        and     al, cl
        ret

example::len_check_old:
        mov     rax, rdi
        mov     ecx, 8
        mul     rcx
        setno   cl
        test    rax, rax
        setns   al
        and     al, cl
        ret
```
After:
```asm
example::len_check_new:
        movabs  rax, 3074457345618258603
        cmp     rdi, rax
        setb    al
        ret

example::len_check_new:
        shr     rdi, 60
        sete    al
        ret
```

Running rustc-perf locally, this looks like up to a 4.5% improvement when `debug-assertions-std = true`.

Thanks ```@LegionMammal978``` (I think that's you?) for turning my idea into a much cleaner implementation.

r? ```@thomcc```
2022-10-26 11:29:53 +05:30
Ben Kimock
0c3ae7d97c Try to say that memory outside the AM is always exposed
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-25 17:58:29 -04:00
Dylan DPC
d2d44f619f
Rollup merge of #98204 - Kixiron:stable-unzip, r=thomcc
Stabilize `Option::unzip()`

Stabilizes `Option::unzip()`, closes #87800

```@rustbot``` modify labels: +T-libs-api
2022-10-25 14:43:13 +05:30
Maybe Waffle
6279d092c3 Make pointer::byte_offset_from more generic 2022-10-24 16:05:54 +00:00
Yuki Okushi
c1f9d985d7
Rollup merge of #102271 - lopopolo:lopopolo/stabilize-duration-try-from-secs-float, r=dtolnay
Stabilize `duration_checked_float`

## Stabilization Report

This stabilization report is for a stabilization of `duration_checked_float`, tracking issue: https://github.com/rust-lang/rust/issues/83400.

### Implementation History

- https://github.com/rust-lang/rust/pull/82179
- https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051
- Changed error type to `FromFloatSecsError` in https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051 changes the rounding mode to round-to-nearest instead of truncate.

## API Summary

This stabilization report proposes the following API to be stabilized in `core`, along with their re-exports in `std`:

```rust
// core::time

impl Duration {
    pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, TryFromFloatSecsError>;
    pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TryFromFloatSecsError { ... }

impl core::fmt::Display for TryFromFloatSecsError { ... }
impl core::error::Error for TryFromFloatSecsError { ... }
```

These functions are made const unstable under `duration_consts_float`, tracking issue #72440.

There is an open question in the tracking issue around what the error type should be called which I was hoping to resolve in the context of an FCP.

In this stabilization PR, I have altered the name of the error type to `TryFromFloatSecsError`. In my opinion, the error type shares the name of the method (adjusted to accommodate both types of floats), which is consistent with other error types in `core`, `alloc` and `std` like `TryReserveError` and `TryFromIntError`.

## Experience Report

Code such as this is ready to be converted to a checked API to ensure it is panic free:

```rust
impl Time {
    pub fn checked_add_f64(&self, seconds: f64) -> Result<Self, TimeError> {
        // Fail safely during `f64` conversion to duration
        if seconds.is_nan() || seconds.is_infinite() {
            return Err(TzOutOfRangeError::new().into());
        }

        if seconds.is_sign_positive() {
            self.checked_add(Duration::from_secs_f64(seconds))
        } else {
            self.checked_sub(Duration::from_secs_f64(-seconds))
        }
    }
}
```

See: https://github.com/artichoke/artichoke/issues/2194.

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

cc `@mbartlett21`
2022-10-24 19:32:26 +09:00
bors
56f132565e Auto merge of #100848 - xfix:use-metadata-for-slice-len, r=thomcc
Use ptr::metadata in <[T]>::len implementation

This avoids duplication of ptr::metadata code.

I believe this is acceptable as the previous approach essentially duplicated `ptr::metadata` because back then `rustc_allow_const_fn_unstable` annotation did not exist.

I would like somebody to ping `@rust-lang/wg-const-eval` as the documentation says:

> Always ping `@rust-lang/wg-const-eval` if you are adding more rustc_allow_const_fn_unstable attributes to any const fn.
2022-10-24 04:14:46 +00:00
Pointerbender
5673536153
fix typos
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-24 04:27:37 +02:00
Scott McMurray
3b16c04676 unchecked_{shl|shr} should use u32 as the RHS 2022-10-23 17:32:36 -07:00
Michael Howell
ae2b1f096f
Rollup merge of #103447 - ajtribick:maybe_uninit_doc_update, r=scottmcm
`MaybeUninit`: use `assume_init_drop()` in the partially initialized array example

The `assume_init_drop()` method does the same thing as the pointer conversion, and makes the example more straightforward.
2022-10-23 14:48:19 -07:00
Michael Howell
acc269d65b
Rollup merge of #100462 - zohnannor:master, r=thomcc
Clarify `array::from_fn` documentation

I've seen quite a few of people on social media confused of where the length of array is coming from in the newly stabilized `array::from_fn` example.

This PR tries to clarify the documentation on this.
2022-10-23 14:48:13 -07:00
Andrew Tribick
560433ac86 MaybeUninit: use assume_init_drop() in the partially initialized array example 2022-10-23 19:09:18 +02:00
Ralf Jung
964290a0ad Pin::new_unchecked: discuss pinning closure captures 2022-10-22 18:11:36 +02:00
Dylan DPC
b22559f547
Rollup merge of #103346 - HeroicKatora:metadata_of_const_pointer_argument, r=dtolnay
Adjust argument type for mutable with_metadata_of (#75091)

The method takes two pointer arguments: one `self` supplying the pointer value, and a second pointer supplying the metadata.

The new parameter type more clearly reflects the actual requirements. The provenance of the metadata parameter is disregarded completely. Using a mutable pointer in the call site can be coerced to a const pointer while the reverse is not true.

In some cases, the current parameter type can thus lead to a very slightly confusing additional cast. [Example](cad93775eb).

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = val as *const _ as *mut T;
let ptr = uninit.as_ptr().with_metadata_of(ptr);
```

This could then instead be simplified to:

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = uninit.as_ptr().with_metadata_of(&**val);
```

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

``@dtolnay`` you're reviewed #95249, would you mind chiming in?
2022-10-22 16:28:09 +05:30
Dylan DPC
3f49f9506f
Rollup merge of #103329 - saethlin:nonnull-precondition, r=thomcc
Add a forgotten check for NonNull::new_unchecked's precondition

Looks like I forgot this function a while ago in https://github.com/rust-lang/rust/pull/92686

r? ```@thomcc```
2022-10-22 16:28:08 +05:30
Simonas Kazlauskas
a3c3f722b7 Fix mod_inv termination for the last iteration
On usize=u64 platforms, the 4th iteration would overflow the `mod_gate`
back to 0. Similarly for usize=u32 platforms, the 3rd iteration would
overflow much the same way.

I tested various approaches to resolving this, including approaches with
`saturating_mul` and `widening_mul` to a double usize. Turns out LLVM
likes `mul_with_overflow` the best. In fact now, that LLVM can see the
iteration count is limited, it will happily unroll the loop into a nice
linear sequence.

You will also notice that the code around the loop got simplified
somewhat. Now that LLVM is handling the loop nicely, there isn’t any
more reasons to manually unroll the first iteration out of the loop
(though looking at the code today I’m not sure all that complexity was
necessary in the first place).

Fixes #103361
2022-10-22 03:46:48 +03:00
bors
5c8bff74bc Auto merge of #101263 - lopopolo:lopopolo/c-unwind-fn-ptr-impls, r=thomcc
Add default trait implementations for "c-unwind" ABI function pointers

Following up on #92964, only add default trait implementations for the `c-unwind` family of function pointers. The previous attempt in #92964 added trait implementations for many more ABIs and ran into concerns regarding the increase in size of the libcore rlib.

An attempt to abstract away function pointer types behind a unified trait to reduce the duplication of trait impls is being discussed in #99531 but this change looks to be blocked on a lang MCP.

Following `@RalfJung's` suggestion in https://github.com/rust-lang/rust/pull/99531#issuecomment-1233440142, this commit is another cut at #92964 but it _only_ adds the impls for `extern "C-unwind" fn` and `unsafe extern "C-unwind" fn`.

I am interested in landing this patch to unblock the stabilization of the `c_unwind` feature.

RFC: https://github.com/rust-lang/rfcs/pull/2945
Tracking Issue: https://github.com/rust-lang/rust/issues/74990
2022-10-21 20:59:03 +00:00
Andreas Molzer
71c39dea4d Argument type for mutable with_metadata_of (#75091)
The method takes two pointer arguments: one `self` supplying the pointer
value, and a second pointer supplying the metadata.

The new parameter type more clearly reflects the actual requirements.
The provenance of the metadata parameter is disregarded completely.
Using a mutable pointer in the call site can be coerced to a const
pointer while the reverse is not true.

An example of the current use:

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = val as *const _ as *mut T;
let ptr = uninit.as_ptr().with_metadata_of(ptr);
```

This could then instead be simplified to:

```rust
// Manually taking an unsized object from a `ManuallyDrop` into another allocation.
let val: &core::mem::ManuallyDrop<T> = …;

let ptr = uninit.as_ptr().with_metadata_of(&**val);
```
2022-10-21 14:46:14 +02:00
Ben Kimock
9b6791078a Add a missing precondition check 2022-10-20 20:40:35 -04:00
Matthias Krüger
cfb424a044
Rollup merge of #103281 - thomcc:long-overdue, r=jyn514
Adjust `transmute{,_copy}` to be clearer about which of `T` and `U` is input vs output

This is essentially a documentation-only change (although it does touch code in an irrelevant way).
2022-10-20 22:42:39 +02:00
Andrew Tribick
aa9837ba29 Add tests for rounding of ties during float formatting 2022-10-20 22:09:24 +02:00
b4den
6cb65646b8 Update tests to match error message changes 2022-10-20 16:43:27 +01:00
Ryan Lopopolo
efe61dab21
Skip C-unwind fn pointer impls with the bootstrap compiler
These need to wait until #103239 makes it into the bootstrap compiler.
2022-10-20 07:37:17 -07:00
Pointerbender
16104474ad clarify documentation about the memory layout of UnsafeCell 2022-10-20 08:37:47 +02:00
Thom Chiovoloni
afd08175de
Adjust transmute{,_copy} to be clearer about which of T and U is input vs output 2022-10-19 22:36:14 -07:00
Ben Kimock
cfcb0a2135 Use a faster allocation size check in slice::from_raw_parts 2022-10-20 00:30:00 -04:00
Ryan Lopopolo
531679684c
Update stability annotations on fnptr impls for C-unwind ABI 2022-10-19 19:17:32 -07:00
Ryan Lopopolo
16dd5737b0
Add default trait implementations for "c-unwind" ABI function pointers
Following up on #92964, only add default trait implementations for the
`c-unwind` family of function pointers. The previous attempt in #92964
added trait implementations for many more ABIs and ran into concerns
regarding the increase in size of the libcore rlib.

An attempt to abstract away function pointer types behind a unified
trait to reduce the duplication of trait impls is being discussed in #99531
but this change looks to be blocked on a lang MCP.

Following @RalfJung's suggestion in
https://github.com/rust-lang/rust/pull/99531#issuecomment-1233440142,
this commit is another cut at #92964 but it _only_ adds the impls for
`extern "C-unwind" fn` and `unsafe extern "C-unwind" fn`.

I am interested in landing this patch to unblock the stabilization of
the `c_unwind` feature.

RFC: https://github.com/rust-lang/rfcs/pull/2945
Tracking Issue: https://github.com/rust-lang/rust/issues/74990
2022-10-19 19:17:32 -07:00
clubby789
19bc8fb05a Remove extra spaces 2022-10-19 23:54:00 +01:00
inquisitivecrystal
4a92cf6156 Derive Eq and Hash for ControlFlow 2022-10-19 13:25:34 -07:00
Dylan DPC
f4afb9d9ec
Rollup merge of #103127 - SUPERCILEX:inline-const-uninit, r=scottmcm
Make transpose const and inline

r? `@scottmcm`

- These should have been const from the beginning since we're never going to do more than a transmute.
- Inline these always because that's what every other method in MaybeUninit which simply casts does. :) Ok, but a stronger justification is that because we're taking in arrays by `self`, not inlining would defeat the whole purpose of using `MaybeUninit` due to the copying.
2022-10-19 14:05:52 +05:30
bors
84365fff0a Auto merge of #103225 - matthiaskrgr:rollup-1zkv87y, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #103166 (Optimize `slice_iter.copied().next_chunk()`)
 - #103176 (Fix `TyKind::is_simple_path`)
 - #103178 (Partially fix `src/test/run-make/coverage-reports` when cross-compiling)
 - #103198 (Update cargo)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-19 05:41:14 +00:00
Matthias Krüger
d6eb7bca09
Rollup merge of #103166 - the8472:copied-next-chunk, r=m-ou-se
Optimize `slice_iter.copied().next_chunk()`

```
OLD:
test iter::bench_copied_array_chunks                               ... bench:         371 ns/iter (+/- 7)
NEW:
test iter::bench_copied_array_chunks                               ... bench:          31 ns/iter (+/- 0)
```

The default `next_chunk` implementation suffers from having to assemble the array byte by byte via `next()`, checking the `Option<&T>` and then dereferencing `&T`. The specialization copies the chunk directly from the slice.
2022-10-19 07:15:30 +02:00
The 8472
873a18e221 specialize slice_iter.copied().next_chunk() 2022-10-19 00:02:00 +02:00
Matthias Krüger
18431b66ce
Rollup merge of #102507 - scottmcm:more-binary-search-docs, r=m-ou-se
More slice::partition_point examples

After seeing the discussion of `binary_search` vs `partition_point` in #101999, I thought some more example code could be helpful.
2022-10-18 21:18:46 +02:00
Matthias Krüger
d2644e538c
Rollup merge of #101889 - tspiteri:redoc-uint-adc-sbb, r=m-ou-se
doc: rewrite doc for uint::{carrying_add,borrowing_sub}

Reword the documentation for bigint helper methods `uint::{carrying_add,borrowing_sub}` (#85532).

The examples were also rewritten to demonstrate how the methods can be used in bignum arithmetic. No loops are used in the examples, but the variable names were chosen to include indices so that it is clear how this can be used in a loop if required.

Also, previously `carrying_add` had an example to say that if the input carry is false, the method is equivalent to `overflowing_add`. While the note was kept, the example was removed and an extra note was added to make sure this equivalence is not assumed for signed integers as well.
2022-10-18 21:18:46 +02:00
Yuki Okushi
b411b8861c
Rollup merge of #103163 - SUPERCILEX:uninit-array-assume2, r=scottmcm
Remove all uses of array_assume_init

See https://github.com/rust-lang/rust/pull/103134#discussion_r997462733

r? `@scottmcm`
2022-10-18 21:21:32 +09:00
Yuki Okushi
e04bbcb9b1
Rollup merge of #103159 - cuviper:check_pow-final-try_opt, r=Mark-Simulacrum
Remove the redundant `Some(try_opt!(..))` in `checked_pow`

The final return value doesn't need to be tried at all -- we can just
return the checked option directly. The optimizer can probably figure
this out anyway, but there's no need to make it work here.
2022-10-18 21:21:31 +09:00
The 8472
963d6f757c add a benchmark for slice_iter.copied().array_chunks() 2022-10-17 23:40:21 +02:00
Alex Saveau
55d71c61b8
Remove all uses of array_assume_init
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17 13:03:54 -07:00
Josh Stone
d7fd1d57ec Remove the redundant Some(try_opt!(..)) in checked_pow
The final return value doesn't need to be tried at all -- we can just
return the checked option directly. The optimizer can probably figure
this out anyway, but there's no need to make it work here.
2022-10-17 11:21:50 -07:00
Sky
9a7e527e28
Fix typo in ReverseSearcher docs 2022-10-17 13:14:15 -04:00
Thayne McCombs
63a7fdf61b Fix types in documentation for Alignment::as_usize and Alignmnet::as_nonzero 2022-10-16 23:44:06 -06:00
Alex Saveau
1a1ebb080f
Make transpose const and inline
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-16 17:51:38 -07:00
Matthias Krüger
0602d6484b
Rollup merge of #103109 - RalfJung:phantom-data-impl, r=thomcc
PhantomData: inline a macro that is used only once

I suspect this macro used to have more uses, but right now it just obfuscates the code.
2022-10-16 22:36:06 +02:00
Matthias Krüger
bdfc262742
Rollup merge of #103102 - H4x5:len_utf16_docs, r=scottmcm
Clarify the possible return values of `len_utf16`

`char::len_utf16` always return 1 or 2. Clarify this in the docs, in the same way as `char::len_utf8`.
2022-10-16 22:36:06 +02:00
Sky
a6372525ce
Clarify the possible return values of len_utf16 2022-10-16 11:06:19 -04:00
Ralf Jung
73d655e9c2 remove redundant Send impls for references
also move them next to the trait they are implementing
2022-10-16 11:34:24 +02:00
Ralf Jung
ddd5e983d1 PhantomData: inline a macro that is used only once 2022-10-16 10:37:51 +02:00
Yuki Okushi
166f664037
Rollup merge of #102023 - SUPERCILEX:maybeuninit-transpose, r=scottmcm
Add MaybeUninit array transpose From impls

See discussion in https://github.com/rust-lang/rust/pull/101179 and https://github.com/rust-lang/rust/issues/96097. I believe this solution offers the simplest implementation with minimal future API regret.

`@RalfJung` mind doing a correctness review?
2022-10-16 11:41:12 +09:00
Yuki Okushi
cbc0a73c95
Rollup merge of #101717 - Pointerbender:unsafecell-memory-layout, r=Amanieu
Add documentation about the memory layout of `UnsafeCell<T>`

The documentation for `UnsafeCell<T>` currently does not make any promises about its memory layout. This PR adds this documentation, namely that the memory layout of `UnsafeCell<T>` is the same as the memory layout of its inner `T`.

# Use case
Without this layout promise, the following cast would not be legally possible:

```rust
fn example<T>(ptr: *mut T) -> *const UnsafeCell<T> {
  ptr as *const UnsafeCell<T>
}
```

A use case where this can come up involves FFI. If Rust receives a pointer over a FFI boundary which provides shared read-write access (with some form of custom synchronization), and this pointer is managed by some Rust struct with lifetime `'a`, then it would greatly simplify its (internal) API and safety contract if a `&'a UnsafeCell<T>` can be created from a raw FFI pointer `*mut T`. A lot of safety checks can be done when receiving the pointer for the first time through FFI (non-nullness, alignment, initialize uninit bytes, etc.) and these properties can then be encoded into the `&UnsafeCell<T>` type. Without this documentation guarantee, this is not legal today outside of the standard library.

# Caveats
Casting in the opposite direction is still not valid, even with this documentation change:

```rust
fn example2<T>(ptr: &UnsafeCell<T>) -> &mut T {
  let t = ptr as *const UnsafeCell<T> as *mut T;
  unsafe { &mut *t }
}
```

This is because the only legal way to obtain a mutable pointer to the contents of the shared reference is through [`UnsafeCell::get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get) and [`UnsafeCell::raw_get`](https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.raw_get). Although there might be a desire to also make this legal at some point in the future, that part is outside the scope of this PR. Also see this relevant [Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/transmuting.20.26.20-.3E.20.26mut).

# Alternatives
Instead of adding a new documentation promise, it's also possible to add a new method to `UnsafeCell<T>` with signature `pub fn from_ptr_bikeshed(ptr: *mut T) -> *const UnsafeCell<T>` which indirectly only allows one-way casting to `*const UnsafeCell<T>`.
2022-10-16 11:41:12 +09:00
Alex Saveau
393434c29e
Add MaybeUninit array transpose impls
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-15 15:57:19 -07:00
Scott McMurray
5b9a02a87d More slice::partition_point examples 2022-10-15 14:03:56 -07:00
Ryan Lopopolo
95040a70d7
Stabilize duration_checked_float
Tracking issue:

- https://github.com/rust-lang/rust/issues/83400
2022-10-15 12:02:13 -07:00
bors
8147e6e427 Auto merge of #103069 - matthiaskrgr:rollup-xxsx6sk, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #102092 (refactor: use grep -E/-F instead of fgrep/egrep)
 - #102781 (Improved documentation for `std::io::Error`)
 - #103017 (Avoid dropping TLS Key on sgx)
 - #103039 (checktools: fix comments)
 - #103045 (Remove leading newlines from integer primitive doc examples)
 - #103047 (Update browser-ui-test version to fix some flaky tests)
 - #103054 (Clean up rust-logo rustdoc GUI test)
 - #103059 (Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`)
 - #103067 (More alphabetical sorting)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-14 22:56:53 +00:00
Matthias Krüger
03a521b4fe
Rollup merge of #103059 - beetrees:duration-from-negative-zero, r=thomcc
Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`

Make `Duration::{try_,}from_secs_f{32,64}(-0.0)` return `Duration::ZERO` (as they did before #90247) instead of erroring/panicking.

I'll update this PR to remove the `#![feature(duration_checked_float)]` if #102271 is merged before this PR.

Tracking issue for `try_from_secs_f{32,64}`: #83400
2022-10-14 23:43:46 +02:00
Matthias Krüger
1a5d8a5c59
Rollup merge of #103045 - lukas-code:blank-lines, r=GuillaumeGomez
Remove leading newlines from integer primitive doc examples

fixes https://github.com/rust-lang/rust/issues/103043

```@rustbot``` label +A-docs
2022-10-14 23:43:44 +02:00
bors
bf15a9e526 Auto merge of #101030 - woppopo:const_location, r=scottmcm
Constify `Location` methods

Tracking issue: #102911

Example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4789884c2f16ec4fb0e0405d86b794f5
2022-10-14 20:15:51 +00:00
beetrees
c9948f5c5f
Fix Duration::{try_,}from_secs_f{32,64}(-0.0) 2022-10-14 16:07:09 +01:00
Lukas Markeffsky
b8bb40664c remove leading newlines from integer primitive doc examples 2022-10-14 12:14:29 +02:00
Rageking8
7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
bors
4891d57f7a Auto merge of #102919 - luojia65:update-stdarch, r=Amanieu
library: update stdarch submodule

It has been one month since we update `stdarch`  submodule into main branch Rust, it includes various fixes in code and more neat documents. This pull request also adds missing features to ensure we can build latest stdarch submodule.

The documents after this pull request:
<details>

![图片](https://user-images.githubusercontent.com/40385009/195123337-a6c4cfaa-a7b9-4574-b524-c43683e6540c.png)
</details>

Comparing to current nightly:
<details>

![图片](https://user-images.githubusercontent.com/40385009/195123430-e047cff1-a925-4d2d-ae1c-da9769383a9c.png)
</details>

r? `@Amanieu`
2022-10-13 12:03:46 +00:00
luojia65
59fea7ecf4 library: update stdarch submodule
add feature target_feature_11 and riscv_target_feature
2022-10-13 09:41:16 +08:00
Pointerbender
ddd119b2fe expand documentation on type conversion w.r.t. UnsafeCell 2022-10-12 23:34:13 +02:00
Lukas Markeffsky
a02ec4cf18 remove HRTB from [T]::is_sorted_by{,_key} 2022-10-12 18:39:22 +02:00
bors
538f118da1 Auto merge of #102732 - RalfJung:assert_unsafe_precondition2, r=bjorn3
nicer errors from assert_unsafe_precondition

This makes the errors shown by cargo-careful nicer, and since `panic_no_unwind` is `nounwind noreturn` it hopefully doesn't have bad codegen impact. Thanks to `@bjorn3` for the hint!

Would be nice if we could somehow supply our own (static) message to print, currently it always prints `panic in a function that cannot unwind`. But still, this is better than before.
2022-10-12 14:39:43 +00:00
Markus Reiter
36dbb07daf
Update docs for CStr::from_ptr. 2022-10-12 13:46:20 +02:00
Markus Reiter
328f81713c
Make CStr::from_ptr const. 2022-10-12 13:01:30 +02:00
Dylan DPC
d8091f8991
Rollup merge of #102578 - lukas-code:ilog-panic, r=m-ou-se
Panic for invalid arguments of `{integer primitive}::ilog{,2,10}` in all modes

Decision made in https://github.com/rust-lang/rust/issues/100422#issuecomment-1245864700

resolves https://github.com/rust-lang/rust/issues/100422

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

r? `@m-ou-se`
2022-10-12 11:11:25 +05:30
Andrew Tribick
848744403a Fix inconsistent rounding of 0.5 when formatted to 0 decimal places 2022-10-11 23:09:23 +02:00
Ralf Jung
38c78a9ac1 reorder panicking.rs to put main entry points at the top 2022-10-11 22:47:31 +02:00
Ralf Jung
b61e742a39 use panic_fmt_nounwind for assert_unsafe_precondition 2022-10-11 22:47:31 +02:00
Ralf Jung
66282cb47d add panic_fmt_nounwind for panicing without unwinding, and use it for panic_no_unwind 2022-10-11 22:47:31 +02:00
Matthias Krüger
d10b47ef69
Rollup merge of #102445 - jmillikin:cstr-is-empty, r=Mark-Simulacrum
Add `is_empty()` method to `core::ffi::CStr`.

ACP: https://github.com/rust-lang/libs-team/issues/106

Tracking issue: https://github.com/rust-lang/rust/issues/102444
2022-10-11 18:59:48 +02:00
Matthias Krüger
d13f7aef70
Rollup merge of #101774 - Riolku:atomic-update-aba, r=m-ou-se
Warn about safety of `fetch_update`

Specifically as it relates to the ABA problem.

`fetch_update` is a useful function, and one that isn't provided by, say, C++. However, this does not mean the function is magic. It is implemented in terms of `compare_exchange_weak`, and in particular, suffers from the ABA problem. See the following code, which is a naive implementation of `pop` in a lock-free queue:

```rust
fn pop(&self) -> Option<i32> {
    self.front.fetch_update(Ordering::Relaxed, Ordering::Acquire, |front| {
        if front == ptr::null_mut() {
            None
        }
        else {
            Some(unsafe { (*front).next })
        }
    }.ok()
}
```

This code is unsound if called from multiple threads because of the ABA problem. Specifically, suppose nodes are allocated with `Box`. Suppose the following sequence happens:

```
Initial: Queue is X -> Y.

Thread A: Starts popping, is pre-empted.
Thread B: Pops successfully, twice, leaving the queue empty.
Thread C: Pushes, and `Box` returns X (very common for allocators)
Thread A: Wakes up, sees the head is still X, and stores Y as the new head.
```

But `Y` is deallocated. This is undefined behaviour.

Adding a note about this problem to `fetch_update` should hopefully prevent users from being misled, and also, a link to this common problem is, in my opinion, an improvement to our docs on atomics.
2022-10-11 18:59:46 +02:00
Yuki Okushi
ff903bbb71
Rollup merge of #102258 - cjgillot:core-kappa, r=m-ou-se
Remove unused variable in float formatting.
2022-10-11 18:37:52 +09:00
woppopo
a53e3acca9 Change tracking issue from #76156 to #102911 2022-10-11 06:40:37 +00:00
bors
0265a3e93b Auto merge of #96711 - emilio:inline-slice-clone, r=nikic
slice: #[inline] a couple iterator methods.

The one I care about and actually saw in the wild not getting inlined is
clone(). We ended up doing a whole function call for something that just
copies two pointers.

I ended up marking as_slice / as_ref as well because make_slice is
inline(always) itself, and is also the kind of think that can kill
performance in hot loops if you expect it to get inlined. But happy to
undo those.
2022-10-10 12:09:21 +00:00
Dylan DPC
7e16f9f1ea
Rollup merge of #99696 - WaffleLapkin:uplift, r=fee1-dead
Uplift `clippy::for_loops_over_fallibles` lint into rustc

This PR, as the title suggests, uplifts [`clippy::for_loops_over_fallibles`] lint into rustc. This lint warns for code like this:
```rust
for _ in Some(1) {}
for _ in Ok::<_, ()>(1) {}
```
i.e. directly iterating over `Option` and `Result` using `for` loop.

There are a number of suggestions that this PR adds (on top of what clippy suggested):
1. If the argument (? is there a better name for that expression) of a `for` loop is a `.next()` call, then we can suggest removing it (or rather replacing with `.by_ref()` to allow iterator being used later)
   ```rust
    for _ in iter.next() {}
    // turns into
    for _ in iter.by_ref() {}
    ```
2. (otherwise) We can suggest using `while let`, this is useful for non-iterator, iterator-like things like [async] channels
   ```rust
   for _ in rx.recv() {}
   // turns into
   while let Some(_) = rx.recv() {}
   ```
3. If the argument type is `Result<impl IntoIterator, _>` and the body has a `Result<_, _>` type, we can suggest using `?`
   ```rust
   for _ in f() {}
   // turns into
   for _ in f()? {}
   ```
4. To preserve the original behavior and clear intent, we can suggest using `if let`
   ```rust
   for _ in f() {}
   // turns into
   if let Some(_) = f() {}
   ```
(P.S. `Some` and `Ok` are interchangeable depending on the type)

I still feel that the lint wording/look is somewhat off, so I'll be happy to hear suggestions (on how to improve suggestions :D)!

Resolves #99272

[`clippy::for_loops_over_fallibles`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles
2022-10-10 13:43:40 +05:30
Scott McMurray
0718aeceb3 From<Alignment> for usize & NonZeroUsize 2022-10-09 15:44:49 -07:00
Pointerbender
9c37c801ad expand documentation on type conversion w.r.t. UnsafeCell 2022-10-09 22:32:23 +02:00
Yuki Okushi
38db483af7
Rollup merge of #102072 - scottmcm:ptr-alignment-type, r=thomcc
Add `ptr::Alignment` type

Essentially no new code here, just exposing the previously-`pub(crate)` `ValidAlign` type under the name from the ACP.

ACP: https://github.com/rust-lang/libs-team/issues/108
Tracking Issue: https://github.com/rust-lang/rust/issues/102070

r? ``@ghost``
2022-10-10 00:09:40 +09:00
Maybe Waffle
7434b9f0d1 fixup lint name 2022-10-09 13:07:21 +00:00
Maybe Waffle
75ae20a42f allow for_loop_over_fallibles in a core test 2022-10-09 13:07:20 +00:00