Commit Graph

7368 Commits

Author SHA1 Message Date
Dylan DPC
8bfc03fde0
Rollup merge of #95098 - shepmaster:vec-from-array-ref, r=dtolnay
impl From<&[T; N]> and From<&mut [T; N]> for Vec<T>

I really wanted to write:

```rust
fn example(a: impl Into<Vec<u8>>) {}

fn main() {
    example(b"raw");
}
```
2022-03-28 04:12:11 +02:00
Dylan DPC
d88c03c0f1
Rollup merge of #95016 - janpaul123:patch-1, r=dtolnay
Docs: make Vec::from_raw_parts documentation less strict

This is my first PR; be gentle!

In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters.

Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too.

Let me know what you think! :)
2022-03-28 04:12:10 +02:00
Dylan DPC
6ed1a67b38
Rollup merge of #93755 - ChayimFriedman2:allow-comparing-vecs-with-different-allocators, r=dtolnay
Allow comparing `Vec`s with different allocators using `==`

See https://stackoverflow.com/q/71021633/7884305.

I did not changed the `PartialOrd` impl too because it was not generic already (didn't support `Vec<T> <=> Vec<U> where T: PartialOrd<U>`).

Does it needs tests?

I don't think this will hurt type inference much because the default allocator is usually not inferred (`new()` specifies it directly, and even with other allocators, you pass the allocator to `new_in()` so the compiler usually knows the type).

I think this requires FCP since the impls are already stable.
2022-03-28 04:12:10 +02:00
Dylan DPC
9412316ac3
Rollup merge of #88375 - joshlf:patch-3, r=dtolnay
Clarify that ManuallyDrop<T> has same layout as T

This PR implements the documentation change under discussion in https://github.com/rust-lang/unsafe-code-guidelines/issues/302. It should not be approved or merged until the discussion there is resolved.
2022-03-28 04:12:09 +02:00
Eric Huss
182d4b32d5 Update target_has_atomic documentation for stabilization 2022-03-27 15:13:17 -07:00
Dylan DPC
eca2531155
Rollup merge of #95368 - lopopolo:lopopolo/string-try-reserve-exact-doc-typo, r=Dylan-DPC
Fix typo in `String::try_reserve_exact` docs

Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`,
it looks like this doc comment is intending to refer to the currently-being-documented
function.
2022-03-27 22:51:42 +02:00
Ryan Lopopolo
1ba885113a
Fix typo in String::try_reserve_exact docs
Copying the pattern from `Vec::try_reserve_exact` and `String::try_reserve`,
it looks like this doc comment is intending to refer to the currently-being-documented
function.
2022-03-27 06:53:55 -07:00
David Tolnay
2ac9efbe95
Debug print char 0 as '\0' rather than '\u{0}' 2022-03-27 04:49:10 -07:00
David Tolnay
333756f1c5
Bump const_ptr_offset stabilization to 1.61 2022-03-26 21:15:16 -07:00
Jörn Horstmann
d9a438dc73 Add another assertion without into_iter 2022-03-25 16:57:59 +01:00
Jörn Horstmann
4b53f563bd Add a test verifying the number of drop calls 2022-03-25 13:28:19 +01:00
Jörn Horstmann
d14c0d2acb
Use ManuallyDrop::take instead of into_inner
Co-authored-by: Daniel Henry-Mantilla <daniel.henry.mantilla@gmail.com>
2022-03-25 13:27:18 +01:00
Jörn Horstmann
0cf606177e Fix double drop of allocator in IntoIter impl of Vec 2022-03-25 11:39:11 +01:00
Martin Pool
93e9f5e966 Document Linux kernel handoff in std::io::copy and std::fs::copy 2022-03-24 21:44:39 -07:00
Dylan DPC
3716c4275f
Rollup merge of #95276 - FoseFx:clippy_trim_split_whitespace, r=flip1995
add diagnostic items for clippy's `trim_split_whitespace`

Adding the following diagnostic items:
 * str_split_whitespace,
 * str_trim,
 * str_trim_start,
 * str_trim_end

They are needed for https://github.com/rust-lang/rust-clippy/pull/8575

r? `@flip1995`
2022-03-25 01:34:32 +01:00
bors
4b133a7e27 Auto merge of #94517 - aDotInTheVoid:inline_wrapping_next_power_two, r=yaahc
Mark `uint::wrapping_next_power_of_two` as `#[inline]`

This brings it in line with `next_power_of_two` and `checked_next_power_of_two`

https://godbolt.org/z/Tr18GnqKj

<details>
<summary> Output as of `rustc 1.61.0-nightly (4ce374923 2022-02-28)` </summary>

```asm
example::npot:
        lea     eax, [rdi - 1]
        movzx   eax, al
        lzcnt   ecx, eax
        add     ecx, -24
        mov     al, -1
        shr     al, cl
        inc     al
        cmp     dil, 2
        movzx   ecx, al
        mov     eax, 1
        cmovae  eax, ecx
        ret

example::cnpot:
        lea     eax, [rdi - 1]
        movzx   eax, al
        lzcnt   ecx, eax
        add     ecx, -24
        mov     al, -1
        shr     al, cl
        xor     ecx, ecx
        cmp     dil, 2
        movzx   edx, al
        cmovb   edx, ecx
        inc     dl
        setne   al
        ret

example::wrapping_next_power_of_two:
        jmp     qword ptr [rip + _ZN4core3num20_$LT$impl$u20$u8$GT$26wrapping_next_power_of_two17hd879a85055735264E@GOTPCREL]
```

</details>
2022-03-24 17:32:40 +00:00
Max Baumann
64ad96dd9a
add diagnostic items for clippy's 2022-03-24 18:18:44 +01:00
Mara Bos
c9ae3fe68f Explicitly use CLOCK_MONOTONIC in futex_wait.
Instant might be changed to use CLOCK_BOOTTIME at some point.
2022-03-24 11:11:31 +01:00
Mara Bos
23badeb4cb Make Timespec available in sys::unix. 2022-03-24 11:11:03 +01:00
Mara Bos
87299298d9 Use FUTEX_WAIT_BITSET rather than FUTEX_WAIT on Linux. 2022-03-24 09:51:48 +01:00
bors
6970f88db3 Auto merge of #87667 - the8472:document-in-place-iter, r=yaahc
add module-level documentation for vec's in-place iteration

As requested in the last libs team meeting and during previous reviews.

Feel free to point out any gaps you encounter, after all non-obvious things may with hindsight seem obvious to me.

r? `@yaahc`

CC `@steffahn`
2022-03-24 01:43:21 +00:00
Thom Chiovoloni
09d83e292d
Add a compile_fail doctest to check that io::Error: !UnwindSafe 2022-03-23 17:29:19 -07:00
Thom Chiovoloni
b898ad499f
Ensure io::Error's bitpacked repr doesn't accidentally impl UnwindSafe 2022-03-23 17:12:47 -07:00
The 8472
29e29ce65d fix some links, clarify documentation based on review feedback 2022-03-23 20:57:49 +01:00
Andreas Molzer
d489ea777d Refactor set_ptr_value as with_metadata_of
By reversing the arguments we achieve several clarifications:

- The function closely resembles `cast` but with an argument to
  initialized the metadata. This is easier to teach and answers an long
  outstanding question that had restricted cast to `Sized` targets
  initially. See multiples reviews of
  <https://github.com/rust-lang/rust/pull/47631>
- The 'object identity', in the form or provenance, is now preserved
  from the call receiver to the result. This helps explain the method as
  a builder-style, instead of some kind of setter that would modify
  something in-place. Ensuring that the result has the identity of the
  `self` argument is also beneficial for an intuition of effects.
- An outstanding concern, 'Correct argument type', is avoided by not
  committing to any specific argument type. This is consistent with cast
  which does not require its receiver to be a raw address.
2022-03-23 19:59:37 +01:00
bors
9280445570 Auto merge of #94901 - fee1-dead:destructable, r=oli-obk
Rename `~const Drop` to `~const Destruct`

r? `@oli-obk`

Completely switching to `~const Destructible` would be rather complicated, so it seems best to add it for now and wait for it to be backported to beta in the next release.

The rationale is to prevent complications such as #92149 and #94803 by introducing an entirely new trait. And `~const Destructible` reads a bit better than `~const Drop`. Name Bikesheddable.
2022-03-23 14:04:38 +00:00
Mara Bos
da4ef044c1 Spin before blocking in Mutex::lock. 2022-03-23 14:58:44 +01:00
Mara Bos
10b6f33508 Update tests. 2022-03-23 14:58:44 +01:00
Mara Bos
7f26adeac1 Replace Linux Mutex and Condvar with futex based ones. 2022-03-23 14:58:44 +01:00
Mara Bos
73d63488e4 Add futex_wake_all. 2022-03-23 14:53:59 +01:00
Mara Bos
4fbd71c943 Return timeout status in futex_wait. 2022-03-23 14:53:59 +01:00
bors
c99b42cf14 Auto merge of #95235 - asquared31415:ptr_eq_typo, r=Dylan-DPC
Fix `core::ptr::guaranteed_eq` and `guaranteed_ne` docs typo
2022-03-23 11:21:04 +00:00
asquared31415
0b81628aba ptr::guaranteed_eq doc typo 2022-03-23 04:51:59 -04:00
bors
36748cf814 Auto merge of #95173 - m-ou-se:sys-locks-module, r=dtolnay
Move std::sys::{mutex, condvar, rwlock} to std::sys::locks.

This cleans up the the std::sys modules a bit by putting the locks in a single module called `locks` rather than spread over the three modules `mutex`, `condvar`, and `rwlock`. This makes it easier to organise lock implementations, which helps with https://github.com/rust-lang/rust/issues/93740.
2022-03-23 06:01:48 +00:00
bors
7b0bf9efc9 Auto merge of #95223 - Dylan-DPC:rollup-idpb7ka, r=Dylan-DPC
Rollup of 6 pull requests

Successful merges:

 - #91608 (Fold aarch64 feature +fp into +neon)
 - #92955 (add perf side effect docs to `Iterator::cloned()`)
 - #94713 (Add u16::is_utf16_surrogate)
 - #95212 (Replace `this.clone()` with `this.create_snapshot_for_diagnostic()`)
 - #95219 (Modernize `alloc-no-oom-handling` test)
 - #95222 (interpret/validity: improve clarity)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-03-23 03:31:20 +00:00
Dylan DPC
25acd9331e
Rollup merge of #94713 - clarfonthey:is_char_surrogate, r=scottmcm
Add u16::is_utf16_surrogate

Right now, there are methods in the standard library for encoding and decoding UTF-16, but at least for the moment, there aren't any methods specifically for `u16` to help work with UTF-16 data. Since the full logic already exists, this wouldn't really add any code, just expose what's already there.

This method in particular is useful for working with the data returned by Windows `OsStrExt::encode_wide`. Initially, I was planning to also offer a `TryFrom<u16> for char`, but decided against it for now. There is plenty of code in rustc that could be rewritten to use this method, but I only checked within the standard library to replace them.

I think that offering more UTF-16-related methods to u16 would be useful, but I think this one is a good start. For example, one useful method might be `u16::is_pattern_whitespace`, which would check if something is the Unicode `Pattern_Whitespace` category. We can get away with this because all of the `Pattern_Whitespace` characters are in the basic multilingual plane, and hence we don't need to check for surrogates.
2022-03-23 03:05:31 +01:00
Dylan DPC
0e86cabdce
Rollup merge of #92955 - llogiq:cloned-side-effect-doc, r=yaahc
add perf side effect docs to `Iterator::cloned()`

Now that #90209 has been closed, as the current state of affairs is neither here nor there, this at least adds a paragraph + example on what to expect performance-wise and how to deal with it to the .cloned() docs.

cc `@the8472`
2022-03-23 03:05:28 +01:00
Dylan DPC
67d6cc6ef3
Rollup merge of #91608 - workingjubilee:fold-neon-fp, r=nagisa,Amanieu
Fold aarch64 feature +fp into +neon

Arm's FEAT_FP and Feat_AdvSIMD describe the same thing on AArch64:
The Neon unit, which handles both floating point and SIMD instructions.
Moreover, a configuration for AArch64 must include both or neither.
Arm says "entirely proprietary" toolchains may omit floating point:
https://developer.arm.com/documentation/102374/0101/Data-processing---floating-point
In the Programmer's Guide for Armv8-A, Arm says AArch64 can have
both FP and Neon or neither in custom implementations:
https://developer.arm.com/documentation/den0024/a/AArch64-Floating-point-and-NEON

In "Bare metal boot code for Armv8-A", enabling Neon and FP
is just disabling the same trap flag:
https://developer.arm.com/documentation/dai0527/a

In an unlikely future where "Neon and FP" become unrelated,
we can add "[+-]fp" as its own feature flag.
Until then, we can simplify programming with Rust on AArch64 by
folding both into "[+-]neon", which is valid as it supersets both.

"[+-]neon" is retained for niche uses such as firmware, kernels,
"I just hate floats", and so on.

I am... pretty sure no one is relying on this.

An argument could be made that, as we are not an "entirely proprietary" toolchain, we should not support AArch64 without floats at all. I think that's a bit excessive. However, I want to recognize the intent: programming for AArch64 should be simplified where possible. For x86-64, programmers regularly set up illegal feature configurations because it's hard to understand them, see https://github.com/rust-lang/rust/issues/89586. And per the above notes, plus the discussion in https://github.com/rust-lang/rust/issues/86941, there should be no real use cases for leaving these features split: the two should in fact always go together.

- Fixes rust-lang/rust#95002.
- Fixes rust-lang/rust#95064.
- Fixes rust-lang/rust#95122.
2022-03-23 03:05:28 +01:00
bors
2b50739b49 Auto merge of #95088 - bjorn3:fix_test_variadic_fnptr, r=dtolnay
Don't declare test_variadic_fnptr with two conflicting signatures

It is UB for LLVM and results in a compile error for Cranelift.

cc https://github.com/bjorn3/rustc_codegen_cranelift/issues/806
Fixes https://github.com/rust-lang/rust/issues/66690
2022-03-23 00:50:33 +00:00
Jubilee Young
b807d5970b Fold aarch64 feature +fp into +neon
Arm's FEAT_FP and Feat_AdvSIMD describe the same thing on AArch64:
The Neon unit, which handles both floating point and SIMD instructions.
Moreover, a configuration for AArch64 must include both or neither.
Arm says "entirely proprietary" toolchains may omit floating point:
https://developer.arm.com/documentation/102374/0101/Data-processing---floating-point
In the Programmer's Guide for Armv8-A, Arm says AArch64 can have
both FP and Neon or neither in custom implementations:
https://developer.arm.com/documentation/den0024/a/AArch64-Floating-point-and-NEON

In "Bare metal boot code for Armv8-A", enabling Neon and FP
is just disabling the same trap flag:
https://developer.arm.com/documentation/dai0527/a

In an unlikely future where "Neon and FP" become unrelated,
we can add "[+-]fp" as its own feature flag.
Until then, we can simplify programming with Rust on AArch64 by
folding both into "[+-]neon", which is valid as it supersets both.

"[+-]neon" is retained for niche uses such as firmware, kernels,
"I just hate floats", and so on.
2022-03-22 15:14:33 -07:00
bjorn3
4af755baf5 Limit test_variadic_fnptr to unix 2022-03-22 22:27:13 +01:00
Andre Bogus
1fb43f6662 add perf side effect docs to Iterator::cloned() 2022-03-22 19:07:23 +01:00
Mara Bos
733153f2e5 Move std::sys::{mutex, condvar, rwlock} to std::sys::locks. 2022-03-22 18:19:47 +01:00
ZHANGWENTAI
71e34231e0 add some fix
Signed-off-by: ZHANGWENTAI <2092913428@qq.com>
2022-03-22 23:33:08 +08:00
ZHANGWENTAI
161b01a9ac fix the lint problem
Signed-off-by: ZHANGWENTAI <2092913428@qq.com>
2022-03-22 23:10:00 +08:00
ZHANGWENTAI
6e971a8bc2 update Termination trait docs 2022-03-22 22:37:17 +08:00
bors
3ea44938e2 Auto merge of #95107 - r00ster91:fmt, r=joshtriplett
Improve formatting in macro

CC `@dtolnay`
2022-03-22 08:47:16 +00:00
bors
b9c4067417 Auto merge of #95158 - sunfishcode:sunfishcode/windows-8, r=joshtriplett
Preserve the Windows `GetLastError` error in `HandleOrInvalid`.

In the `TryFrom<HandleOrInvalid> for OwnedHandle` and
`TryFrom<HandleOrNull> for OwnedHandle` implemenations, `forget` the
owned handle on the error path, to avoid calling `CloseHandle` on an
invalid handle. It's harmless, except that it may overwrite the
thread's `GetLastError` error.

r? `@joshtriplett`
2022-03-22 05:48:49 +00:00
ltdk
d5803678c1 Add u16::is_utf16_surrogate 2022-03-21 22:51:32 -04:00
The 8472
7549cfa599 rename internal helper trait AsIntoIter to AsVecIntoIter 2022-03-22 00:02:54 +01:00
Mara Bos
2437422622 Stabilize Stdin::lines. 2022-03-21 22:57:31 +01:00
The8472
a1a602adde add module-level documentation for vec's in-place iteration 2022-03-21 22:29:38 +01:00
The8472
79b43b35be move AsIntoIter helper trait and mark it as unsafe 2022-03-21 22:29:38 +01:00
The8472
47a7a07a8b rename module to better reflect its purpose 2022-03-21 22:29:38 +01:00
Mara Bos
ac6996345d Move pthread locks to own module. 2022-03-21 15:51:25 +01:00
Deadbeef
1f3ee7f32e
Rename ~const Drop to ~const Destruct 2022-03-21 17:04:03 +11:00
Deadbeef
4df2a28aee
Add Destructible for replacing ~const Drop 2022-03-21 17:04:02 +11:00
Dan Gohman
6c407d0592 Add a testcase. 2022-03-20 15:56:25 -07:00
Dan Gohman
95e1702284 Preserve the Windows GetLastError error in HandleOrInvalid.
In the `TryFrom<HandleOrInvalid> for OwnedHandle` and
`TryFrom<HandleOrNull> for OwnedHandle` implemenations, `forget` the
owned handle on the error path, to avoid calling `CloseHandle` on an
invalid handle. It's harmless, except that it may overwrite the
thread's `GetLastError` error.
2022-03-20 15:37:31 -07:00
bjorn3
56939ffe7d Don't declare test_variadic_fnptr with two conflicting signatures
It is UB for LLVM and results in a compile error for Cranelift
2022-03-20 21:09:35 +01:00
Matthias Krüger
3c02b5192e
Rollup merge of #95114 - ChrisDenton:symlink-test, r=the8472
Skip a test if symlink creation is not possible

If someone running tests on Windows does not have Developer Mode enabled then creating symlinks will fail which in turn would cause this test to fail. This can be a stumbling block for contributors.
2022-03-20 20:42:43 +01:00
bors
c7ce69faf2 Auto merge of #92962 - frank-king:btree_entry_no_insert, r=Amanieu
BTreeMap::entry: Avoid allocating if no insertion

This PR allows the `VacantEntry` to borrow from an empty tree with no root, and to lazily allocate a new root node when the user calls `.insert(value)`.
2022-03-20 11:20:26 +00:00
Matthias Krüger
9725caf9e9
Rollup merge of #95110 - wmstack:patch-1, r=Dylan-DPC
Provide more useful documentation of conversion methods

I thought that the documentation for these methods needed to be a bit more explanatory for new users. For advanced users, the comments are relatively unnecessary. I think it would be useful to explain precisely what the method does. As a new user, when you see the `into` method, where the type is inferred, if you are new you don't even know what you convert to, because it is implicit. I believe this can help new users understand.
2022-03-20 09:15:01 +01:00
Matthias Krüger
24a7aad082
Rollup merge of #94989 - compiler-errors:stream-alias, r=Dylan-DPC
Add Stream alias for AsyncIterator

Fixes #94965
2022-03-20 09:15:00 +01:00
Matthias Krüger
acb7ed141b
Rollup merge of #94749 - RalfJung:remove-dir-all-miri, r=cuviper
remove_dir_all: use fallback implementation on Miri

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

The new implementation requires `openat`, `unlinkat`, and `fdopendir`. These cannot easily be shimmed in Miri since libstd does not expose APIs corresponding to them. So for now it is probably easiest to just use the fallback code in Miri. Nobody should run Miri as root anyway...
2022-03-20 09:14:58 +01:00
Jubilee Young
5a25e228eb Stabilize thread::is_finished 2022-03-19 19:53:26 -07:00
bors
f2661cfe34 Auto merge of #94372 - erikdesjardins:asrefinl, r=dtolnay
Add #[inline] to trivial AsRef/AsMut impls

These appeared uninlined in some perf runs, but they're trivial.

r? `@ghost`
2022-03-19 22:32:28 +00:00
Chris Denton
68c03cd386
Skip a test if symlink creation is not possible 2022-03-19 15:09:36 +00:00
Dylan DPC
6a73024661
Rollup merge of #94991 - CAD97:const-weak-new, r=dtolnay
Make Weak::new const

Simple enough. This is const creation of an allocating container, but no actual allocation is done, because it's defined to.
2022-03-19 14:50:25 +01:00
Dylan DPC
d1ef570a2f
Rollup merge of #94650 - ChrisDenton:windows-absolute-fix, r=dtolnay
Relax tests for Windows dos device names

Windows 11 no longer turn paths ending with dos device names into device paths.

E.g. `C:\path\to\COM1.txt` used to get turned into `\\.\COM1`. Whereas now this path is left as is.

Note though that if the given path is an exact (case-insensitive) match for the string `COM1` then it'll still be converted to `\\.\COM1`.
2022-03-19 14:50:24 +01:00
Dylan DPC
3545003b29
Rollup merge of #93858 - krallin:process-process_group, r=dtolnay
Add a `process_group` method to UNIX `CommandExt`

- Tracking issue: #93857
- RFC: https://github.com/rust-lang/rfcs/pull/3228

Add a `process_group` method to `std::os::unix::process::CommandExt` that
allows setting the process group id (i.e. calling `setpgid`) in the child, thus
enabling users to set process groups while leveraging the `posix_spawn` fast
path.
2022-03-19 14:50:24 +01:00
r00ster91
7e3fd5957b Improve formatting in macro 2022-03-19 09:44:52 +01:00
Waleed Dahshan
edee46e257
Provide more useful documentation of conversion methods
I thought that the documentation for these methods needed to be a bit more explanatory for new users. For advanced users, the comments are relatively unnecessary. I think it would be useful to explain precisely what the method does. As a new user, when you see the `into` method, where the type is inferred, if you are new you don't even know what you convert to, because it is implicit. I believe this can help new users understand.
2022-03-19 18:52:30 +11:00
Dylan DPC
30b4182fa7
Rollup merge of #94984 - ericseppanen:cstr_from_bytes, r=Mark-Simulacrum
add `CStr` method that accepts any slice containing a nul-terminated string

I haven't created an issue (tracking or otherwise) for this yet; apologies if my approach isn't correct. This is my first code contribution.

This change adds a member fn that converts a slice into a `CStr`; it is intended to be safer than `from_ptr` (which is unsafe and may read out of bounds), and more useful than `from_bytes_with_nul` (which requires that the caller already know where the nul byte is).

The reason I find this useful is for situations like this:
```rust
let mut buffer = [0u8; 32];
unsafe {
    some_c_function(buffer.as_mut_ptr(), buffer.len());
}
let result = CStr::from_bytes_with_nul(&buffer).unwrap();
```

This code above returns an error with `kind = InteriorNul`, because `from_bytes_with_nul` expects that the caller has passed in a slice with the NUL byte at the end of the slice. But if I just got back a nul-terminated string from some FFI function, I probably don't know where the NUL byte is.

I would wish for a `CStr` constructor with the following properties:
- Accept `&[u8]` as input
- Scan for the first NUL byte and return the `CStr` that spans the correct sub-slice (see [future note below](https://github.com/rust-lang/rust/pull/94984#issuecomment-1070754281)).
- Return an error if no NUL byte is found within the input slice

I asked on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/CStr.20from.20.26.5Bu8.5D.20without.20knowing.20the.20NUL.20location.3F) whether this sounded like a good idea, and got a couple of positive-sounding responses from ``@joshtriplett`` and ``@AzureMarker.``

This is my first draft, so feedback is welcome.

A few issues that definitely need feedback:

1. Naming. ``@joshtriplett`` called this `from_bytes_with_internal_nul` on Zulip, but after staring at all of the available methods, I believe that this function is probably what end users want (rather than the existing fn `from_bytes_with_nul`). Giving it a simpler name (**`from_bytes`**) implies that this should be their first choice.
2. Should I add a similar method on `CString` that accepts `Vec<u8>`? I'd assume the answer is probably yes, but I figured I'd try to get early feedback before making this change bigger.
3. What should the error type look like? I made a unit struct since `CStr::from_bytes` can only fail in one obvious way, but if I need to do this for `CString` as well then that one may want to return `FromVecWithNulError`. And maybe that should dictate the shape of the `CStr` error type also?

Also, cc ``@poliorcetics`` who wrote #73139 containing similar fns.
2022-03-19 02:02:02 +01:00
Dylan DPC
463e516b0c
Rollup merge of #93692 - mfrw:mfrw/document-keyword-in, r=dtolnay
keyword_docs: document use of `in` with `pub` keyword

Signed-off-by: Muhammad Falak R Wani <falakreyaz@gmail.com>

Fixes: #93609
2022-03-19 02:02:02 +01:00
Dylan DPC
fe55eee9a5
Rollup merge of #93263 - sunfishcode:sunfishcode/detatched-console-handle, r=dtolnay
Consistently present absent stdio handles on Windows as NULL handles.

This addresses #90964 by making the std API consistent about presenting
absent stdio handles on Windows as NULL handles. Stdio handles may be
absent due to `#![windows_subsystem = "windows"]`, due to the console
being detached, or due to a child process having been launched from a
parent where stdio handles are absent.

Specifically, this fixes the case of child processes of parents with absent
stdio, which previously ended up with `stdin().as_raw_handle()` returning
`INVALID_HANDLE_VALUE`, which was surprising, and which overlapped with an
unrelated valid handle value. With this patch, `stdin().as_raw_handle()`
now returns null in these situation, which is consistent with what it
does in the parent process.

And, document this in the "Windows Portability Considerations" sections of
the relevant documentation.
2022-03-19 02:02:01 +01:00
Dylan DPC
e9f63fdf86
Rollup merge of #92663 - cuviper:generic-write-cursor, r=dtolnay
Implement `Write for Cursor<[u8; N]>`, plus `A: Allocator` cursor support

This implements `Write for Cursor<[u8; N]>`, and also adds support for generic `A: Allocator` in `Box` and `Vec` cursors.

This was inspired by a user questioning why they couldn't write a `Cursor<[u8; N]>`:
https://users.rust-lang.org/t/why-vec-and-not-u8-makes-cursor-have-write/68210

Related history:
- #27197 switched `AsRef<[u8]>` for reading and seeking
- #67415 tried to use `AsMut<[u8]>` for writing, but did not specialize `Vec`.
2022-03-19 02:02:00 +01:00
Dylan DPC
a87590e34e
Rollup merge of #92612 - atopia:update-lib-l4re, r=dtolnay
Update stdlib for the l4re target

This PR contains the work by ``@humenda`` and myself to update standard library support for the x86_64-unknown-l4re-uclibc tier 3 target, split out from  humenda/rust as requested in #85967. The changes have been rebased on current master and updated in follow up commits by myself. The publishing of the changes is authorized and preferred by the original author. To preserve attribution, when standard library changes were introduced as part of other changes to the compiler, I have kept the changes concerning the standard library and altered the commit messages as indicated. Any incompatibilities have been remedied in follow up commits, so that the PR as a whole should result in a clean update of the target.
2022-03-19 02:01:59 +01:00
Dylan DPC
ba2d5ede70
Rollup merge of #92519 - ChrisDenton:command-maybe-verbatim, r=dtolnay
Use verbatim paths for `process::Command` if necessary

In #89174, the standard library started using verbatim paths so longer paths are usable by default. However, `Command` was originally left out because of the way `CreateProcessW` was being called. This was changed as a side effect of #87704 so now `Command` paths can be converted to verbatim too (if necessary).
2022-03-19 02:01:59 +01:00
Jake Goulding
5dd702763a impl From<&[T; N]> and From<&mut [T; N]> for Vec<T> 2022-03-18 20:31:53 -04:00
CAD97
a358ad2aff Make Weak::new const 2022-03-18 17:47:36 -05:00
Eric Seppanen
d5fe4cad5a add CStr::from_bytes_until_nul
This adds a member fn that converts a slice into a CStr; it is intended
to be safer than from_ptr (which is unsafe and may read out of bounds),
and more useful than from_bytes_with_nul (which requires that the caller
already know where the nul byte is).

feature gate: cstr_from_bytes_until_nul

Also add an error type FromBytesUntilNulError for this fn.
2022-03-18 15:46:49 -07:00
David Tolnay
7d44316bcf
Bump impl Write for Cursor<[u8; N]> to 1.61 2022-03-18 15:04:37 -07:00
Matthias Krüger
9c40db22ff
Rollup merge of #95083 - danielhenrymantilla:patch-2, r=RalfJung
Document that `Option<extern "abi" fn>` discriminant elision applies for any ABI

The current phrasing was not very clear on that aspect.

r? `@RalfJung`

`@rustbot` modify labels: A-docs A-ffi
2022-03-18 21:50:50 +01:00
Matthias Krüger
c8cf9e3a8f
Rollup merge of #95058 - wcampbell0x2a:use-then-in-unix-process, r=dtolnay
Add use of bool::then in sys/unix/process

Remove `else { None }` in favor of using `bool::then()`
2022-03-18 21:50:49 +01:00
Matthias Krüger
4ead6d9dc7
Rollup merge of #95017 - zachs18:cmp_ordering_derive_eq, r=Dylan-DPC
Derive Eq for std::cmp::Ordering, instead of using manual impl.

This allows consts of type Ordering to be used in patterns, and with feature(adt_const_params) allows using `Ordering` as a const generic parameter.

Currently, `std::cmp::Ordering` implements `Eq` using a manually written `impl Eq for Ordering {}`, instead of `derive(Eq)`. This means that it does not implement `StructuralEq`.

This commit removes the manually written impl, and adds `derive(Eq)` to `Ordering`, so that it will implement `StructuralEq`.
2022-03-18 21:50:48 +01:00
Matthias Krüger
c183d4a510
Rollup merge of #94115 - scottmcm:iter-process-by-ref, r=yaahc
Let `try_collect` take advantage of `try_fold` overrides

No public API changes.

With this change, `try_collect` (#94047) is no longer going through the `impl Iterator for &mut impl Iterator`, and thus will be able to use `try_fold` overrides instead of being forced through `next` for every element.

Here's the test added, to see that it fails before this PR (once a new enough nightly is out): https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=462f2896f2fed2c238ee63ca1a7e7c56

This might as well go to the same person as my last `try_process` PR  (#93572), so
r? ``@yaahc``
2022-03-18 21:50:44 +01:00
Daniel Henry-Mantilla
156734dda0
Document that Option<extern "abi" fn> discriminant elision applies for any ABI
The current phrasing was not very clear on that aspect.
2022-03-18 18:14:34 +01:00
bors
d6f3a4ecb4 Auto merge of #88098 - Amanieu:oom_panic, r=nagisa
Implement -Z oom=panic

This PR removes the `#[rustc_allocator_nounwind]` attribute on `alloc_error_handler` which allows it to unwind with a panic instead of always aborting. This is then used to implement `-Z oom=panic` as per RFC 2116 (tracking issue #43596).

Perf and binary size tests show negligible impact.
2022-03-18 03:01:46 +00:00
wcampbell
b1f3179804 feat: Add use of bool::then in sys/unix/process
Remove else { None } in favor of using bool::then()
2022-03-17 19:12:09 -04:00
Dylan DPC
270a41c33e
Rollup merge of #94960 - codehorseman:master, r=oli-obk
Fix many spelling mistakes

Signed-off-by: codehorseman <cricis@yeah.net>
2022-03-17 22:55:05 +01:00
Dylan DPC
07121c88ad
Rollup merge of #93745 - tarcieri:stabilize-adx, r=cjgillot
Stabilize ADX target feature

This is a continuation of #60109, which noted that while the ADX intrinsics were stabilized, the corresponding target feature never was.

This PR follows the same general structure and stabilizes the ADX target feature.

See also https://github.com/rust-lang/rust/issues/44839 - tracking issue for target feature
2022-03-17 22:55:01 +01:00
Zachary S
b13b495b91 Add test for StructuralEq for std::cmp::Ordering.
Added test in library/core/tests/cmp.rs that ensures that `const`s of type `Ordering`s can be used in patterns.
2022-03-16 14:01:48 -05:00
Zachary S
ba611d55f3 Derive Eq for std::cmp::Ordering, instead of using manual impl.
This allows consts of type Ordering to be used in patterns, and (with feature(adt_const_params)) allows using Orderings as const generic parameters.
2022-03-16 11:36:31 -05:00
JP Posma
80340f62fe
Docs: make Vec::from_raw_parts documentation less strict
This is my first PR; be gentle!

In https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/2?u=janpaul123 it was suggested to me that I should make a PR to make the documentation of `Vec::from_raw_parts` less strict, since we don't require `T` to have the same size, just `size_of::<T>() * capacity` to be the same, since that is what results in `Layout::size` being the same in `dealloc`, which is really what matters.

Also in https://users.rust-lang.org/t/why-does-vec-from-raw-parts-require-same-size-and-not-same-size-capacity/73036/8?u=janpaul123 it was suggested that it's better to use `slice::from_raw_parts`, which I think is useful advise that could also be mentioned in the docs, so I added that too.

Let me know what you think! :)
2022-03-16 09:34:12 -07:00
codehorseman
01dbfb3eb2 resolve the conflict in compiler/rustc_session/src/parse.rs
Signed-off-by: codehorseman <cricis@yeah.net>
2022-03-16 20:12:30 +08:00
Michael Goulet
8a75d55514 Add Stream alias for AsyncIterator 2022-03-15 20:59:13 -07:00
Dylan DPC
0732ea2f3e
Rollup merge of #94957 - iamzhangyong:explanation-read_line, r=Dylan-DPC
Improve the explanation about the behaviour of read_line

Close issue like https://github.com/rust-lang/book/issues/2574
2022-03-16 03:34:34 +01:00
Dylan DPC
f986c7434a
Rollup merge of #94868 - dtolnay:noblock, r=Dylan-DPC
Format core and std macro rules, removing needless surrounding blocks

Many of the asserting and printing macros in `core` and `std` are written with prehistoric-looking formatting, like this:

335ffbfa54/library/std/src/macros.rs (L96-L101)

In modern Rust style this would conventionally be written as follows instead, always using braces and a trailing semicolon on the macro arms:

af53809c87/library/std/src/macros.rs (L98-L105)

Getting rid of the unneeded braces inside the expansion reduces extraneous indentation in macro-expanded code. For example:

```rust
println!("repro {}", true);
```

```rust
// before:

{
    ::std::io::_print(
        ::core::fmt::Arguments::new_v1(
            &["repro ", "\n"],
            &[::core::fmt::ArgumentV1::new_display(&true)],
        ),
    );
};
```

```rust
// after:

::std::io::_print(
    ::core::fmt::Arguments::new_v1(
        &["repro ", "\n"],
        &[::core::fmt::ArgumentV1::new_display(&true)],
    ),
);
```
2022-03-16 03:34:32 +01:00
Dylan DPC
2c06c861de
changed wording 2022-03-16 03:04:40 +01:00
Matthias Krüger
277802e99a
Rollup merge of #94947 - Dylan-DPC:fix/typos, r=oli-obk
fix typos

Rework of #94603 which got closed as I was trying to unmerge and repush.  This is a subset of changes from the original pr as I sed'd whatever typos I remembered from the original PR

thanks to `@cuishuang` for the original PR
2022-03-15 17:15:53 +01:00
zed.zy
7da07ff48b Improve the explanation about the behaviour of read_line 2022-03-15 19:37:52 +08:00
Dylan DPC
13e889986d fix typos 2022-03-15 02:00:08 +01:00
Tony Arcieri
78567df575 Stabilize ADX target feature
This is a continuation of #60109, which noted that while the ADX
intrinsics were stabilized, the corresponding target feature never was.

This PR follows the same general structure and stabilizes the ADX target
feature.
2022-03-14 18:56:39 -06:00
Matthias Krüger
0e423932f8
Rollup merge of #90621 - adamgemmell:dev/stabilise-target-feature, r=Amanieu
Stabilise `aarch64_target_feature`

This PR stabilises `aarch64_target_feature` - see https://github.com/rust-lang/rust/issues/90620
2022-03-14 17:24:56 +01:00
Thomas Orozco
b628497b7c Add a process_group method to UNIX CommandExt 2022-03-14 14:33:41 +00:00
Adam Gemmell
5a5621791f Stabilise aarch64_target_feature 2022-03-14 11:02:50 +00:00
bors
e95b10ba4a Auto merge of #94916 - matthiaskrgr:rollup-s6zedfl, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #93292 (Implement `BITS` constant for non-zero integers)
 - #94777 (Update armv7-unknown-linux-uclibceabi platform support page.)
 - #94816 (Add `Atomic*::get_mut_slice`)
 - #94844 (Reduce rustbuild bloat caused by serde_derive)
 - #94907 (Omit stdarch test crates from the rust-src component)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-03-13 20:59:29 +00:00
Matthias Krüger
8dad2d172c
Rollup merge of #94816 - WaffleLapkin:atomic_get_mut_slice, r=Mark-Simulacrum
Add `Atomic*::get_mut_slice`

This PR adds the inverse of `Atomic*::from_mut_slice` introduced in #94384 with the following API:
```rust
// core::sync::atomic

impl Atomic* {
    fn get_mut_slice(this: &mut [Self]) -> &mut [*];
}
```

cc `@cuviper`

-----

For now I've used the same tracking issue as `Atomic*::from_mut_slice`, should I open a new one?
2022-03-13 20:02:00 +01:00
Matthias Krüger
2f9bc56e5a
Rollup merge of #93292 - nvzqz:nonzero-bits, r=dtolnay
Implement `BITS` constant for non-zero integers

This adds the associated [`BITS`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.BITS) constant to `NonZero{U,I}{8,16,32,64,128,size}`.

This is useful when a type alias refers to either a regular or non-zero integer.
2022-03-13 20:01:58 +01:00
bors
21b0325c68 Auto merge of #94738 - Urgau:rustbuild-check-cfg-values, r=Mark-Simulacrum
Enable conditional checking of values in the Rust codebase

This pull-request enable conditional checking of (well known) values in the Rust codebase.

Well known values were added in https://github.com/rust-lang/rust/pull/94362. All the `target_*` values are taken from all the built-in targets which is why some extra values were needed do be added as they are not (yet ?) defined in any built-in targets.

r? `@Mark-Simulacrum`
2022-03-13 18:34:00 +00:00
Jubilee Young
2b1f249ecf Use reduce_sum in as_simd example 2022-03-12 16:43:38 -08:00
Jubilee Young
aabaf8430c Sync portable-simd to rust-lang/portable-simd@72df4c4505 2022-03-12 16:09:37 -08:00
Nikolai Vazquez
6b5acf0d40 Use Self::BITS in log2 implementation 2022-03-12 08:01:35 -05:00
Nikolai Vazquez
1d13de6867 Implement BITS constant for non-zero integers 2022-03-12 08:00:45 -05:00
David Tolnay
af53809c87
Format core and std macro rules, removing needless surrounding blocks 2022-03-11 15:26:51 -08:00
bors
2c6a29af35 Auto merge of #94860 - Dylan-DPC:rollup-n06j8h6, r=Dylan-DPC
Rollup of 7 pull requests

Successful merges:

 - #87618 (Add missing documentation for std::char types)
 - #94769 (Collapse blanket and auto-trait impls by default)
 - #94798 (`parse_tt` refactorings)
 - #94818 (Rename `IntoFuture::Future` to `IntoFuture::IntoFuture`)
 - #94827 (CTFE/Miri: detect out-of-bounds pointers in offset_from)
 - #94838 (Make float parsing docs more comprehensive)
 - #94839 (Suggest using double colon when a struct field type include single colon)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-03-11 21:44:06 +00:00
Dylan DPC
ad513548ce
Rollup merge of #94838 - antonok-edm:float-parse-docs, r=Dylan-DPC
Make float parsing docs more comprehensive

I was working on some code with some specialized restrictions on float parsing. I noticed the doc comments for `f32::from_str` and `f64::from_str` were missing several cases of valid inputs that are otherwise difficult to discover without looking at source code.

I'm not sure if the doc comments were initially intended to contain a comprehensive description of valid inputs, but I figured it's useful to include these extra cases for reference.
2022-03-11 20:29:46 +01:00
Dylan DPC
fedf70acb1
Rollup merge of #94818 - yoshuawuyts:into-future-associated-type, r=joshtriplett
Rename `IntoFuture::Future` to `IntoFuture::IntoFuture`

Ref: https://github.com/rust-lang/rust/issues/67644#issuecomment-1051401459

This renames `IntoFuture::Future` to `IntoFuture::IntoFuture`. This adds the `Into*` prefix to the associated type, similar to the [`IntoIterator::IntoIter`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#associatedtype.IntoIter) associated type. It's my mistake we didn't do so in the first place. This fixes that and brings the two closer together. Thanks!

### References
__`IntoIterator` trait def__
```rust
pub trait IntoIterator {
    type Item;
    type IntoIter: Iterator<Item = Self::Item>;
    fn into_iter(self) -> Self::IntoIter;
}
```
__`IntoFuture` trait def__
```rust
pub trait IntoFuture {
    type Output;
    type IntoFuture: Future<Output = Self::Output>; // Prior to this PR: `type Future:`
    fn into_future(self) -> Self::IntoFuture;
}
```

cc/ `@eholk` `@rust-lang/wg-async`
2022-03-11 20:29:45 +01:00
Dylan DPC
85056107fa
Rollup merge of #87618 - GuillaumeGomez:std-char-types-doc, r=jyn514,camelid
Add missing documentation for std::char types
2022-03-11 20:29:42 +01:00
bors
335ffbfa54 Auto merge of #94472 - JmPotato:use_maybeuninit_for_vecdeque, r=m-ou-se
Use MaybeUninit in VecDeque to remove the undefined behavior of slice

Signed-off-by: JmPotato <ghzpotato@gmail.com>

Ref https://github.com/rust-lang/rust/issues/74189. Adjust the code to follow the [doc.rust-lang.org/reference/behavior-considered-undefined.html](https://doc.rust-lang.org/reference/behavior-considered-undefined.html).

* Change the return type of `buffer_as_slice` from `&[T]` to `&[MaybeUninit<T>]`.
* Add some corresponding safety comments.

Benchmark results:

master 8d6f527530

```rust
test collections::vec_deque::tests::bench_pop_back_100       ... bench:          47 ns/iter (+/- 1)
test collections::vec_deque::tests::bench_pop_front_100      ... bench:          50 ns/iter (+/- 4)
test collections::vec_deque::tests::bench_push_back_100      ... bench:          69 ns/iter (+/- 10)
test collections::vec_deque::tests::bench_push_front_100     ... bench:          72 ns/iter (+/- 6)
test collections::vec_deque::tests::bench_retain_half_10000  ... bench:     145,891 ns/iter (+/- 7,975)
test collections::vec_deque::tests::bench_retain_odd_10000   ... bench:     141,647 ns/iter (+/- 3,711)
test collections::vec_deque::tests::bench_retain_whole_10000 ... bench:     120,132 ns/iter (+/- 4,078)
```

This PR

```rust
test collections::vec_deque::tests::bench_pop_back_100       ... bench:          48 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_pop_front_100      ... bench:          51 ns/iter (+/- 3)
test collections::vec_deque::tests::bench_push_back_100      ... bench:          73 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_push_front_100     ... bench:          73 ns/iter (+/- 2)
test collections::vec_deque::tests::bench_retain_half_10000  ... bench:     131,796 ns/iter (+/- 5,440)
test collections::vec_deque::tests::bench_retain_odd_10000   ... bench:     137,563 ns/iter (+/- 3,349)
test collections::vec_deque::tests::bench_retain_whole_10000 ... bench:     128,815 ns/iter (+/- 3,289)
```
2022-03-11 19:23:55 +00:00
Dylan DPC
fb3d126458
Rollup merge of #94842 - tspiteri:there-is-no-try, r=Dylan-DPC
Remove unnecessary try_opt for operations that cannot fail

As indicated in the added comments, some operation cannot overflow, so using `try_opt!` for them is unnecessary.
2022-03-11 13:38:39 +01:00
Dylan DPC
cdd6d39ecc
Rollup merge of #94776 - martingms:optimize-escape-default, r=nnethercote
Optimize ascii::escape_default

`ascii::escape_default` showed up as a hot function when compiling `deunicode-1.3.1` in `@nnethercote's` [analysis](https://hackmd.io/mxdn4U58Su-UQXwzOHpHag) of `@lqd's` [rustc-benchmarking-data](https://github.com/lqd/rustc-benchmarking-data).
After taking a look at the generated assembly it looked like a LUT-based approach could be faster for `hexify()`-ing ascii characters, so that's what this PR implements

The patch looks like it provides about a 1-2% improvement in instructions for that particular crate. This should definitely be verified with a perf run as I'm still getting used to the `rustc-perf` tooling and might easily have made an error!
2022-03-11 13:38:37 +01:00
Dylan DPC
7189fceab7
Rollup merge of #93283 - m1guelperez:master, r=Mark-Simulacrum
Fix for localized windows editions in testcase fn read_link() Issue#93211

This PR aims to fix the issue with localized windows versions that do not necessarily have the folder "Documents and settings" in English.

The idea was provided by `@the8472.` We check if the "CI" environment variable is set, then we always check for the "Documents and Settings"-folder, otherwise we check if the folder exists on the local machine, and if not we skip this assert.

Resoles #93211.
2022-03-11 13:38:36 +01:00
Antonio Yang
14daf47e0a Show ignore message in console and json output 2022-03-11 07:15:27 -05:00
Trevor Spiteri
ed10356d52 remove unnecessary try_opt for operations that cannot fail 2022-03-11 11:07:45 +01:00
Anton Lazarev
4c17217f99
make float parsing docs more comprehensive 2022-03-10 22:26:30 -08:00
Dylan DPC
f97a1c6909
Rollup merge of #94826 - allgoewer:fix-retain-documentation, r=yaahc
Improve doc wording for retain on some collections

I found the documentation wording on the various retain methods on many collections to be unusual.
I tried to invert the relation by switching `such that` with `for which` .
2022-03-11 03:32:06 +01:00
Dylan DPC
6d66020594
Rollup merge of #94765 - m-ou-se:is-some-and, r=Dylan-DPC
Rename is_{some,ok,err}_with to is_{some,ok,err}_and.

This renames `is_{some,ok,err}_with` to `is_{some,ok,err}_and`. This was discussed on the [tracking issue](https://github.com/rust-lang/rust/issues/93050).
2022-03-11 03:32:04 +01:00
Dylan DPC
ab851653a5
Rollup merge of #94356 - Thomasdezeeuw:stabilize_unix_socket_creation, r=dtolnay
Rename unix::net::SocketAddr::from_path to from_pathname and stabilize it

Stabilizes `unix_socket_creation`.

Closes https://github.com/rust-lang/rust/issues/93423
r? `@m-ou-se`
2022-03-11 03:32:03 +01:00
Dylan DPC
d58c69ae96
Rollup merge of #93293 - nvzqz:nonzero-min-max, r=joshtriplett
Implement `MIN`/`MAX` constants for non-zero integers

This adds the associated [`MIN`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MIN)/[`MAX`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.MAX) constants to `NonZero{U,I}{8,16,32,64,128,size}`, requested in #89065.

This reimplements #89077 due that PR being stagnant for 4 months. I am fine with closing this in favor of that one if the author revisits it. If so, I'd like to see that PR have the docs link to the `$Int`'s constants.
2022-03-11 03:32:02 +01:00
Maik Allgöwer
229e01d11f Improve doc wording for retain on some collections 2022-03-11 00:29:43 +01:00
Nikolai Vazquez
ecb7927050 Move note about 0 gap to signed integers
Was accidentally placed on unsigned integers, where it is not relevant.
2022-03-10 17:52:48 -05:00
Dylan DPC
3979e150cc
Rollup merge of #94790 - RalfJung:portable-simd-miri, r=Dylan-DPC
enable portable-simd doctests in Miri

With https://github.com/rust-lang/miri/pull/2013 we shouldn't need to disable these tests any more. :)
2022-03-10 23:13:01 +01:00
Dylan DPC
5a7f09d9a3
Rollup merge of #93950 - T-O-R-U-S:use-modern-formatting-for-format!-macros, r=Mark-Simulacrum
Use modern formatting for format! macros

This updates the standard library's documentation to use the new format_args syntax.
The documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).

`eprintln!("{}", e)` becomes `eprintln!("{e}")`, but `eprintln!("{}", e.kind())` remains untouched.
2022-03-10 23:12:57 +01:00
Maybe Waffle
ecf46d1074 Add Atomic*::get_mut_slice
Just as `get_mut` is the inverse of `from_mut`, `get_mut_slice` is the
inverse of `from_mut_slice`.
2022-03-11 00:31:19 +04:00
Yoshua Wuyts
3f2cb6eba1 Rename IntoFuture::Future to IntoFuture::IntoFuture 2022-03-10 20:51:52 +01:00
Matthias Krüger
af35dc2a95
Rollup merge of #94805 - oli-obk:drop_box, r=pnkfelix
Revert accidental stabilization

fixes #94804
2022-03-10 19:00:11 +01:00
Matthias Krüger
f1a677789a
Rollup merge of #94644 - m-ou-se:scoped-threads-drop-soundness, r=joshtriplett
Fix soundness issue in scoped threads.

This was discovered in https://github.com/rust-lang/rust/pull/94559#discussion_r820116323

The `scope()` function returns when all threads are finished, but I accidentally considered a thread 'finished' before dropping their panic payload or ignored return value.

So if a thread returned (or panics with) something that in its `Drop` implementation still uses borrowed stuff, it goes wrong.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=2a1f19ac4676cdabe43e24e536ff9358
2022-03-10 19:00:07 +01:00
Matthias Krüger
b5127202b2
Rollup merge of #94587 - JKAnderson409:issue-90107-fix, r=scottmcm
Document new recommended use of `FromIterator::from_iter`

#90107
Most of the added prose was paraphrased from the links provided in the issue. The suggested `VecDeque` example seemed to make the point well enough so I just used that.
2022-03-10 19:00:06 +01:00
T-O-R-U-S
72a25d05bf Use implicit capture syntax in format_args
This updates the standard library's documentation to use the new syntax. The
documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).
2022-03-10 10:23:40 -05:00
Oli Scherer
5f7ca55df6 Revert accidental stabilization 2022-03-10 14:36:51 +00:00
Martin Gammelsæter
c62ab422d0 Inline <EscapeDefault as Iterator>::next 2022-03-10 15:35:22 +01:00
Matthias Krüger
e7281d08de
Rollup merge of #94746 - notriddle:notriddle/method-rustc-on-unimplemented, r=davidtwco
diagnostics: use rustc_on_unimplemented to recommend `[].iter()`

To make this work, the `#[rustc_on_unimplemented]` data needs to be used to
report method resolution errors, which is most of what this commit does.

Fixes #94581
2022-03-10 12:20:53 +01:00
Matthias Krüger
fe034cb43b
Rollup merge of #94657 - fee1-dead:const_slice_index, r=oli-obk
Constify `Index{,Mut}` for `[T]`, `str`, and `[T; N]`

Several panic functions were rewired (via `const_eval_select`) to simpler implementations that do not require formatting for compile-time usage.

r? ```@oli-obk```
2022-03-10 12:20:52 +01:00
Matthias Krüger
313a668234
Rollup merge of #94635 - jhpratt:merge-deprecated-attrs, r=davidtwco
Merge `#[deprecated]` and `#[rustc_deprecated]`

The first commit makes "reason" an alias for "note" in `#[rustc_deprecated]`, while still prohibiting it in `#[deprecated]`.

The second commit changes "suggestion" to not just be a feature of `#[rustc_deprecated]`. This is placed behind the new `deprecated_suggestion` feature. This needs a tracking issue; let me know if this PR will be approved and I can create one.

The third commit is what permits `#[deprecated]` to be used when `#![feature(staged_api)]` is enabled. This isn't yet used in stdlib (only tests), as it would require duplicating all deprecation attributes until a bootstrap occurs. I intend to submit a follow-up PR that replaces all uses and removes the remaining `#[rustc_deprecated]` code after the next bootstrap.

`@rustbot` label +T-libs-api +C-feature-request +A-attributes +S-waiting-on-review
2022-03-10 12:20:51 +01:00
Scott McMurray
7ef74bc8b9 Let try_collect take advantage of try_fold overrides
Without this change it's going through `&mut impl Iterator`, which handles `?Sized` and thus currently can't forward generics.

Here's the test added, to see that it fails before this PR (once a new enough nightly is out): https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=462f2896f2fed2c238ee63ca1a7e7c56
2022-03-10 00:16:06 -08:00
JmPotato
2f18fa801b Use MaybeUninit in VecDeque to remove the undefined behavior of slice
Signed-off-by: JmPotato <ghzpotato@gmail.com>
2022-03-10 14:14:25 +08:00
Ralf Jung
29d979fb3c enable portable-simd doctests in Miri 2022-03-09 19:31:25 -05:00
Matthias Krüger
06944d9e49
Rollup merge of #94768 - fortanix:raoul/fix_close_read_wakes_up_test_sgx_platform, r=dtolnay
Ignore `close_read_wakes_up` test on SGX platform

PR #94714 enabled the `close_read_wakes_up` test for all platforms. This is incorrect. This test should be ignored at least for the SGX platform.

cc: ``@mzohreva`` ``@jethrogb``
2022-03-09 23:14:15 +01:00
Matthias Krüger
9e90f8d39b
Rollup merge of #94763 - m-ou-se:scoped-threads-lifetime-docs, r=Mark-Simulacrum
Add documentation about lifetimes to thread::scope.

This resolves the last unresolved question of https://github.com/rust-lang/rust/issues/93203

This was brought up in https://github.com/rust-lang/rust/pull/94559#discussion_r820872694

r? `````@Mark-Simulacrum`````
2022-03-09 23:14:14 +01:00
Matthias Krüger
d5c05fcc8a
Rollup merge of #93057 - frengor:iter_collect_into, r=m-ou-se
Add Iterator::collect_into

This PR adds `Iterator::collect_into` as proposed by ``@cormacrelf`` in #48597 (see https://github.com/rust-lang/rust/pull/48597#issuecomment-842083688).
Followup of #92982.

This adds the following method to the Iterator trait:

```rust
fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
```
2022-03-09 23:14:11 +01:00
Matthias Krüger
2567d0f883
Rollup merge of #92541 - asquared31415:from-docs, r=m-ou-se
Mention intent of `From` trait in its docs

This pr is a docs modification to add to the documentation of the `From` trait a note about its intent as a perfect conversion.  This is already stated in the `TryFrom` docs so this is simply adding that information in a more visible way.
2022-03-09 23:14:10 +01:00
Matthias Krüger
c0259626b6
Rollup merge of #91804 - woppopo:const_clone, r=oli-obk
Make some `Clone` impls `const`

Tracking issue: #91805
`Clone::clone_from` and some impls (Option, Result) bounded on `~const Drop`.

```rust
// core::clone
impl const Clone for INTEGER
impl const Clone for FLOAT
impl const Clone for bool
impl const Clone for char
impl const Clone for !
impl<T: ?Sized> const Clone for *const T
impl<T: ?Sized> const Clone for *mut T
impl<T: ?Sized> const Clone for &T

// core::option
impl<T> const Clone for Option<T>
where
    T: ~const Clone + ~const Drop

// core::result
impl<T, E> const Clone for Result<T, E>
where
    T: ~const Clone + ~const Drop,
    E: ~const Clone + ~const Drop,

// core::convert
impl const Clone for Infallible

// core::ptr
impl<T: ?Sized> const Clone for NonNull<T>
impl<T: ?Sized> const Clone for Unique<T>
```
2022-03-09 23:14:09 +01:00
Jacob Pratt
5636655d0f
New deprecated_suggestion feature, use in tests 2022-03-09 16:32:47 -05:00
Martin Gammelsæter
7f4f4fc34c Use indexing instead of .get_unchecked() for LUT lookup
Based on @paolobarbolini's tip that the unsafe block was unnecessary in
this case.

Not much left of `hexify()` after this, so seemed clearer to just inline
it.
2022-03-09 22:21:35 +01:00
fren_gor
63eddb3e68
Add tracking issue 2022-03-09 21:12:07 +01:00
Michael Howell
32d7f8145a diagnostics: use rustc_on_unimplemented to recommend [].iter()
To make this work, the `#[rustc_on_unimplemented]` data needs to be used to
report method resolution errors, which is most of what this commit does.

Fixes #94581
2022-03-09 09:52:55 -07:00
Martin Gammelsæter
876142417c Optimize ascii::escape_default by using a digit LUT 2022-03-09 17:10:34 +01:00
Frank King
2c3c891df0 BTreeMap::entry: Avoid allocating if no insertion 2022-03-09 22:29:05 +08:00
Mara Bos
4d56c1563c Add documentation about lifetimes to thread::scope. 2022-03-09 15:20:00 +01:00
Raoul Strackx
491350ce75 Ignore close_read_wakes_up test on SGX platform 2022-03-09 12:28:16 +01:00
Benjamin Lamowski
bc199b5778 add as_raw() method to L4Re's Socket mock
Minimally comply with with #87329 to avoid breaking tests on L4Re.
2022-03-09 11:53:27 +01:00
Benjamin Lamowski
cb013d4802 put L4Re specifics into their own platform
The initial stdlib modifications for L4Re just used the linux specifics
directly because they were reasonably close to L4Re's behavior.
However, this breaks when Linux-specific code relies on code that is
only available for the linux target, such as in #81825.

Put L4Re into its own platform to avoid such breakage in the future.
This uses the Linux-specific code as a starting point, which seems to be
in line with other OSes with a unix-y interface such as Fuchsia.
2022-03-09 11:53:27 +01:00
Benjamin Lamowski
997dc5899a adapt L4Re network interface mock to #87329
Copy the relevant trait implementations from the Unix default.
2022-03-09 11:53:27 +01:00
Benjamin Lamowski
c0dc41f5ff L4Re does not support sanitizing standard streams
L4Re provides limited POSIX support which includes support for
standard I/O streams, and a limited implementation of the standard file
handling API. However, because as a capability based OS it strives to
only make a local view available to each application, there are
currently no standardized special files like /dev/null that could serve
to sanitize closed standard FDs.

For now, skip any attempts to sanitize standard streams until a more
complete POSIX runtime is available.
2022-03-09 11:53:27 +01:00
Benjamin Lamowski
898f379817 drop unused libc imports on L4Re
As a capability-based microkernel OS, L4Re only has incomplete support
for POSIX APIs, in particular it does not implement UIDs and GIDs.
2022-03-09 11:53:27 +01:00
Sebastian Humenda
11b717647e fix return value of LookupHost::port()
[Benjamin Lamowski: Reworded commit message after split commit.]
2022-03-09 11:53:27 +01:00
Sebastian Humenda
7a74d28c38 fix return values in L4Re networking stub
[Benjamin Lamowski: Reworded commit message after split commit.]
2022-03-09 11:53:27 +01:00
Mara Bos
b97d87518d Add soundness test for dropping scoped thread results before joining. 2022-03-09 11:47:53 +01:00
Mara Bos
1c06eb7c1f Remove outdated comment. 2022-03-09 11:47:46 +01:00
Mara Bos
7a481ff8a4 Properly abort when thread result panics on drop. 2022-03-09 11:44:24 +01:00
Mara Bos
5226395d6f Fix soundness issue in scoped threads. 2022-03-09 11:44:24 +01:00
Mara Bos
7c7411fb5d Rename is_{some,ok,err}_with to is_{some,ok,err}_and. 2022-03-09 11:20:36 +01:00
Dylan DPC
28d06bdec9
Rollup merge of #94756 - ChrisDenton:unreachable, r=yaahc
Use `unreachable!` for an unreachable code path

Closes #73212
2022-03-09 06:38:53 +01:00
Dylan DPC
4de06d459f
Rollup merge of #94699 - ssomers:btree_prune_insert, r=Dylan-DPC
BTree: remove dead data needlessly complicating insert

Possibly needless instructions generated

r? rust-lang/libs
r? ``@Amanieu``
cc ``@frank-king``
2022-03-09 06:38:52 +01:00
bors
163c207fc2 Auto merge of #94750 - cuviper:dirent64_min, r=joshtriplett
unix: reduce the size of DirEntry

On platforms where we call `readdir` instead of `readdir_r`, we store
the name as an allocated `CString` for variable length. There's no point
carrying around a full `dirent64` with its fixed-length `d_name` too.
2022-03-09 02:17:58 +00:00
Ralf Jung
28eb06bd98 docs 2022-03-08 20:09:44 -05:00
Chris Denton
57442beb18
Use unreachable! for an unreachable code path 2022-03-09 01:05:47 +00:00
Loïc BRANSTETT
e3ea59ada5 Remove unexpected #[cfg(target_pointer_width = "8")] in tests 2022-03-09 00:30:17 +01:00
Dylan DPC
5629026e90
Rollup merge of #94730 - msabansal:sabansal/b-atomic-mut-ptr, r=Dylan-DPC
Reverted atomic_mut_ptr feature removal causing compilation break

Fixes a regression introduced as part of https://github.com/rust-lang/rust/pull/94546

Std no longer compiles on nightly while using the following commnd:

export RUSTFLAGS='-C target-feature=+atomics,+bulk-memory'
cargo build --target wasm32-unknown-unknown -Z build-std=panic_abort,std

I can help add tests to avoid future breaks but i couldn't understand the test framework
2022-03-08 22:44:01 +01:00
Dylan DPC
a67b6299b4
Rollup merge of #94724 - cuviper:rmdirall-cstr, r=Dylan-DPC
unix: Avoid name conversions in `remove_dir_all_recursive`

Each recursive call was creating an `OsString` for a `&Path`, only for
it to be turned into a `CString` right away. Instead we can directly
pass `.name_cstr()`, saving two allocations each time.
2022-03-08 22:44:00 +01:00
Dylan DPC
ff54e34463
Rollup merge of #94723 - dtolnay:mustuse, r=Mark-Simulacrum
Add core::hint::must_use

The example code in this documentation is minimized from a real-world situation in the `anyhow` crate where this function would have been valuable.

Having this provided by the standard library is especially useful for proc macros, even more than for macro_rules. That's because proc macro crates aren't allowed to export anything other than macros, so they couldn't make their own `must_use` function for their macro-generated code to call.

<br>

## Rendered documentation

> An identity function that causes an `unused_must_use` warning to be triggered if the given value is not used (returned, stored in a variable, etc) by the caller.
>
> This is primarily intended for use in macro-generated code, in which a [`#[must_use]` attribute][must_use] either on a type or a function would not be convenient.
>
> [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
>
> ### Example
>
> ```rust
> #![feature(hint_must_use)]
>
> use core::fmt;
>
> pub struct Error(/* ... */);
>
> #[macro_export]
> macro_rules! make_error {
>     ($($args:expr),*) => {
>         core::hint::must_use({
>             let error = $crate::make_error(core::format_args!($($args),*));
>             error
>         })
>     };
> }
>
> // Implementation detail of make_error! macro.
> #[doc(hidden)]
> pub fn make_error(args: fmt::Arguments<'_>) -> Error {
>     Error(/* ... */)
> }
>
> fn demo() -> Option<Error> {
>     if true {
>         // Oops, meant to write `return Some(make_error!("..."));`
>         Some(make_error!("..."));
>     }
>     None
> }
> ```
>
> In the above example, we'd like an `unused_must_use` lint to apply to the value created by `make_error!`. However, neither `#[must_use]` on a struct nor `#[must_use]` on a function is appropriate here, so the macro expands using `core::hint::must_use` instead.
>
> - We wouldn't want `#[must_use]` on the `struct Error` because that would make the following unproblematic code trigger a warning:
>
>   ```rust
>   fn f(arg: &str) -> Result<(), Error>
>
>   #[test]
>   fn t() {
>       // Assert that `f` returns error if passed an empty string.
>       // A value of type `Error` is unused here but that's not a problem.
>       f("").unwrap_err();
>   }
>   ```
>
> - Using `#[must_use]` on `fn make_error` can't help because the return value *is* used, as the right-hand side of a `let` statement. The `let` statement looks useless but is in fact necessary for ensuring that temporaries within the `format_args` expansion are not kept alive past the creation of the `Error`, as keeping them alive past that point can cause autotrait issues in async code:
>
>   ```rust
>   async fn f() {
>       // Using `let` inside the make_error expansion causes temporaries like
>       // `unsync()` to drop at the semicolon of that `let` statement, which
>       // is prior to the await point. They would otherwise stay around until
>       // the semicolon on *this* statement, which is after the await point,
>       // and the enclosing Future would not implement Send.
>       log(make_error!("look: {:p}", unsync())).await;
>   }
>
>   async fn log(error: Error) {/* ... */}
>
>   // Returns something without a Sync impl.
>   fn unsync() -> *const () {
>       0 as *const ()
>   }
>   ```
2022-03-08 22:43:59 +01:00
Dylan DPC
ee8109d12d
Rollup merge of #94714 - ChrisDenton:win-close_read_wakes_up, r=Mark-Simulacrum
Enable `close_read_wakes_up` test on Windows

I wonder if we could/should try enabling this again? It was closed by #38867 due to #31657. I've tried running this test (along with other tests) on my machine a number of times and haven't seen this fail yet,

Caveat: the worst that can happen is this succeeds initially but then causes random hangs in CI. This is not a great failure mode and would be a reason not to do this.

If this does work out, closes #39006

r? `@Mark-Simulacrum`
2022-03-08 22:43:57 +01:00
Josh Stone
e8b9ba84be unix: reduce the size of DirEntry
On platforms where we call `readdir` instead of `readdir_r`, we store
the name as an allocated `CString` for variable length. There's no point
carrying around a full `dirent64` with its fixed-length `d_name` too.
2022-03-08 13:36:01 -08:00
Ralf Jung
2a2b212ea3 remove_dir_all: use fallback implementation on Miri 2022-03-08 16:26:10 -05:00
David Tolnay
b2473e988f
Add core::hint::must_use 2022-03-08 10:58:03 -08:00
Matthias Krüger
a077e44c14
Rollup merge of #94712 - kckeiks:remove-rwlock-read-error-assumption, r=Mark-Simulacrum
promot debug_assert to assert

Fixes #94705
2022-03-08 11:04:55 +01:00
Matthias Krüger
aec535f805
Rollup merge of #94559 - m-ou-se:thread-scope-spawn-closure-without-arg, r=Mark-Simulacrum
Remove argument from closure in thread::Scope::spawn.

This implements ```@danielhenrymantilla's``` [suggestion](https://github.com/rust-lang/rust/issues/93203#issuecomment-1040798286) for improving the scoped threads interface.

Summary:

The `Scope` type gets an extra lifetime argument, which represents basically its own lifetime that will be used in `&'scope Scope<'scope, 'env>`:

```diff
- pub struct Scope<'env> { .. };
+ pub struct Scope<'scope, 'env: 'scope> { .. }

  pub fn scope<'env, F, T>(f: F) -> T
  where
-     F: FnOnce(&Scope<'env>) -> T;
+     F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T;
```

This simplifies the `spawn` function, which now no longer passes an argument to the closure you give it, and now uses the `'scope` lifetime for everything:

```diff
-     pub fn spawn<'scope, F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
+     pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
      where
-         F: FnOnce(&Scope<'env>) -> T + Send + 'env,
+         F: FnOnce() -> T + Send + 'scope,
-         T: Send + 'env;
+         T: Send + 'scope;
```

The only difference the user will notice, is that their closure now takes no arguments anymore, even when spawning threads from spawned threads:

```diff
  thread::scope(|s| {
-     s.spawn(|_| {
+     s.spawn(|| {
          ...
      });
-     s.spawn(|s| {
+     s.spawn(|| {
          ...
-         s.spawn(|_| ...);
+         s.spawn(|| ...);
      });
  });
```

<details><summary>And, as a bonus, errors get <em>slightly</em> better because now any lifetime issues point to the outermost <code>s</code> (since there is only one <code>s</code>), rather than the innermost <code>s</code>, making it clear that the lifetime lasts for the entire <code>thread::scope</code>.

</summary>

```diff
  error[E0373]: closure may outlive the current function, but it borrows `a`, which is owned by the current function
   --> src/main.rs:9:21
    |
- 7 |         s.spawn(|s| {
-   |                  - has type `&Scope<'1>`
+ 6 |     thread::scope(|s| {
+   |                    - lifetime `'1` appears in the type of `s`
  9 |             s.spawn(|| println!("{:?}", a)); // might run after `a` is dropped
    |                     ^^                  - `a` is borrowed here
    |                     |
    |                     may outlive borrowed value `a`
    |
  note: function requires argument type to outlive `'1`
   --> src/main.rs:9:13
    |
  9 |             s.spawn(|| println!("{:?}", a)); // might run after `a` is dropped
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  help: to force the closure to take ownership of `a` (and any other referenced variables), use the `move` keyword
    |
  9 |             s.spawn(move || println!("{:?}", a)); // might run after `a` is dropped
    |                     ++++
"
```
</details>

The downside is that the signature of `scope` and `Scope` gets slightly more complex, but in most cases the user wouldn't need to write those, as they just use the argument provided by `thread::scope` without having to name its type.

Another downside is that this does not work nicely in Rust 2015 and Rust 2018, since in those editions, `s` would be captured by reference and not by copy. In those editions, the user would need to use `move ||` to capture `s` by copy. (Which is what the compiler suggests in the error.)
2022-03-08 11:04:51 +01:00
Matthias Krüger
e22331ce02
Rollup merge of #92385 - clarfonthey:const_option, r=fee1-dead
Add Result::{ok, err, and, or, unwrap_or} as const

Already opened tracking issue #92384.

I don't think that this should actually cause any issues as long as the constness is unstable, but we may want to double-check that this doesn't get interpreted as a weird `Drop` bound even for non-const usages.
2022-03-08 11:04:50 +01:00
Miguel Perez
b795ae5280 Fix for issue #93283 2022-03-08 10:16:18 +01:00
Sandeep Bansal
d8e75bc1b7 Reverted atomic-mut-ptr feature removal causing compilation break 2022-03-07 23:41:52 -08:00
Josh Stone
ef3e33bd16 unix: Avoid name conversions in remove_dir_all_recursive
Each recursive call was creating an `OsString` for a `&Path`, only for
it to be turned into a `CString` right away. Instead we can directly
pass `.name_cstr()`, saving two allocations each time.
2022-03-07 18:51:53 -08:00
Chris Denton
24ec0f223d
Enable close_read_wakes_up on Windows 2022-03-07 22:35:17 +00:00
Mara Bos
a3d269e91c
Use f instead of || f().
Co-authored-by: Mark Rousskov <mark.simulacrum@gmail.com>
2022-03-07 22:14:02 +00:00
Fausto
776be7e73e promot debug_assert to assert 2022-03-07 15:48:35 -05:00
Matthias Krüger
9d7166c66f
Rollup merge of #93827 - eholk:stabilize-const_fn-features, r=wesleywiser
Stabilize const_fn_fn_ptr_basics, const_fn_trait_bound, and const_impl_trait

# Stabilization Report

This PR serves as a request for stabilization for three const evaluation features:

1. `const_fn_fn_ptr_basics`
2. `const_fn_trait_bound`
3. `const_impl_trait`

These are being stabilized together because they are relatively minor and related updates to existing functionality.

## `const_fn_fn_ptr_basics`

Allows creating, passing, and casting function pointers in a `const fn`.

The following is an example of what is now allowed:

```rust
const fn get_function() -> fn() {
    fn foo() {
        println!("Hello, World!");
    }

    foo
}
```

Casts between function pointer types are allowed, as well as transmuting from integers:

```rust
const fn get_function() -> fn() {
    unsafe {
        std::mem::transmute(0x1234usize)
    }
}
```

However, casting from a function pointer to an integer is not allowed:

```rust
const fn fn_to_usize(f: fn()) -> usize {
    f as usize  //~ pointers cannot be cast to integers during const eval
}
```

Calling function pointers is also not allowed.

```rust
const fn call_fn_ptr(f: fn()) {
    f() //~ function pointers are not allowed in const fn
}
```

### Test Coverage

The following tests include code that exercises this feature:

- `src/test/ui/consts/issue-37550.rs`
- `src/test/ui/consts/issue-46553.rs`
- `src/test/ui/consts/issue-56164.rs`
- `src/test/ui/consts/min_const_fn/allow_const_fn_ptr_run_pass.rs`
- `src/test/ui/consts/min_const_fn/cast_fn.rs`
- `src/test/ui/consts/min_const_fn/cmp_fn_pointers.rs`

## `const_fn_trait_bound`

Allows trait bounds in `const fn`. Additionally, this feature allows creating and passing `dyn Trait` objects.

Examples such as the following are allowed by this feature:

```rust
const fn do_thing<T: Foo>(_x: &T) {
    // ...
}
```

Previously only `Sized` was allowed as a trait bound.

There is no way to call methods from the trait because trait methods cannot currently be marked as const. Allowing trait bounds in const functions does allow the const function to use the trait's associated types and constants.

This feature also allowes `dyn Trait` types. These work equivalently to non-const code. Similar to other pointers in const code, the value of a `dyn Trait` pointer cannot be observed.

Note that due to https://github.com/rust-lang/rust/issues/90912, it was already possible to do the example above as follows:

```rust
const fn do_thing<T>(_x: &T) where (T,): Foo {
    // ...
}
```

### Test Coverage

The following tests include code that exercises `const_fn_trait_bound`:

- `src/test/ui/consts/const-fn.rs`
- `src/test/ui/consts/issue-88071.rs`
- `src/test/ui/consts/min_const_fn/min_const_fn.rs`
- `src/test/ui/consts/min_const_fn/min_const_fn_dyn.rs`
- `src/test/ui/nll/issue-55825-const-fn.rs`
- Many of the tests in `src/test/ui/rfc-2632-const-trait-impl/` also exercise this feature.

## `const_impl_trait`

Allows argument and return position `impl Trait` in a `const fn`, such as in the following example:

```rust
const fn do_thing(x: impl Foo) -> impl Foo {
    x
}
```

Similar to generic parameters and function pointers, this allows the creation of such opaque types, but not doing anything with them beyond accessing associated types and constants.

### Test Coverage

The following tests exercise this feature:

- `src/test/ui/type-alias-impl-trait/issue-53096.rs`
- `src/test/ui/type-alias-impl-trait/issue-53678-generator-and-const-fn.rs`

## Documentation

These features are documented along with the other const evaluation features in the Rust Reference at https://doc.rust-lang.org/stable/reference/const_eval.html.

There is a PR that updates this documentation to reflect the capabilities enabled by these features at https://github.com/rust-lang/reference/pull/1166.

Tracking issues: #57563, #63997, #93706
2022-03-07 18:39:02 +01:00
Matthias Krüger
1ca8d0bf8c
Rollup merge of #93350 - gburgessiv:master, r=Mark-Simulacrum
libunwind: readd link attrs to _Unwind_Backtrace

It seems the removal of these in 1c07096a45 was unintended; readding them fixes the build.

fixes rust-lang/rust#93349

r? `@alexcrichton`
2022-03-07 18:39:02 +01:00
Eric Holk
8700b45b67 Stabilize const_impl_trait as well 2022-03-07 08:47:18 -08:00
Eric Holk
7723506d13 Stabilize const_fn_fn_ptr_basics and const_fn_trait_bound 2022-03-07 08:47:15 -08:00