The old documentation suggested the use of yield_now for repeated
polling instead of discouraging it; it also made the false claim that
channels are implementing using yield_now. (They are not, except for
a corner case).
Remove some doc aliases
As per the new doc alias policy in https://github.com/rust-lang/std-dev-guide/pull/25, this removes some controversial doc aliases:
- `malloc`, `alloc`, `realloc`, etc.
- `length` (alias for `len`)
- `delete` (alias for `remove` in collections and also file/directory deletion)
r? `@joshtriplett`
Stabilize `Seek::rewind()`
This stabilizes `Seek::rewind`. It seemed to fit into one of the existing tests, so I extended that test rather than adding a new one.
Closes#85149.
aborts: Clarify documentation and comments
In the docs for intrinsics::abort():
* Strengthen the recommendation by to use process::abort instead.
* Document the fact that it sometimes (ab)uses an LLVM debug trap and what the likely consequences are.
* State that the precise behaviour is unstable.
In the docs for process::abort():
* Promise that we have the same behaviour as C `abort()`.
* Document the likely consequences, including, specifically, the consequences on Unix.
In the internal comment for unix::abort_internal:
* Refer to the public docs for the public API functions.
* Correct and expand the description of libc::abort. Specifically:
* Do not claim that abort() unregisters signal handlers. It doesn't; it honours the SIGABRT handler.
* Discuss, extensively, the issue with abort() flushing stdio buffers.
* Describe the glibc behaviour in some detail.
Co-authored-by: Mark Wooding <mdw@distorted.org.uk>
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Fixes#40230
Add std::os::unix::fs::DirEntryExt2::file_name_ref(&self) -> &OsStr
Greetings!
This is my first PR here, so please forgive me if I've missed an important step or otherwise done something wrong. I'm very open to suggestions/fixes/corrections.
This PR adds a function that allows `std::fs::DirEntry` to vend a borrow of its filename on Unix platforms, which is especially useful for sorting. (Windows has (as I understand it) encoding differences that require an allocation.) This new function sits alongside the cross-platform [`file_name(&self) -> OsString`](https://doc.rust-lang.org/std/fs/struct.DirEntry.html#method.file_name) function.
I pitched this idea in an [internals thread](https://internals.rust-lang.org/t/allow-std-direntry-to-vend-borrows-of-its-filename/14328/4), and no one objected vehemently, so here we are.
I understand features in general, I believe, but I'm not at all confident that my whole-cloth invention of a new feature string (as required by the compiler) was correct (or that the name is appropriate). Further, there doesn't appear to be a test for the sibling `ino` function, so I didn't add one for this similarly trivial function either. If it's desirable that I should do so, I'd be happy to [figure out how to] do that.
The following is a trivial sample of a use-case for this function, in which directory entries are sorted without any additional allocations:
```rust
use std::os::unix::fs::DirEntryExt;
use std::{fs, io};
fn main() -> io::Result<()> {
let mut entries = fs::read_dir(".")?.collect::<Result<Vec<_>, io::Error>>()?;
entries.sort_unstable_by(|a, b| a.file_name_ref().cmp(b.file_name_ref()));
for p in entries {
println!("{:?}", p);
}
Ok(())
}
```
And withdraw the allegation of "abuse".
Adapted from a suggestion by @m-ou-se.
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
In the docs for intrinsics::abort():
* Strengthen the recommendation by to use process::abort instead.
* Document the fact that it (ab)uses an LLVM debug trap and what the
likely consequences are.
* State that the precise behaviour is unstable.
In the docs for process::abort():
* Promise that we have the same behaviour as C `abort()`.
* Document the likely consequences, including, specifically, the
consequences on Unix.
In the internal comment for unix::abort_internal:
* Refer to the public docs for the public API functions.
* Correct and expand the description of libc::abort. Specifically:
* Do not claim that abort() unregisters signal handlers. It doesn't;
it honours the SIGABRT handler.
* Discuss, extensively, the issue with abort() flushing stdio buffers.
* Describe the glibc behaviour in some detail.
Co-authored-by: Mark Wooding <mdw@distorted.org.uk>
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Rollup of 8 pull requests
Successful merges:
- #86477 (E0716: clarify that equivalent code example is erroneous)
- #86623 (Add check to ensure error code explanations are not removed anymore even if not emitted)
- #86856 (Make x.py less verbose on failures)
- #86858 (Stabilize `string_drain_as_str`)
- #86859 (Add a regression test for issue-69323)
- #86862 (re-export SwitchIntEdgeEffects)
- #86864 (Add missing code example for Write::write_vectored)
- #86874 (Bump deps)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Add examples to the various methods of `core::task::Poll`
This improves the documentation of the various methods of [`core::task::Poll`](https://doc.rust-lang.org/std/task/enum.Poll.html). These currently have fairly simple docs with no examples. This PR changes these methods to be closer to `core::option::Option` and adds usage examples (and importantly: tests!) to `Poll`'s methods.
cc/ `@rust-lang/wg-async-foundations`
## Screenshots
<details>
<summary>View generated rustdoc page</summary>
<image src="https://user-images.githubusercontent.com/2467194/123286616-59ee9b00-d50e-11eb-9e02-40269070f904.png" alt="Poll in core::task"></details>
core: add unstable no_fp_fmt_parse to disable float formatting code
In some projects (e.g. kernel), floating point is forbidden. They can disable
hardware floating point support and use `+soft-float` to avoid fp instructions
from being generated, but as libcore contains the formatting code for `f32`
and `f64`, some fp intrinsics are depended. One could define stubs for these
intrinsics that just panic [1], but it means that if any formatting functions
are accidentally used, mistake can only be caught during the runtime rather
than during compile-time or link-time, and they consume a lot of space without
LTO.
This patch provides an unstable cfg `no_fp_fmt_parse` to disable these.
A panicking stub is still provided for the `Debug` implementation (unfortunately)
because there are some SIMD types that use `#[derive(Debug)]`.
[1]: https://lkml.org/lkml/2021/4/14/1028
Stabilize `str::from_utf8_unchecked` as `const`
This stabilizes `unsafe fn str::from_utf8_unchecked` as `const` pending FCP on #75196. By the time FCP finishes, the beta will have already been cut, so I've set 1.55 as the stable-since version.
(should also be +relnotes but I don't have the permission to do that)
r? `@m-ou-se`
Closes#75196
Remove the deprecated `core::raw` and `std::raw` module.
A few months has passed since #84207. I think now it's time for the final removal.
Closes#27751.
r? `@m-ou-se`
When using `process::Command` on Windows, environment variable names must be case-preserving but case-insensitive
When using `Command` to set the environment variables, the key should be compared as uppercase Unicode but when set it should preserve the original case.
Fixes#85242
alloc: `no_global_oom_handling`: disable `new()`s, `pin()`s, etc.
They are infallible, and could not be actually used because
they will trigger an error when monomorphized, but it is better
to just remove them.
Link: https://github.com/Rust-for-Linux/linux/pull/402
Suggested-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
add owned locked stdio handles
Add stderr_locked, stdin_locked, and stdout_locked free functions
to obtain owned locked stdio handles in a single step. Also add
into_lock methods to consume a stdio handle and return an owned
lock. These methods will make it easier to use locked stdio
handles without having to deal with lifetime problems or keeping
bindings to the unlocked handles around.
Fixes#85383; enables #86412.
r? `@joshtriplett`
`@rustbot` label +A-io +C-enhancement +D-newcomer-roadblock +T-libs-api
More ErrorKinds for common errnos
From the commit message of the main commit here (as revised):
```
There are a number of IO error situations which it would be very
useful for Rust code to be able to recognise without having to resort
to OS-specific code. Taking some Unix examples, `ENOTEMPTY` and
`EXDEV` have obvious recovery strategies. Recently I was surprised to
discover that `ENOSPC` came out as `ErrorKind::Other`.
Since I am familiar with Unix I reviwed the list of errno values in
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html
Here, I add those that most clearly seem to be needed.
`@CraftSpider` provided information about Windows, and references, which
I have tried to take into account.
This has to be insta-stable because we can't sensibly have a different
set of ErrorKinds depending on a std feature flag.
I have *not* added these to the mapping tables for any operating
systems other than Unix and Windows. I hope that it is OK to add them
now for Unix and Windows now, and maybe add them to other OS's mapping
tables as and when someone on that OS is able to consider the
situation.
I adopted the general principle that it was usually a bad idea to map
two distinct error values to the same Rust error code. I notice that
this principle is already violated in the case of `EACCES` and
`EPERM`, which both map to `PermissionDenied`. I think this was
probably a mistake but it would be quite hard to change now, so I
don't propose to do anything about that.
However, for Windows, there are sometimes different error codes for
identical situations. Eg there are WSA* versions of some error
codes as well as ERROR_* ones. Also Windows seems to have a great
many more erorr codes. I don't know precisely what best practice
would be for Windows.
```
<strike>
```
Errno values I wasn't sure about so *haven't* included:
EMFILE ENFILE ENOBUFS ENOLCK:
These are all fairly Unix-specific resource exhaustion situations.
In practice it seemed not very likely to me that anyone would want
to handle these differently to `Other`.
ENOMEM ERANGE EDOM EOVERFLOW
Normally these don't get exposed to the Rust callers I hope. They
don't tend to come out of filesystem APIs.
EILSEQ
Hopefully Rust libraries open files in binary mode and do the
converstion in Rust. So Rust code ought not to be exposed to
EILSEQ.
EIO
The range of things that could cause this is troublesome. I found
it difficult to describe. I do think it would be useful to add this
at some point, because EIO on a filesystem operation is much more
serious than most other errors.
ENETDOWN
I wasn't sure if this was useful or, indeed, if any modern systems
use it.
ENOEXEC
It is not clear to me how a Rust program could respond to this. It
seems rather niche.
EPROTO ENETRESET ENODATA ENOMSG ENOPROTOOPT ENOSR ENOSTR ETIME
ENOTRECOVERABLE EOWNERDEAD EBADMSG EPROTONOSUPPORT EPROTOTYPE EIDRM
These are network or STREAMS related errors which I have never in
my own Unix programming found the need to do anything with. I think
someone who understands these better should be the one to try to
find good Rust names and descriptions for them.
ENOTTY ENXIO ENODEV EOPNOTSUPP ESRCH EALREADY ECANCELED ECHILD
EINPROGRESS
These are very hard to get unless you're already doing something
very Unix-specific, in which case the raw_os_error interface is
probably more suitable than relying on the Rust ErrorKind mapping.
EFAULT EBADF
These would seem to be the result of application UB.
```
</strike>
<i>(omitted errnos are discussed below, especially in https://github.com/rust-lang/rust/pull/79965#issuecomment-810468334)
In some projects (e.g. kernel), floating point is forbidden. They can disable
hardware floating point support and use `+soft-float` to avoid fp instructions
from being generated, but as libcore contains the formatting code for `f32`
and `f64`, some fp intrinsics are depended. One could define stubs for these
intrinsics that just panic [1], but it means that if any formatting functions
are accidentally used, mistake can only be caught during the runtime rather
than during compile-time or link-time, and they consume a lot of space without
LTO.
This patch provides an unstable cfg `no_fp_fmt_parse` to disable these.
A panicking stub is still provided for the `Debug` implementation (unfortunately)
because there are some SIMD types that use `#[derive(Debug)]`.
[1]: https://lkml.org/lkml/2021/4/14/1028
Fix double import in wasm thread
The `unsupported` type is imported two times, as `super::unsupported` and as `crate::sys::unsupported`, throwing an error. Remove `super::unsupported` in favor of the other.
As reported in #86802.
Fix#86802
Remove & from Command::args calls in documentation
Now that arrays implement `IntoIterator`, using `&` is no longer necessary. This makes examples easier to understand.
Merge `sys_common::bytestring` back into `os_str_bytes`
`bytestring` contains code for correctly debug formatting a byte slice (`[u8]`). This functionality is and has historically only been used to provide the debug formatting of byte-based os-strings (on unix etc.).
Having this functionality in the separate `bytestring` module was useful in the past to reduce duplication, as [when it was added](https://github.com/rust-lang/rust/pull/46798) `os_str_bytes` was still split into `sys::{unix, redox, wasi, etc.}::os_str`. However, now that is no longer the case, there is not much reason for the `bytestring` functionality to be separate from `os_str_bytes`; I don't think it is very likely that another part of std will need to handle formatting byte strings that are not os-strings in the future (everything should be `utf8`). This is why this PR merges the functionality of `bytestring` directly into the debug implementation in `os_str_bytes`.
add `track_path::path` fn for usage in `proc_macro`s
Adds a way to declare a dependency on external files without including them, to either re-trigger the build of a file as well as covering the use case of including dependencies within the `rustc` invocation, such that tools like `sccache`/`cachepot` are able to handle references to external files which are not included.
Ref #73921
They are infallible, and could not be actually used because
they will trigger an error when monomorphized, but it is better
to just remove them.
Link: https://github.com/Rust-for-Linux/linux/pull/402
Suggested-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
The `unsupported` type is imported two times, as `super::unsupported` and as `crate::sys::unsupported`, throwing an error. Remove `super::unsupported` in favor of the other.
Add linked list cursor end methods
I add several methods to `LinkedList::CursorMut` and `LinkedList::Cursor`. These methods allow you to access/manipulate the ends of a list via the cursor. This is especially helpful when scanning through a list and reordering. For example:
```rust
let mut c = ll.back_cursor_mut();
let mut moves = 10;
while c.current().map(|x| x > 5).unwrap_or(false) {
let n = c.remove_current();
c.push_front(n);
if moves > 0 { break; } else { moves -= 1; }
}
```
I encountered this problem working on my bachelors thesis doing graph index manipulation.
While this problem can be avoided by splicing, it is awkward. I asked about the problem [here](https://internals.rust-lang.org/t/linked-list-cursurmut-missing-methods/14921/4) and it was suggested I write a PR.
All methods added consist of
```rust
Cursor::front(&self) -> Option<&T>;
Cursor::back(&self) -> Option<&T>;
CursorMut::front(&self) -> Option<&T>;
CursorMut::back(&self) -> Option<&T>;
CursorMut::front_mut(&mut self) -> Option<&mut T>;
CursorMut::back_mut(&mut self) -> Option<&mut T>;
CursorMut::push_front(&mut self, elt: T);
CursorMut::push_back(&mut self, elt: T);
CursorMut::pop_front(&mut self) -> Option<T>;
CursorMut::pop_back(&mut self) -> Option<T>;
```
#### Design decisions:
I tried to remain as consistent as possible with what was already present for linked lists.
The methods `front`, `front_mut`, `back` and `back_mut` are identical to their `LinkedList` equivalents.
I tried to make the `pop_front` and `pop_back` methods work the same way (vis a vis the "ghost" node) as `remove_current`. I thought this was the closest analog.
`push_front` and `push_back` do not change the "current" node, even if it is the "ghost" node. I thought it was most intuitive to say that if you add to the list, current will never change.
Any feedback would be welcome 😄
Redefine `ErrorKind::Other` and stop using it in std.
This implements the idea I shared yesterday in the libs meeting when we were discussing how to handle adding new `ErrorKind`s to the standard library: This redefines `Other` to be for *user defined errors only*, and changes all uses of `Other` in the standard library to a `#[doc(hidden)]` and permanently `#[unstable]` `ErrorKind` that users can not match on. This ensures that adding `ErrorKind`s at a later point in time is not a breaking change, since the user couldn't match on these errors anyway. This way, we use the `#[non_exhaustive]` property of the enum in a more effective way.
Open questions:
- How do we check this change doesn't cause too much breakage? Will a crate run help and be enough?
- How do we ensure we don't accidentally start using `Other` again in the standard library? We don't have a `pub(not crate)` or `#[deprecated(in this crate only)]`.
cc https://github.com/rust-lang/rust/pull/79965
cc `@rust-lang/libs` `@ijackson`
r? `@dtolnay`
Add stderr_locked, stdin_locked, and stdout_locked free functions
to obtain owned locked stdio handles in a single step. Also add
into_lock methods to consume a stdio handle and return an owned
lock. These methods will make it easier to use locked stdio
handles without having to deal with lifetime problems or keeping
bindings to the unlocked handles around.
This commit makes the documentation of `BTreeSet::drain_filter` more
consistent with that of `BTreeMap::drain_filter` after the changes in
f0b8166870.
In particular, this explicitly documents the iteration order.
Use HTTPS links where possible
While looking at #86583, I wondered how many other (insecure) HTTP links were in `rustc`. This changes most other `http` links to `https`. While most of the links are in comments or documentation, there are a few other HTTP links that are used by CI that are changed to HTTPS.
Notes:
- I didn't change any to or in licences
- Some links don't support HTTPS :(
- Some `http` links were dead, in those cases I upgraded them to their new places (all of which used HTTPS)
Use `#[non_exhaustive]` where appropriate
Due to the std/alloc split, it is not possible to make `alloc::collections::TryReserveError::AllocError` non-exhaustive without having an unstable, doc-hidden method to construct (which negates the benefits from `#[non_exhaustive]`).
`@rustbot` label +C-cleanup +T-libs +S-waiting-on-review
Add `BuildHasher::hash_one` as unstable
Inspired by https://github.com/rust-lang/rust/pull/86140/files#diff-246941135168fbc44fce120385ee9c3156e08a1c3e2697985b56dcb8d728eedeR2416, where I wanted to write a quick test for a `Hash` implementation and it took more of a dance than I'd hoped.
It looks like this would be handy in hashtable implementations, too -- a quick look at hashbrown found two places where it needs to do the same dance:
6302512a8a/src/map.rs (L247-L270)
I wanted to get a "seems plausible" from a libs member before making a tracking issue, so random-sampling the intersection of highfive and governance gave me...
r? `@joshtriplett`
(As always, bikeshed away! And let me know if I missed something obvious again that I should have used instead.)
(Most of these are from a review by joshtriplett. Thanks!)
Fix errors in `as_pin_ref` and `as_pin_mut` in the "Adapters for
working with references" overview.
Reword some headings about transformation methods.
Reclassify `map`, `map_or`, `map_or_else`, `map_err`, etc. to more
accurately reflect which variants they transform.
Document `Debug` requirement for `get_or_insert_default`.
Reword text about `take` and `replace` to be more accurate.
Add examples for the `Product` and `Sum` traits.
Also:
Move link reference definitions closer to their uses. Warn about making
link reference definintions for `err` and `ok`. Avoid making other link
reference definitions that might conflict in the future (foreign methods
that share a name with local ones, etc.)
Write out the generics of `Option` and `Result` when the following
text refers to the type parameters.
Due to the std/alloc split, it is not possible to make
`alloc::collections::TryReserveError::AllocError` non-exhaustive without
having an unstable, doc-hidden method to construct (which negates the
benefits from `#[non_exhaustive]`.
Document associativity of iterator folds.
Document the associativity of `Iterator::fold` and
`DoubleEndedIterator::rfold` and add examples demonstrating this.
Add links to direct users to the fold of the opposite associativity.
Better errors for Debug and Display traits
Currently, if someone tries to pass value that does not implement `Debug` or `Display` to a formatting macro, they get a very verbose and confusing error message. This PR changes the error messages for missing `Debug` and `Display` impls to be less overwhelming in this case, as suggested by #85844. I was a little less aggressive in changing the error message than that issue proposed. Still, this implementation would be enough to reduce the number of messages to be much more manageable.
After this PR, information on the cause of an error involving a `Debug` or `Display` implementation would suppressed if the requirement originated within a standard library macro. My reasoning was that errors originating from within a macro are confusing when they mention details that the programmer can't see, and this is particularly problematic for `Debug` and `Display`, which are most often used via macros. It is possible that either a broader or a narrower criterion would be better. I'm quite open to any feedback.
Fixes#85844.
Add comments around code where ordering is important due for panic-safety
Iterators contain arbitrary code which may panic. Unsafe code has to be
careful to do its state updates at the right point between calls that may panic.
As requested in https://github.com/rust-lang/rust/pull/86452#discussion_r655153948
r? `@RalfJung`