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.
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.
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.
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.
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`
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`
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.
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.
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.
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.
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`
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.
- Fixesrust-lang/rust#95002.
- Fixesrust-lang/rust#95064.
- Fixesrust-lang/rust#95122.
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.
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`
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.
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.
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)`.
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.
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...
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`.
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.
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.
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.
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.
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`.
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.
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).
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.
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
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`.
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``
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.
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
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)],
),
);
```
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
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.
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?
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`
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.
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`
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.
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!
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.
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` .
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).
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.
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.
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).
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
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```
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
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``
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
```
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.
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.
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
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.
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.
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.
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
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.
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 ()
> }
> ```
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`
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.
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.)
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.
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.
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
libunwind: readd link attrs to _Unwind_Backtrace
It seems the removal of these in 1c07096a45 was unintended; readding them fixes the build.
fixesrust-lang/rust#93349
r? `@alexcrichton`