Commit Graph

3863 Commits

Author SHA1 Message Date
Matthias Krüger
1cdcf508bb
Rollup merge of #100663 - clarfonthey:const-reverse, r=scottmcm
Make slice::reverse const

I remember this not being doable for some reason before, but decided to try it again and everything worked out in the tests.
2022-08-21 16:54:01 +02:00
Matthias Krüger
a5c16a5381
Rollup merge of #100556 - Alex-Velez:patch-1, r=scottmcm
Clamp Function for f32 and f64

I thought the clamp function could use a little improvement for readability purposes. The function now returns early in order to skip the extra bound checks.

If there was a reason for binding `self` to `x` or if this code is incorrect, please correct me :)
2022-08-21 16:54:01 +02:00
Maybe Waffle
efef211876 Make use of pointer::is_aligned[_to] 2022-08-21 15:46:03 +04:00
Maybe Waffle
b2625e24b9 fix nitpicks from review 2022-08-21 06:36:11 +04:00
Maybe Waffle
168a837975 fill in tracking issue for feature(ptr_mask) 2022-08-21 05:27:14 +04:00
Maybe Waffle
10270f4b44 Add pointer masking convenience functions
This commit adds the following functions all of which have a signature
`pointer, usize -> pointer`:
- `<*mut T>::mask`
- `<*const T>::mask`
- `intrinsics::ptr_mask`

These functions are equivalent to `.map_addr(|a| a & mask)` but they
utilize `llvm.ptrmask` llvm intrinsic.

*masks your pointers*
2022-08-21 05:27:14 +04:00
Maybe Waffle
3ba393465f Make some docs nicer wrt pointer offsets 2022-08-21 02:22:20 +04:00
Maybe Waffle
e4720e1cf2 Replace most uses of pointer::offset with add and sub 2022-08-21 02:21:41 +04:00
Cameron Steffen
17ddcb434b Improve primitive/std docs separation and headers 2022-08-20 16:50:29 -05:00
Matthias Krüger
bd4a63cda2
Rollup merge of #100585 - wooorm:patch-1, r=Mark-Simulacrum
Fix trailing space showing up in example

The current text is rendered as: U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or (**note the final space!**)
This patch changes that to render as: U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or (**note no final space!**)

The reason for that, is that CommonMark has a solution for starting or ending inline code with a backtick/grave accent: padding both sides with a space, makes that padding disappear.
2022-08-20 19:32:08 +02:00
Matthias Krüger
d49906519b
Rollup merge of #99544 - dylni:expose-utf8lossy, r=Mark-Simulacrum
Expose `Utf8Lossy` as `Utf8Chunks`

This PR changes the feature for `Utf8Lossy` from `str_internals` to `utf8_lossy` and improves the API. This is done to eventually expose the API as stable.

Proposal: rust-lang/libs-team#54
Tracking Issue: #99543
2022-08-20 19:32:07 +02:00
dylni
e8ee0b7b2b Expose Utf8Lossy as Utf8Chunks 2022-08-20 12:49:20 -04:00
ltdk
ae2b1dbc89 Tracking issue for const_reverse 2022-08-19 20:38:32 -04:00
KaDiWa
a297631bdc
use <[u8]>::escape_ascii instead of core::ascii::escape_default 2022-08-19 19:00:37 +02:00
bors
6c943bad02 Auto merge of #99541 - timvermeulen:flatten_cleanup, r=the8472
Refactor iteration logic in the `Flatten` and `FlatMap` iterators

The `Flatten` and `FlatMap` iterators both delegate to `FlattenCompat`:
```rust
struct FlattenCompat<I, U> {
    iter: Fuse<I>,
    frontiter: Option<U>,
    backiter: Option<U>,
}
```
Every individual iterator method that `FlattenCompat` implements needs to carefully manage this state, checking whether the `frontiter` and `backiter` are present, and storing the current iterator appropriately if iteration is aborted. This has led to methods such as `next`, `advance_by`, and `try_fold` all having similar code for managing the iterator's state.

I have extracted this common logic of iterating the inner iterators with the option to exit early into a `iter_try_fold` method:
```rust
impl<I, U> FlattenCompat<I, U>
where
    I: Iterator<Item: IntoIterator<IntoIter = U>>,
{
    fn iter_try_fold<Acc, Fold, R>(&mut self, acc: Acc, fold: Fold) -> R
    where
        Fold: FnMut(Acc, &mut U) -> R,
        R: Try<Output = Acc>,
    { ... }
}
```
It passes each of the inner iterators to the given function as long as it keep succeeding. It takes care of managing `FlattenCompat`'s state, so that the actual `Iterator` methods don't need to. The resulting code that makes use of this abstraction is much more straightforward:
```rust
fn next(&mut self) -> Option<U::Item> {
    #[inline]
    fn next<U: Iterator>((): (), iter: &mut U) -> ControlFlow<U::Item> {
        match iter.next() {
            None => ControlFlow::CONTINUE,
            Some(x) => ControlFlow::Break(x),
        }
    }

    self.iter_try_fold((), next).break_value()
}
```
Note that despite being implemented in terms of `iter_try_fold`, `next` is still able to benefit from `U`'s `next` method. It therefore does not take the performance hit that implementing `next` directly in terms of `Self::try_fold` causes (in some benchmarks).

This PR also adds `iter_try_rfold` which captures the shared logic of `try_rfold` and `advance_back_by`, as well as `iter_fold` and `iter_rfold` for folding without early exits (used by `fold`, `rfold`, `count`, and `last`).

Benchmark results:
```
                                             before                after
bench_flat_map_sum                       423,255 ns/iter      414,338 ns/iter
bench_flat_map_ref_sum                 1,942,139 ns/iter    2,216,643 ns/iter
bench_flat_map_chain_sum               1,616,840 ns/iter    1,246,445 ns/iter
bench_flat_map_chain_ref_sum           4,348,110 ns/iter    3,574,775 ns/iter
bench_flat_map_chain_option_sum          780,037 ns/iter      780,679 ns/iter
bench_flat_map_chain_option_ref_sum    2,056,458 ns/iter      834,932 ns/iter
```

I added the last two benchmarks specifically to demonstrate an extreme case where `FlatMap::next` can benefit from custom internal iteration of the outer iterator, so take it with a grain of salt. We should probably do a perf run to see if the changes to `next` are worth it in practice.
2022-08-19 02:34:30 +00:00
Scott McMurray
8118a31e86 Inline <T as From<T>>::from
I noticed in the MIR for <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=67097e0494363ee27421a4e3bdfaf513> that it's inlined most stuff
```
scope 5 (inlined <Result<i32, u32> as Try>::branch)
```
```
scope 8 (inlined <Result<i32, u32> as Try>::from_output)
```

But yet the do-nothing `from` call was still there:
```
_17 = <u32 as From<u32>>::from(move _18) -> bb9;
```

So let's give this a try and see what perf has to say.
2022-08-18 16:04:00 -07:00
bors
361c599fee Auto merge of #98655 - nnethercote:dont-derive-PartialEq-ne, r=dtolnay
Don't derive `PartialEq::ne`.

Currently we skip deriving `PartialEq::ne` for C-like (fieldless) enums
and empty structs, thus reyling on the default `ne`. This behaviour is
unnecessarily conservative, because the `PartialEq` docs say this:

> Implementations must ensure that eq and ne are consistent with each other:
>
> `a != b` if and only if `!(a == b)` (ensured by the default
> implementation).

This means that the default implementation (`!(a == b)`) is always good
enough. So this commit changes things such that `ne` is never derived.

The motivation for this change is that not deriving `ne` reduces compile
times and binary sizes.

Observable behaviour may change if a user has defined a type `A` with an
inconsistent `PartialEq` and then defines a type `B` that contains an
`A` and also derives `PartialEq`. Such code is already buggy and
preserving bug-for-bug compatibility isn't necessary.

Two side-effects of the change:
- There is only one error message produced for types where `PartialEq`
  cannot be derived, instead of two.
- For coverage reports, some warnings about generated `ne` methods not
  being executed have disappeared.

Both side-effects seem fine, and possibly preferable.
2022-08-18 10:11:11 +00:00
David Tolnay
83f081fc01
Remove unstable Result::into_ok_or_err 2022-08-17 17:20:42 -07:00
Matthias Krüger
1199dbdcf5
Rollup merge of #100661 - PunkyMunky64:patch-1, r=thomcc
Fixed a few documentation errors

Quick pull request; IEEE-754, not IEEE-745. May save someone a quick second some time.
2022-08-17 12:33:02 +02:00
ltdk
5e1730fd17 Make slice::reverse const 2022-08-17 02:01:32 -04:00
PunkyMunky64
683b3f4e6e
Fixed a few documentation errors
Quick pull request; IEEE-754, not IEEE-745. May save someone a quick second some time.
2022-08-16 22:29:14 -07:00
PunkyMunky64
89d9a35b3e
Fixed a few documentation errors
IEEE-754, not IEEE-745. May save someone a second sometime
2022-08-16 22:28:11 -07:00
Alex
0ff8f0b578 Update src/test/assembly/x86_64-floating-point-clamp.rs
Simple Clamp Function

I thought this was more robust and easier to read. I also allowed this function to return early in order to skip the extra bound check (I'm sure the difference is negligible). I'm not sure if there was a reason for binding `self` to `x`; if so, please correct me.

Simple Clamp Function for f64

I thought this was more robust and easier to read. I also allowed this function to return early in order to skip the extra bound check (I'm sure the difference is negligible). I'm not sure if there was a reason for binding `self` to `x`; if so, please correct me.

Floating point clamp test

f32 clamp using mut self

f64 clamp using mut self

Update library/core/src/num/f32.rs

Update f64.rs

Update x86_64-floating-point-clamp.rs

Update src/test/assembly/x86_64-floating-point-clamp.rs

Update x86_64-floating-point-clamp.rs

Co-Authored-By: scottmcm <scottmcm@users.noreply.github.com>
2022-08-16 19:45:44 -04:00
Matthias Krüger
0b19a185db
Rollup merge of #100460 - cuviper:drop-llvm-12, r=nagisa
Update the minimum external LLVM to 13

With this change, we'll have stable support for LLVM 13 through 15 (pending release).
For reference, the previous increase to LLVM 12 was #90175.

r? `@nagisa`
2022-08-16 06:05:57 +02:00
Titus
8e80c39d2d
Fix trailing space showing up in example
The current text is rendered as: U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or.
This patch changes that to render as: U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or

The reason for that, is that CommonMark has a solution for starting or ending inline code with a backtick/grave accent: padding both sides with a space, makes that padding disappear.
2022-08-15 16:18:00 +02:00
Urgau
3f10e6c86d Say that the identity holds only for all finite numbers (aka not NaN) 2022-08-15 12:47:05 +02:00
Orson Peters
712bf2a07a Added tracking issue numbers for float_next_up_down. 2022-08-15 12:33:00 +02:00
Orson Peters
04681898f0 Added next_up and next_down for f32/f64. 2022-08-15 12:32:53 +02:00
Scott McMurray
7680c8b690 Properly forward ByRefSized::fold to the inner iterator 2022-08-14 22:55:30 -07:00
Josh Stone
2970ad8aee Update the minimum external LLVM to 13 2022-08-14 13:46:51 -07:00
austinabell
00bc9e8ac4
fix(iter::skip): Optimize next and nth implementations of Skip 2022-08-14 13:25:13 -04:00
Dylan DPC
482a6eaf10
Rollup merge of #100026 - WaffleLapkin:array-chunks, r=scottmcm
Add `Iterator::array_chunks` (take N+1)

A revival of https://github.com/rust-lang/rust/pull/92393.

r? `@Mark-Simulacrum`
cc `@rossmacarthur` `@scottmcm` `@the8472`

I've tried to address most of the review comments on the previous attempt. The only thing I didn't address is `try_fold` implementation, I've left the "custom" one for now, not sure what exactly should it use.
2022-08-14 17:09:14 +05:30
Ralf Jung
2dc9bf0fa0 nicer Miri backtraces for from_exposed_addr 2022-08-13 12:55:43 -04:00
Mark Rousskov
154a09dd91 Adjust cfgs 2022-08-12 16:28:15 -04:00
Dylan DPC
da3b89d0bf
Rollup merge of #100255 - thedanvail:issue-98861-fix, r=joshtriplett
Adding more verbose documentation for `std::fmt::Write`

Attempts to address #98861
2022-08-12 20:39:13 +05:30
Dylan DPC
51eed00ca9
Rollup merge of #100030 - WaffleLapkin:nice_pointer_sis, r=scottmcm
cleanup code w/ pointers in std a little

Use pointer methods (`byte_add`, `null_mut`, etc) to make code in std a little nicer.
2022-08-12 20:39:10 +05:30
Maybe Waffle
5fbcde1b55 fill-in tracking issue for feature(iter_array_chunks) 2022-08-12 15:04:29 +04:00
Maybe Waffle
eb6b729545 address review comments 2022-08-12 14:57:15 +04:00
Matthias Krüger
275d4e779a
Rollup merge of #100112 - RalfJung:assert_send_and_sync, r=m-ou-se
Fix test: chunks_mut_are_send_and_sync

Follow-up to https://github.com/rust-lang/rust/pull/100023 to make the test actually effective
2022-08-11 22:53:03 +02:00
Matthias Krüger
37efd55210
Rollup merge of #99511 - RalfJung:raw_eq, r=wesleywiser
make raw_eq precondition more restrictive

Specifically, don't allow comparing pointers that way. Comparing pointers is subtle because you have to talk about what happens to the provenance.

This matches what [Miri already implements](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=9eb1dfb8a61b5a2d4a7cee43df2717af), and all existing users are fine with this.

If raw_eq on pointers is ever desired, we can adjust the intrinsic spec and Miri implementation as needed, but for now that seems just unnecessary. Also, this is a const intrinsic, and in const, comparing pointers this way is *not possible* -- so if we allow the intrinsic to compare pointers in general, we need to impose an extra restrictions saying that in const-context, pointers are *not* okay.
2022-08-11 22:53:01 +02:00
Dylan DPC
d749914f79
Rollup merge of #100184 - Kixunil:stabilize_ptr_const_cast, r=m-ou-se
Stabilize ptr_const_cast

This stabilizes `ptr_const_cast` feature as was decided in a recent
[FCP](https://github.com/rust-lang/rust/issues/92675#issuecomment-1190660233)

Closes #92675
2022-08-11 22:46:58 +05:30
Ralf Jung
338d7c2fb0
more typos
Co-authored-by: Nicholas Nethercote <n.nethercote@gmail.com>
2022-08-11 07:37:22 -04:00
bors
908fc5b26d Auto merge of #99174 - scottmcm:reoptimize-layout-array, r=joshtriplett
Reoptimize layout array

This way it's one check instead of two, so hopefully (cc #99117) it'll be simpler for rustc perf too 🤞

Quick demonstration:
```rust
pub fn demo(n: usize) -> Option<Layout> {
    Layout::array::<i32>(n).ok()
}
```

Nightly: <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=e97bf33508aa03f38968101cdeb5322d>
```nasm
	mov	rax, rdi
	mov	ecx, 4
	mul	rcx
	seto	cl
	movabs	rdx, 9223372036854775805
	xor	esi, esi
	cmp	rax, rdx
	setb	sil
	shl	rsi, 2
	xor	edx, edx
	test	cl, cl
	cmove	rdx, rsi
	ret
```

This PR (note no `mul`, in addition to being much shorter):
```nasm
	xor	edx, edx
	lea	rax, [4*rcx]
	shr	rcx, 61
	sete	dl
	shl	rdx, 2
	ret
```

This is built atop `@CAD97` 's #99136; the new changes are cb8aba66ef6a0e17f08a0574e4820653e31b45a0.

I added a bunch more tests for `Layout::from_size_align` and `Layout::array` too.
2022-08-10 23:50:18 +00:00
Ralf Jung
d1cace5a97
grammar
Co-authored-by: Frank Steffahn <fdsteffahn@gmail.com>
2022-08-10 16:15:21 -04:00
Michael Goulet
eff71b9927
Rollup merge of #100371 - xfix:inline-from-bytes-with-nul-unchecked-rt-impl, r=scottmcm
Inline CStr::from_bytes_with_nul_unchecked::rt_impl

Currently `CStr::from_bytes_with_nul_unchecked::rt_impl` is not being inlined. The following function:

```rust
pub unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) {
    CStr::from_bytes_with_nul_unchecked(bytes);
}
```

Outputs the following assembly on current nightly

```asm
example::from_bytes_with_nul_unchecked:
        jmp     qword ptr [rip + _ZN4core3ffi5c_str4CStr29from_bytes_with_nul_unchecked7rt_impl17h026f29f3d6a41333E@GOTPCREL]
```

Meanwhile on beta this provides the following assembly:

```asm
example::from_bytes_with_nul_unchecked:
        ret
```

This pull request adds `#[inline]` annotation to`rt_impl` to fix a code generation regression for `CStr::from_bytes_with_nul_unchecked`.
2022-08-10 09:28:25 -07:00
Michael Goulet
efa182f3db
Rollup merge of #100353 - theli-ua:master, r=joshtriplett
Fix doc links in core::time::Duration::as_secs
2022-08-10 09:28:23 -07:00
Martin Habovstiak
2a3ce7890c Stabilize ptr_const_cast
This stabilizes `ptr_const_cast` feature as was decided in a recent
[FCP](https://github.com/rust-lang/rust/issues/92675#issuecomment-1190660233)

Closes #92675
2022-08-10 17:22:58 +02:00
Konrad Borowski
de95117ea8 Inline CStr::from_bytes_with_nul_unchecked::rt_impl 2022-08-10 12:21:17 +00:00
Matthias Krüger
3b97de6b1b
Rollup merge of #100345 - vincenzopalazzo:macros/is_number_doc, r=joshtriplett
docs: remove repetition in `is_numeric` function docs

In https://github.com/rust-lang/rust/pull/99628 we introduce new docs for the `is_numeric` function, and this is a follow-up PR that removes some unnecessary repetition that may be introduced by some rebasing.

`@rustbot` r? `@joshtriplett`
2022-08-10 07:21:39 +02:00
Anton Romanov
4a71447d38 Fix doc links in core::time::Duration::as_secs 2022-08-09 21:15:06 -07:00
Vincenzo Palazzo
23bd7cbcb1 docs: remove repetition
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2022-08-09 21:54:05 +00:00
Dan Vail
ee8a01f596 Switching documentation to be more clear about potential errors 2022-08-09 12:57:19 -05:00
Dan Vail
0436067210
Merge branch 'rust-lang:master' into issue-98861-fix 2022-08-09 12:52:11 -05:00
Eric Holk
c18f22058b Rename integer log* methods to ilog*
This reflects the concensus from the libs team as reported at
https://github.com/rust-lang/rust/issues/70887#issuecomment-1209513261

Co-authored-by: Yosh Wuyts <github@yosh.is>
2022-08-09 10:20:49 -07:00
Waffle Maybe
d52ed8234e
move an assert! to the right place 2022-08-09 21:19:19 +04:00
Anton Romanov
63be9a95b6 Update Duration::as_secs doc to point to as_secs_f64/32 for including fractional part
Rather than suggesting to calculate manually
2022-08-08 18:32:16 -07:00
Dan Vail
cc8259e4b6 Adding more verbose documentation for std::fmt::Write 2022-08-07 21:02:04 -05:00
Michael Goulet
6b2eab2310 Add Tuple marker trait 2022-08-07 16:28:24 -07:00
Matthias Krüger
ee0b755fe6
Rollup merge of #100175 - fxn:patch-1, r=Mark-Simulacrum
ascii -> ASCII in code comment

Easy one I spotted while reading source code.
2022-08-07 01:19:35 +02:00
Matthias Krüger
f0ff31fa09
Rollup merge of #100169 - WaffleLapkin:optimize_is_aligned_to, r=workingjubilee
Optimize `pointer::as_aligned_to`

This PR replaces `addr % align` with `addr & align - 1`, which is correct due to `align` being a power of two.

Here is a proof that this makes things better: [[godbolt]](https://godbolt.org/z/Wbq3hx6YG).

This PR also removes `assume(align != 0)`, with the new impl it does not improve anything anymore ([[godbolt]](https://rust.godbolt.org/z/zcnrG4777), [[original concern]](https://github.com/rust-lang/rust/pull/95643#discussion_r843326903)).
2022-08-07 01:19:34 +02:00
Xavier Noria
64d1c91a31
ascii -> ASCII in code comment 2022-08-05 18:45:42 +02:00
Maybe Waffle
c195f7c0a4 Optimize pointer::as_aligned_to 2022-08-05 17:14:32 +04:00
Maybe Waffle
a7c45ec867 improve documentation of pointer::align_offset 2022-08-05 16:47:49 +04:00
Maybe Waffle
127b6c4c18 cleanup code w/ pointers in std a little 2022-08-05 16:47:49 +04:00
Tim Vermeulen
38bb0b173e Move rfold logic into iter_rfold 2022-08-05 03:43:39 +02:00
Tim Vermeulen
3f7004920c Move fold logic to iter_fold method and reuse it in count and last 2022-08-05 03:43:39 +02:00
Tim Vermeulen
cbc5f62782 Move shared logic of try_rfold and advance_back_by into iter_try_rfold 2022-08-05 03:43:39 +02:00
Tim Vermeulen
8ff8d05279 Move shared logic of try_fold and advance_by into iter_try_fold 2022-08-05 03:43:39 +02:00
Kevin Reid
d4bcc4ae6d Remove self-referential intra-doc links. 2022-08-03 22:07:50 -07:00
Kevin Reid
1b87306b98 Document that RawWakerVTable functions must be thread-safe.
Also add some intra-doc links and more high-level explanation of how
`Waker` is used, while I'm here.

Context:
https://internals.rust-lang.org/t/thread-safety-of-rawwakervtables/17126
2022-08-03 19:14:31 -07:00
Ralf Jung
a61c841385 actually call assert_send_and_sync 2022-08-03 12:44:21 -04:00
bors
04f72f9538 Auto merge of #100023 - saethlin:send-sync-chunksmut, r=m-ou-se
Add back Send and Sync impls on ChunksMut iterators

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

These were accidentally removed in #94247 because the representation was changed from `&mut [T]` to `*mut T`, which has `!Send + !Sync`.
2022-08-03 13:17:58 +00:00
Dylan DPC
cb9932ea64
Rollup merge of #99614 - RalfJung:transmute-is-not-memcpy, r=thomcc
do not claim that transmute is like memcpy

Saying transmute is like memcpy is not a well-formed statement, since memcpy is by-ref whereas transmute is by-val. The by-val nature of transmute inherently means that padding is lost along the way. (This is not specific to transmute, this is how all by-value operations work.) So adjust the docs to clarify this aspect.

Cc `@workingjubilee`
2022-08-03 13:45:50 +05:30
Ralf Jung
da3e11fc42 wordsmithing 2022-08-02 20:43:48 -04:00
bors
e4417cf020 Auto merge of #92268 - jswrenn:transmute, r=oli-obk
Initial implementation of transmutability trait.

*T'was the night before Christmas and all through the codebase, not a miri was stirring — no hint of `unsafe`!*

This PR provides an initial, **incomplete** implementation of *[MCP 411: Lang Item for Transmutability](https://github.com/rust-lang/compiler-team/issues/411)*. The `core::mem::BikeshedIntrinsicFrom` trait provided by this PR is implemented on-the-fly by the compiler for types `Src` and `Dst` when the bits of all possible values of type `Src` are safely reinterpretable as a value of type `Dst`.

What this PR provides is:
- [x] [support for transmutations involving primitives](https://github.com/jswrenn/rust/tree/transmute/src/test/ui/transmutability/primitives)
- [x] [support for transmutations involving arrays](https://github.com/jswrenn/rust/tree/transmute/src/test/ui/transmutability/arrays)
- [x] [support for transmutations involving structs](https://github.com/jswrenn/rust/tree/transmute/src/test/ui/transmutability/structs)
- [x] [support for transmutations involving enums](https://github.com/jswrenn/rust/tree/transmute/src/test/ui/transmutability/enums)
- [x] [support for transmutations involving unions](https://github.com/jswrenn/rust/tree/transmute/src/test/ui/transmutability/unions)
- [x] [support for weaker validity checks](https://github.com/jswrenn/rust/blob/transmute/src/test/ui/transmutability/unions/should_permit_intersecting_if_validity_is_assumed.rs) (i.e., `Assume::VALIDITY`)
- [x] visibility checking

What isn't yet implemented:
- [ ] transmutability options passed using the `Assume` struct
- [ ] [support for references](https://github.com/jswrenn/rust/blob/transmute/src/test/ui/transmutability/references.rs)
- [ ] smarter error messages

These features will be implemented in future PRs.
2022-08-02 21:17:31 +00:00
Trevor Spiteri
97c963d081 make slice::{split_at,split_at_unchecked} const functions 2022-08-02 22:22:16 +02:00
Maybe Waffle
756bd6e3a3 Use next_chunk in ArrayChunks impl 2022-08-02 10:46:43 +04:00
Maybe Waffle
475e4ba747 Simplify ArrayChunks::{,r}fold impls 2022-08-01 19:17:01 +04:00
Maybe Waffle
4c0292cff5 Simplify ArrayChunks::is_empty 2022-08-01 19:17:01 +04:00
Maybe Waffle
37dfb04317 Remove Fuse from ArrayChunks implementation
It doesn't seem to be used at all.
2022-08-01 19:16:56 +04:00
Maybe Waffle
3102b39daa Use #[track_caller] to make panic in Iterator::array_chunks nicer 2022-08-01 19:16:36 +04:00
Maybe Waffle
4db628a801 Remove incorrect impl TrustedLen for ArrayChunks
As explained in the review of the previous attempt to add `ArrayChunks`,
adapters that shrink the length can't implement `TrustedLen`.
2022-08-01 19:16:24 +04:00
Ben Kimock
22dfbdd707 Add back Send and Sync impls on ChunksMut iterators
These were accidentally removed in #94247 because the representation was
changed from &mut [T] to *mut T, which has !Send + !Sync.
2022-08-01 10:32:45 -04:00
Maybe Waffle
b8b14864c0 Forward ArrayChunks::next{,_back} to try_{for_each,rfold}
(suggested in the review of the previous attempt to add `ArrayChunks`)
2022-08-01 18:26:18 +04:00
Maybe Waffle
ef72349e38 Remove array::IntoIter::with_partial -- an artifact of the past, once used to create an IntoIter from its parts 2022-08-01 17:00:51 +04:00
Ross MacArthur
f5485181ca Use array::IntoIter for the ArrayChunks remainder 2022-08-01 16:39:30 +04:00
Ross MacArthur
ca3d1010bb Add Iterator::array_chunks() 2022-08-01 16:39:27 +04:00
Nicholas Nethercote
d4a5b034b7 Don't derive PartialEq::ne.
Currently we skip deriving `PartialEq::ne` for C-like (fieldless) enums
and empty structs, thus reyling on the default `ne`. This behaviour is
unnecessarily conservative, because the `PartialEq` docs say this:

> Implementations must ensure that eq and ne are consistent with each other:
>
> `a != b` if and only if `!(a == b)` (ensured by the default
> implementation).

This means that the default implementation (`!(a == b)`) is always good
enough. So this commit changes things such that `ne` is never derived.

The motivation for this change is that not deriving `ne` reduces compile
times and binary sizes.

Observable behaviour may change if a user has defined a type `A` with an
inconsistent `PartialEq` and then defines a type `B` that contains an
`A` and also derives `PartialEq`. Such code is already buggy and
preserving bug-for-bug compatibility isn't necessary.

Two side-effects of the change:
- There is only one error message produced for types where `PartialEq`
  cannot be derived, instead of two.
- For coverage reports, some warnings about generated `ne` methods not
  being executed have disappeared.

Both side-effects seem fine, and possibly preferable.
2022-08-01 08:01:58 +10:00
BlackHoleFox
0e54d71e15 Add validation to const fn CStr creation 2022-07-31 13:14:18 -05:00
Ralf Jung
c4aca2bc88
typo
Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com>
2022-07-31 09:00:49 -04:00
Yuki Okushi
9b3f49f1bd
Rollup merge of #99781 - workingjubilee:demo-string-from-cstr, r=thomcc
Use String::from_utf8_lossy in CStr demo

Fixes rust-lang/rust#99755.
2022-07-29 15:40:00 +09:00
Dylan DPC
48efd30c9d
Rollup merge of #99689 - dtolnay:write, r=Mark-Simulacrum
Revert `write!` and `writeln!` to late drop temporaries

Closes (on master, but not on beta) #99684 by reverting the `write!` and `writeln!` parts of #96455.

argument position | before<br>#94868 | after<br>#94868 | after<br>#96455 | after<br>this PR | desired<br>(unimplementable)
--- |:---:|:---:|:---:|:---:|:---:
`write!($tmp, "…", …)` | **⸺late** | **⸺late** | *early⸺* | **⸺late** | **⸺late**
`write!(…, "…", $tmp)` | **⸺late** | **⸺late** | *early⸺* | **⸺late** | *early⸺*
`writeln!($tmp, "…", …)` | **⸺late** | **⸺late** | *early⸺* | **⸺late** | **⸺late**
`writeln!(…, "…", $tmp)` | **⸺late** | **⸺late** | *early⸺* | **⸺late** | *early⸺*
`print!("…", $tmp)` | **⸺late** | **⸺late** | *early⸺* | *early⸺* | *early⸺*
`println!("…", $tmp)` | *early⸺* | **⸺late** | *early⸺* | *early⸺* | *early⸺*
`eprint!("…", $tmp)` | **⸺late** | **⸺late** | *early⸺* | *early⸺* | *early⸺*
`eprintln!("…", $tmp)` | *early⸺* | **⸺late**| *early⸺* | *early⸺* | *early⸺*
`panic!("…", $tmp)` | *early⸺* | *early⸺* | *early⸺* | *early⸺* | *early⸺*

"Late drop" refers to dropping temporaries at the nearest semicolon **outside** of the macro invocation.

"Early drop" refers to dropping temporaries inside of the macro invocation.
2022-07-28 22:14:46 +05:30
Vincenzo Palazzo
47a0a56c1d add more docs regarding ideographic numbers
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2022-07-28 15:52:18 +00:00
bors
48316dfea1 Auto merge of #99182 - RalfJung:mitigate-uninit, r=scottmcm
mem::uninitialized: mitigate many incorrect uses of this function

Alternative to https://github.com/rust-lang/rust/pull/98966: fill memory with `0x01` rather than leaving it uninit. This is definitely bitewise valid for all `bool` and nonnull types, and also those `Option<&T>` that we started putting `noundef` on. However it is still invalid for `char` and some enums, and on references the `dereferenceable` attribute is still violated, so the generated LLVM IR still has UB -- but in fewer cases, and `dereferenceable` is hopefully less likely to cause problems than clearly incorrect range annotations.

This can make using `mem::uninitialized` a lot slower, but that function has been deprecated for years and we keep telling everyone to move to `MaybeUninit` because it is basically impossible to use `mem::uninitialized` correctly. For the cases where that hasn't helped (and all the old code out there that nobody will ever update), we can at least mitigate the effect of using this API. Note that this is *not* in any way a stable guarantee -- it is still UB to call `mem::uninitialized::<bool>()`, and Miri will call it out as such.

This is somewhat similar to https://github.com/rust-lang/rust/pull/87032, which proposed to make `uninitialized` return a buffer filled with 0x00. However
- That PR also proposed to reduce the situations in which we panic, which I don't think we should do at this time.
- The 0x01 bit pattern means that nonnull requirements are satisfied, which (due to references) is the most common validity invariant.

`@5225225` I hope I am using `cfg(sanitize)` the right way; I was not sure for which ones to test here.
Cc https://github.com/rust-lang/rust/issues/66151
Fixes https://github.com/rust-lang/rust/issues/87675
2022-07-28 01:11:10 +00:00
Jack Wrenn
b78c3daad0 safe transmute: reference tracking issue
ref: https://github.com/rust-lang/rust/pull/92268#discussion_r925266769
2022-07-27 17:33:57 +00:00
Jack Wrenn
21d1ab4877 safe transmute: add rustc_on_unimplemented to BikeshedIntrinsicFrom
ref: https://github.com/rust-lang/rust/pull/92268#discussion_r925266583
2022-07-27 17:33:57 +00:00
Jack Wrenn
bc4a1dea41 Initial (incomplete) implementation of transmutability trait.
This initial implementation handles transmutations between types with specified layouts, except when references are involved.

Co-authored-by: Igor null <m1el.2027@gmail.com>
2022-07-27 17:33:56 +00:00
Guillaume Gomez
ef81fca760
Rollup merge of #94247 - saethlin:chunksmut-aliasing, r=the8472
Fix slice::ChunksMut aliasing

Fixes https://github.com/rust-lang/rust/issues/94231, details in that issue.
cc `@RalfJung`

This isn't done just yet, all the safety comments are placeholders. But otherwise, it seems to work.

I don't really like this approach though. There's a lot of unsafe code where there wasn't before, but as far as I can tell the only other way to uphold the aliasing requirement imposed by `__iterator_get_unchecked` is to use raw slices, which I think require the same amount of unsafe code. All that would do is tie the `len` and `ptr` fields together.

Oh I just looked and I'm pretty sure that `ChunksExactMut`, `RChunksMut`, and `RChunksExactMut` also need to be patched. Even more reason to put up a draft.
2022-07-27 17:55:01 +02:00
Yuki Okushi
28b44ff5d4
Rollup merge of #99704 - fee1-dead-contrib:add_self_tilde_const_trait, r=oli-obk
Add `Self: ~const Trait` to traits with `#[const_trait]`

r? `@oli-obk`
2022-07-27 19:05:33 +09:00
Ben Kimock
746afe8952 Clarify safety comments 2022-07-26 21:25:56 -04:00
Ben Kimock
e2e3a88771 Explain how *mut [T] helps, and how we rely on the check in split_at_mut 2022-07-26 18:37:00 -04:00
Jubilee Young
d48a869b9d Force the Cow into a String 2022-07-26 14:45:28 -07:00
Jubilee Young
79e0543060 Use String::from_utf8_lossy in CStr demo 2022-07-26 13:26:05 -07:00
Matthias Krüger
a739e28aea
Rollup merge of #99757 - asquared31415:patch-1, r=Dylan-DPC
Make `transmute_copy` docs read better
2022-07-26 16:57:52 +02:00
Deadbeef
a6f9826979 Add Self: ~const Trait to traits with #[const_trait] 2022-07-26 14:14:21 +00:00
asquared31415
e241d5a093
Make transmute_copy docs read better 2022-07-26 05:59:44 -04:00
Dylan DPC
deab13c681
Rollup merge of #99692 - RalfJung:too-far, r=oli-obk
interpret, ptr_offset_from: refactor and test too-far-apart check

We didn't have any tests for the "too far apart" message, and indeed that check mostly relied on the in-bounds check and was otherwise probably not entirely correct... so I rewrote that check, and it is before the in-bounds check so we can test it separately.
2022-07-26 14:26:58 +05:30
Yuki Okushi
aeca079d7e
Rollup merge of #99084 - RalfJung:write_bytes, r=thomcc
clarify how write_bytes can lead to UB due to invalid values

Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/330

Cc ``@5225225``
2022-07-26 07:14:46 +09:00
Yuki Okushi
c1647e10ad
Rollup merge of #92390 - fee1-dead-contrib:const_cmp, r=oli-obk
Constify a few `(Partial)Ord` impls

Only a few `impl`s are constified for now, as #92257 has not landed in the bootstrap compiler yet and quite a few impls would need that fix.

This unblocks #92228, which unblocks marking iterator methods as `default_method_body_is_const`.
2022-07-26 07:14:43 +09:00
Ralf Jung
58f2ede15f interpret, ptr_offset_from: refactor and test too-far-apart check 2022-07-24 19:35:40 -04:00
Ralf Jung
d10a7b1243 add miri-track-caller to some intrinsic-exposing methods 2022-07-24 14:49:33 -04:00
David Tolnay
f1ca69d245
Revert write! and writeln! to late drop temporaries 2022-07-24 11:12:00 -07:00
Deadbeef
65fca6db19 add const hack comment 2022-07-24 12:01:23 +00:00
Deadbeef
a89510e5f9 Add issue numbers 2022-07-24 12:01:22 +00:00
Deadbeef
9fc5463c18 Constify a few const (Partial)Ord impls 2022-07-24 12:01:22 +00:00
bors
35a0617248 Auto merge of #98674 - RalfJung:miri-stacktrace-pruning, r=Mark-Simulacrum
miri: prune some atomic operation and raw pointer details from stacktrace

Since Miri removes `track_caller` frames from the stacktrace, adding that attribute can help make backtraces more readable (similar to how it makes panic locations better). I made them only show up with `cfg(miri)` to make sure the extra arguments induced by `track_caller` do not cause any runtime performance trouble.

This is also testing the waters for whether the libs team is okay with having these attributes in their code, or whether you'd prefer if we find some other way to do this. If you are fine with this, we will probably want to add it to a lot more functions (all the other atomic operations, to start).

Before:
```
error: Undefined Behavior: Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
    --> /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:2594:23
     |
2594 |             SeqCst => intrinsics::atomic_load_seqcst(dst),
     |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
     |
     = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
     = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

     = note: inside `std::sync::atomic::atomic_load::<usize>` at /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:2594:23
     = note: inside `std::sync::atomic::AtomicUsize::load` at /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:1719:26
note: inside closure at ../miri/tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
    --> ../miri/tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
     |
22   |             (&*c.0).load(Ordering::SeqCst)
     |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

After:
```
error: Undefined Behavior: Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
  --> tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
   |
22 |             (&*c.0).load(Ordering::SeqCst)
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

   = note: inside closure at tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
```
2022-07-24 06:46:46 +00:00
Ralf Jung
aed5cf3f8c say some more things about how transmute is UB 2022-07-23 08:16:55 -04:00
bors
ed793d86da Auto merge of #93397 - joshtriplett:sort-floats, r=Amanieu
Add `[f32]::sort_floats` and `[f64]::sort_floats`

It's inconvenient to sort a slice or Vec of floats, compared to sorting integers. To simplify numeric code, add a convenience method to `[f32]` and `[f64]` to sort them using `sort_unstable_by` with `total_cmp`.
2022-07-23 02:47:54 +00:00
Ralf Jung
5d95a36244 do not claim that transmute is like memcpy 2022-07-22 14:51:23 -04:00
Ralf Jung
35c6dec921 adjust UnsafeCell documentation 2022-07-22 14:25:41 -04:00
bors
41419e7036 Auto merge of #99491 - workingjubilee:sync-psimd, r=workingjubilee
Sync in portable-simd subtree

r? `@ghost`
2022-07-22 09:48:00 +00:00
Dylan DPC
5df3b98321
Rollup merge of #99579 - CleanCut:expect-warning, r=joshtriplett
Add same warning to Result::expect as Result::unwrap

I was reading a recent blog post by Jimmy Hartzell and [he noted](https://www.thecodedmessage.com/posts/2022-07-14-programming-unwrap/#context):

> I will however note that the documentation of `unwrap` comes with [a warning not to use it](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap). The warning is framed in terms of the fact that `unwrap` may panic, but the [documentation of `expect`](https://doc.rust-lang.org/std/result/enum.Result.html#method.expect), where this is equally true, does not come with such a warning.

It _is_ equally true. Let's add the same warning to `expect`. This PR is a copy-and-paste of the warning text from the docstring for `unwrap`.
2022-07-22 11:53:43 +05:30
Dylan DPC
ad31d5c6a5
Rollup merge of #98174 - Kixunil:rename_ptr_as_mut_const_to_cast, r=scottmcm
Rename `<*{mut,const} T>::as_{const,mut}` to `cast_`

This renames the methods to use the `cast_` prefix instead of `as_` to
make it more readable and avoid confusion with `<*mut T>::as_mut()`
which is `unsafe` and returns a reference.

Sorry, didn't notice ACP process exists, opened https://github.com/rust-lang/libs-team/issues/51

See #92675
2022-07-22 11:53:39 +05:30
bors
aa01891700 Auto merge of #99420 - RalfJung:vtable, r=oli-obk
make vtable pointers entirely opaque

This implements the scheme discussed in https://github.com/rust-lang/unsafe-code-guidelines/issues/338: vtable pointers should be considered entirely opaque and not even readable by Rust code, similar to function pointers.

- We have a new kind of `GlobalAlloc` that symbolically refers to a vtable.
- Miri uses that kind of allocation when generating a vtable.
- The codegen backends, upon encountering such an allocation, call `vtable_allocation` to obtain an actually dataful allocation for this vtable.
- We need new intrinsics to obtain the size and align from a vtable (for some `ptr::metadata` APIs), since direct accesses are UB now.

I had to touch quite a bit of code that I am not very familiar with, so some of this might not make much sense...
r? `@oli-obk`
2022-07-22 01:33:49 +00:00
Nathan Stocks
7ba0be832a add same warning to Result::expect as Result::unwrap 2022-07-21 18:15:24 -06:00
Matthias Krüger
9610c71b1e
Rollup merge of #99454 - benluelo:control-flow/continue-combinators, r=scottmcm
Add map_continue and continue_value combinators to ControlFlow

As suggested in this comment: https://github.com/rust-lang/rust/issues/75744#issuecomment-1188549494

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

r? ``````@scottmcm``````
2022-07-21 18:42:04 +02:00
Martin Habovstiak
eb5acc9b9b Rename <*{mut,const} T>::as_{const,mut} to cast_
This renames the methods to use the `cast_` prefix instead of `as_` to
make it more readable and avoid confusion with `<*mut T>::as_mut()`
which is `unsafe` and returns a reference.

See #92675
2022-07-21 18:30:05 +02:00
Jubilee Young
f8aa494c69 Introduce core::simd trait imports in tests 2022-07-20 18:08:20 -07:00
Bruce A. MacNaughton
5d048eb69d add #inline 2022-07-20 16:13:54 -07:00
Ralf Jung
0318f07bdd various nits from review 2022-07-20 17:12:08 -04:00
Ralf Jung
114da84996 use extern type for extra opaqueness 2022-07-20 17:12:07 -04:00
Ralf Jung
5e840c5c8c incorporate some review feedback 2022-07-20 17:12:07 -04:00
Ralf Jung
8affef2ccb add intrinsic to access vtable size and align 2022-07-20 17:12:07 -04:00
Ralf Jung
13877a965d prune raw pointer read and write methods from Miri backtraces 2022-07-20 16:42:20 -04:00
Ralf Jung
2b269cad43 miri: prune some atomic operation details from stacktrace 2022-07-20 16:34:24 -04:00
benluelo
1993a5f7a8
Add map_continue and continue_value combinators to ControlFlow
Fix type error

Fix continue_value doc comment
2022-07-20 16:32:09 -04:00
Ralf Jung
2d1c683112
fix typo
Co-authored-by: Marco Colombo <mar.colombo13@gmail.com>
2022-07-20 10:39:21 -04:00
Ralf Jung
5848c27c79 make raw_eq precondition more restrictive 2022-07-20 10:22:16 -04:00
Dylan DPC
feebc5f4d5
Rollup merge of #99452 - Stargateur:fix/typo, r=JohnTitor
int_macros was only using to_xe_bytes_doc and not from_xe_bytes_doc

typo in doc [here](https://doc.rust-lang.org/std/primitive.isize.html#method.from_ne_bytes) "returns" => "takes"

`@rustbot` label +T-rustdoc
2022-07-20 11:29:40 +05:30
Bruce A. MacNaughton
e5d4de3912 generated code 2022-07-19 18:03:33 -07:00
bors
9a7b7d5e50 Auto merge of #98180 - notriddle:notriddle/rustdoc-fn, r=petrochenkov,GuillaumeGomez
Improve the function pointer docs

This is #97842 but for function pointers instead of tuples. The concept is basically the same.

* Reduce duplicate impls; show `fn (T₁, T₂, …, Tₙ)` and include a sentence saying that there exists up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.

https://notriddle.com/notriddle-rustdoc-test/std/primitive.fn.html
2022-07-19 19:36:57 +00:00
Michael Howell
ddb5a2638a Use T for all the function primitive docs lists 2022-07-19 08:52:25 -07:00
Michael Howell
5271e32c46 Improve the function pointer docs
* Reduce duplicate impls; show only the `fn (T)` and include a sentence
  saying that there exists up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.
2022-07-19 08:52:24 -07:00
bors
a289cfcfb3 Auto merge of #99462 - matthiaskrgr:rollup-ihhwaru, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #98028 (Add E0790 as more specific variant of E0283)
 - #99384 (use body's param-env when checking if type needs drop)
 - #99401 (Avoid `Symbol` to `&str` conversions)
 - #99419 (Stabilize `core::task::ready!`)
 - #99435 (Revert "Stabilize $$ in Rust 1.63.0")
 - #99438 (Improve suggestions for `NonZeroT` <- `T` coercion error)
 - #99441 (Update mdbook)
 - #99453 (⬆️ rust-analyzer)
 - #99457 (use `par_for_each_in` in `par_body_owners` and `collect_crate_mono_items`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-07-19 13:49:56 +00:00
Matthias Krüger
e6a100baa2
Rollup merge of #99438 - WaffleLapkin:dont_wrap_in_non_zero, r=compiler-errors
Improve suggestions for `NonZeroT` <- `T` coercion error

Currently, when encountering a type mismatch error with `NonZeroT` and `T` (for example `NonZeroU8` and `u8`) we errorneusly suggest wrapping expression in `NonZeroT`:
```text
error[E0308]: mismatched types
 --> ./t.rs:7:35
  |
7 |     let _: std::num::NonZeroU64 = 1;
  |            --------------------   ^ expected struct `NonZeroU64`, found integer
  |            |
  |            expected due to this
  |
help: try wrapping the expression in `std::num::NonZeroU64`
  |
7 |     let _: std::num::NonZeroU64 = std::num::NonZeroU64(1);
  |                                   +++++++++++++++++++++ +
```

I've removed this suggestion and added suggestions to call `new` (for `Option<NonZeroT>` <- `T` case) or `new` and `unwrap` (for `NonZeroT` <- `T` case):

```text
error[E0308]: mismatched types
 --> ./t.rs:7:35
  |
7 |     let _: std::num::NonZeroU64 = 1;
  |            --------------------   ^ expected struct `NonZeroU64`, found integer
  |            |
  |            expected due to this
  |
help: Consider calling `NonZeroU64::new`
  |
7 |     let _: std::num::NonZeroU64 = NonZeroU64::new(1).unwrap();
  |                                   ++++++++++++++++ ++++++++++

error[E0308]: mismatched types
 --> ./t.rs:8:43
  |
8 |     let _: Option<std::num::NonZeroU64> = 1;
  |            ----------------------------   ^ expected enum `Option`, found integer
  |            |
  |            expected due to this
  |
  = note: expected enum `Option<NonZeroU64>`
             found type `{integer}`
help: Consider calling `NonZeroU64::new`
  |
8 |     let _: Option<std::num::NonZeroU64> = NonZeroU64::new(1);
  |                                           ++++++++++++++++ +
```

r? `@compiler-errors`
2022-07-19 13:30:49 +02:00
Matthias Krüger
7d754976c4
Rollup merge of #99419 - yoshuawuyts:stabilize-task-ready, r=Mark-Simulacrum
Stabilize `core::task::ready!`

This stabilizes `core::task::ready!` for Rust 1.64. The FCP for stabilization was just completed here https://github.com/rust-lang/rust/issues/70922#issuecomment-1186231855. Thanks!

Closes #70922

cc/ ``@rust-lang/libs-api``
2022-07-19 13:30:47 +02:00
bors
8bd12e8cca Auto merge of #98912 - nrc:provider-it, r=yaahc
core::any: replace some generic types with impl Trait

This gives a cleaner API since the caller only specifies the concrete type they usually want to.

r? `@yaahc`
2022-07-19 11:28:20 +00:00
Antoine PLASKOWSKI
94f633b002 int_macros was only using to_xe_bytes_doc and not from_xe_bytes_doc 2022-07-19 08:32:08 +02:00
Dylan DPC
e301cd39ad
Rollup merge of #99434 - timvermeulen:skip_next_non_fused, r=scottmcm
Fix `Skip::next` for non-fused inner iterators

`iter.skip(n).next()` will currently call `nth` and `next` in succession on `iter`, without checking whether `nth` exhausts the iterator. Using `?` to propagate a `None` value returned by `nth` avoids this.
2022-07-19 11:38:58 +05:30
Dylan DPC
9f6a2fde34
Rollup merge of #99335 - Dav1dde:fromstr-docs, r=JohnTitor
Use split_once in FromStr docs

Current implementation:

```rust
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
                                 .split(',')
                                 .collect();

        let x_fromstr = coords[0].parse::<i32>()?;
        let y_fromstr = coords[1].parse::<i32>()?;

        Ok(Point { x: x_fromstr, y: y_fromstr })
    }
```

Creating the vector is not necessary, `split_once` does the job better.

Alternatively we could also remove `trim_matches` with `strip_prefix` and `strip_suffix`:

```rust
        let (x, y) = s
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .and_then(|s| s.split_once(','))
            .unwrap();
```

The question is how much 'correctness' is too much and distracts from the example. In a real implementation you would also not unwrap (or originally access the vector without bounds checks), but implementing a custom Error and adding a `From<ParseIntError>` and implementing the `Error` trait adds a lot of code to the example which is not relevant to the `FromStr` trait.
2022-07-19 11:38:53 +05:30