rewrote documentation for thread::yield_now()
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 implemented using yield_now. (They are not, except for
a corner case).
Rename some Rust 2021 lints to better names
Based on conversation in https://github.com/rust-lang/rust/issues/85894.
Rename a bunch of Rust 2021 related lints:
Lints that are officially renamed because they are already in beta or stable:
* `disjoint_capture_migration` => `rust_2021_incompatible_closure_captures`
* `or_patterns_back_compat` => `rust_2021_incompatible_or_patterns`
* `non_fmt_panic` => `non_fmt_panics`
Lints that are renamed but don't require any back -compat work since they aren't yet in stable:
* `future_prelude_collision` => `rust_2021_prelude_collisions`
* `reserved_prefix` => `rust_2021_token_prefixes`
Lints that have been discussed but that I did not rename:
* ~`non_fmt_panic` and `bare_trait_object`: is making this plural worth the headache we might cause users?~
* `array_into_iter`: I'm unsure of a good name and whether bothering users with a name change is worth it.
r? `@nikomatsakis`
Add Integer::log variants
_This is another attempt at landing https://github.com/rust-lang/rust/pull/70835, which was approved by the libs team but failed on Android tests through Bors. The text copied here is from the original issue. The only change made so far is the addition of non-`checked_` variants of the log methods._
_Tracking issue: #70887_
---
This implements `{log,log2,log10}` methods for all integer types. The implementation was provided by `@substack` for use in the stdlib.
_Note: I'm not big on math, so this PR is a best effort written with limited knowledge. It's likely I'll be getting things wrong, but happy to learn and correct. Please bare with me._
## Motivation
Calculating the logarithm of a number is a generally useful operation. Currently the stdlib only provides implementations for floats, which means that if we want to calculate the logarithm for an integer we have to cast it to a float and then back to an int.
> would be nice if there was an integer log2 instead of having to either use the f32 version or leading_zeros() which i have to verify the results of every time to be sure
_— [`@substack,` 2020-03-08](https://twitter.com/substack/status/1236445105197727744)_
At higher numbers converting from an integer to a float we also risk overflows. This means that Rust currently only provides log operations for a limited set of integers.
The process of doing log operations by converting between floats and integers is also prone to rounding errors. In the following example we're trying to calculate `base10` for an integer. We might try and calculate the `base2` for the values, and attempt [a base swap](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules) to arrive at `base10`. However because we're performing intermediate rounding we arrive at the wrong result:
```rust
// log10(900) = ~2.95 = 2
dbg!(900f32.log10() as u64);
// log base change rule: logb(x) = logc(x) / logc(b)
// log2(900) / log2(10) = 9/3 = 3
dbg!((900f32.log2() as u64) / (10f32.log2() as u64));
```
_[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0)_
This is somewhat nuanced as a lot of the time it'll work well, but in real world code this could lead to some hard to track bugs. By providing correct log implementations directly on integers we can help prevent errors around this.
## Implementation notes
I checked whether LLVM intrinsics existed before implementing this, and none exist yet. ~~Also I couldn't really find a better way to write the `ilog` function. One option would be to make it a private method on the number, but I didn't see any precedent for that. I also didn't know where to best place the tests, so I added them to the bottom of the file. Even though they might seem like quite a lot they take no time to execute.~~
## References
- [Log rules](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules)
- [Rounding error playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0)
- [substack's tweet asking about integer log2 in the stdlib](https://twitter.com/substack/status/1236445105197727744)
- [Integer Logarithm, A. Jaffer 2008](https://people.csail.mit.edu/jaffer/III/ilog.pdf)
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 😄