Commit graph

1930 commits

Author SHA1 Message Date
Guillaume Gomez
eb54ddd123
Rollup merge of #87279 - sunfishcode:document-unix-argv, r=RalfJung
Add comments explaining the unix command-line argument support.

Following up on #87236, add comments to the unix command-line argument
support explaining that the code doesn't mutate the system-provided
argc/argv, and that this is why the code doesn't need a lock or special
memory ordering.

r? ```@RalfJung```
2021-07-21 15:52:49 +02:00
Dominik Stolz
c3321d3eb3 Add tracking issue and link to man-page 2021-07-21 10:49:11 +02:00
Dominik Stolz
619fd96868 Add PidFd type and seal traits
Improve docs

Split do_fork into two

Make do_fork unsafe

Add target attribute to create_pidfd field in Command

Add method to get create_pidfd value
2021-07-21 10:49:11 +02:00
Josh Triplett
ef03de2e6a Typo fix
Co-authored-by: bjorn3 <bjorn3@users.noreply.github.com>
2021-07-21 10:49:11 +02:00
Aaron Hill
694be09b7b Add Linux-specific pidfd process extensions
Background:

Over the last year, pidfd support was added to the Linux kernel. This
allows interacting with other processes. In particular, this allows
waiting on a child process with a timeout in a race-free way, bypassing
all of the awful signal-handler tricks that are usually required.

Pidfds can be obtained for a child process (as well as any other
process) via the `pidfd_open` syscall. Unfortunately, this requires
several conditions to hold in order to be race-free (i.e. the pid is not
reused).
Per `man pidfd_open`:

```
· the disposition of SIGCHLD has not been explicitly set to SIG_IGN
 (see sigaction(2));

· the SA_NOCLDWAIT flag was not specified while establishing a han‐
 dler for SIGCHLD or while setting the disposition of that signal to
 SIG_DFL (see sigaction(2)); and

· the zombie process was not reaped elsewhere in the program (e.g.,
 either by an asynchronously executed signal handler or by wait(2)
 or similar in another thread).

If any of these conditions does not hold, then the child process
(along with a PID file descriptor that refers to it) should instead
be created using clone(2) with the CLONE_PIDFD flag.
```

Sadly, these conditions are impossible to guarantee once any libraries
are used. For example, C code runnng in a different thread could call
`wait()`, which is impossible to detect from Rust code trying to open a
pidfd.

While pid reuse issues should (hopefully) be rare in practice, we can do
better. By passing the `CLONE_PIDFD` flag to `clone()` or `clone3()`, we
can obtain a pidfd for the child process in a guaranteed race-free
manner.

This PR:

This PR adds Linux-specific process extension methods to allow obtaining
pidfds for processes spawned via the standard `Command` API. Other than
being made available to user code, the standard library does not make
use of these pidfds in any way. In particular, the implementation of
`Child::wait` is completely unchanged.

Two Linux-specific helper methods are added: `CommandExt::create_pidfd`
and `ChildExt::pidfd`. These methods are intended to serve as a building
block for libraries to build higher-level abstractions - in particular,
waiting on a process with a timeout.

I've included a basic test, which verifies that pidfds are created iff
the `create_pidfd` method is used. This test is somewhat special - it
should always succeed on systems with the `clone3` system call
available, and always fail on systems without `clone3` available. I'm
not sure how to best ensure this programatically.

This PR relies on the newer `clone3` system call to pass the `CLONE_FD`,
rather than the older `clone` system call. `clone3` was added to Linux
in the same release as pidfds, so this shouldn't unnecessarily limit the
kernel versions that this code supports.

Unresolved questions:
* What should the name of the feature gate be for these newly added
  methods?
* Should the `pidfd` method distinguish between an error occurring
  and `create_pidfd` not being called?
2021-07-21 10:49:11 +02:00
bors
cf932aa584 Auto merge of #86847 - tlyu:stdin-forwarders, r=joshtriplett
add `Stdin::lines`, `Stdin::split` forwarder methods

Add forwarder methods `Stdin::lines` and `Stdin::split`, which consume
and lock a `Stdin` handle, and forward on to the corresponding `BufRead`
methods. This should make it easier for beginners to use those iterator
constructors without explicitly dealing with locks or lifetimes.

Replaces #86412.
~~Based on #86846 to get the tracking issue number for the `stdio_locked` feature.~~ Rebased after merge, so it's only one commit now.

r? `@joshtriplett`
`@rustbot` label +A-io +C-enhancement +D-newcomer-roadblock +T-libs-api
2021-07-21 06:06:37 +00:00
inquisitivecrystal
e7fe2dfef2 Use hashbrown's extend_reserve() in HashMap 2021-07-20 15:56:36 -07:00
Dan Gohman
2a56a681c4 Add comments explaining the unix command-line argument support.
Following up on #87236, add comments to the unix command-line argument
support explaining that the code doesn't mutate the system-provided
argc/argv, and that this is why the code doesn't need a lock or special
memory ordering.
2021-07-19 07:16:37 -07:00
Guillaume Gomez
6df9df7e36
Rollup merge of #87236 - sunfishcode:avoid-locking-args, r=joshtriplett
Simplify command-line argument initialization on unix

Simplify Rust's command-line argument initialization code on unix:
 - The cleanup code isn't needed, because it was just zeroing out non-owning variables at runtime cleanup time. After 91c3eee173, Rust's command-line initialization code on unix no longer allocates `CString`s and a `Vec` at startup time.
 - The `Mutex` isn't needed; if there's somehow a call to `args()` before argument initialization has happened, the code returns return an empty list, which we can do with a null check.

With these changes, a simple cdylib that doesn't use threads avoids getting `pthread_mutex_lock`/`pthread_mutex_unlock` in its symbol table.
2021-07-19 11:37:45 +02:00
Guillaume Gomez
65b7aa98c7
Rollup merge of #87227 - bstrie:asm2arch, r=Amanieu
Move asm! and global_asm! to core::arch

Follow-up to https://github.com/rust-lang/stdarch/pull/1183 .

Implements the libs-api team decision from rust-lang/rust#84019 (comment) .

In order to not break nightly users, this PR also adds the newly-moved items to the prelude. However, a decision will need to be made before stabilization as to whether these items should remain in the prelude. I will file an issue for this separately.

Fixes #84019 .

r? `@Amanieu`
2021-07-19 11:37:44 +02:00
bstrie
f26fbe2453 Move asm! and global_asm! to core::arch 2021-07-18 18:30:58 -04:00
Yuki Okushi
07faa2e32c
Rollup merge of #87170 - xFrednet:clippy-5393-add-diagnostic-items, r=Manishearth,oli-obk
Add diagnostic items for Clippy

This adds a bunch of diagnostic items to `std`/`core`/`alloc` functions, structs and traits used in Clippy. The actual refactorings in Clippy to use these items will be done in a different PR in Clippy after the next sync.

This PR doesn't include all paths Clippy uses, I've only gone through the first 85 lines of Clippy's [`paths.rs`](ecf85f4bdc/clippy_utils/src/paths.rs) (after rust-lang/rust-clippy#7466) to get some feedback early on. I've also decided against adding diagnostic items to methods, as it would be nicer and more scalable to access them in a nicer fashion, like adding a `is_diagnostic_assoc_item(did, sym::Iterator, sym::map)` function or something similar (Suggested by `@camsteffen` [on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/147480-t-compiler.2Fwg-diagnostics/topic/Diagnostic.20Item.20Naming.20Convention.3F/near/225024603))

There seems to be some different naming conventions when it comes to diagnostic items, some use UpperCamelCase (`BinaryHeap`) and some snake_case (`hashmap_type`). This PR uses UpperCamelCase for structs and traits and snake_case with the module name as a prefix for functions. Any feedback on is this welcome.

cc: rust-lang/rust-clippy#5393

r? `@Manishearth`
2021-07-18 14:21:57 +09:00
Dan Gohman
c3df0ae97f x.py fmt 2021-07-17 18:31:51 -07:00
Dan Gohman
9bb11ba511 Remove an unnecessary Mutex around argument initialization.
In the command-line argument initialization code, remove the Mutex
around the `ARGV` and `ARGC` variables, and simply check whether
ARGV is non-null before dereferencing it. This way, if either of
ARGV or ARGC is not initialized, we'll get an empty argument list.

This allows simple cdylibs to avoid having
`pthread_mutex_lock`/`pthread_mutex_unlock` appear in their symbol
tables if they don't otherwise use threads.
2021-07-17 13:35:38 -07:00
Dan Gohman
46010c4618 Remove args cleanup code.
As of 91c3eee173, the global ARGC and ARGV
no longer reference dynamically-allocated memory, so they don't need to
be cleaned up.
2021-07-17 13:35:27 -07:00
Jane Lusby
93b7aee2da rename assert_matches module 2021-07-16 09:18:14 -07:00
inquisitivecrystal
803f79db48 Stabilize into_parts() and into_error() 2021-07-15 16:44:56 -07:00
xFrednet
d38f2b0cc1 Added diagnostic items to structs and traits for Clippy 2021-07-15 23:57:02 +02:00
Yuki Okushi
b99f7edad2
Rollup merge of #87081 - a1phyr:add_wasi_ext_tracking_issue, r=dtolnay
Add tracking issue number to `wasi_ext`

Feature `wasi_ext` is tracked by #71213 but is was not in the source code.
2021-07-15 21:19:18 +09:00
Yuki Okushi
a5acb7b4ba
Rollup merge of #86947 - m-ou-se:assert-matches-to-submodule, r=yaahc
Move assert_matches to an inner module

Fixes #82913
2021-07-15 21:19:16 +09:00
Vadim Petrochenkov
6c9ea1e8a9 expand: Support helper attributes for built-in derive macros 2021-07-13 21:59:22 +03:00
Taylor Yu
339ce4fee8 add Stdin::lines, Stdin::split forwarder methods
Add forwarder methods `Stdin::lines` and `Stdin::split`, which consume
and lock a `Stdin` handle, and forward on to the corresponding `BufRead`
methods. This should make it easier for beginners to use those iterator
constructors without explicitly dealing with locks or lifetimes.
2021-07-12 23:43:42 -05:00
Yuki Okushi
bcacfe7c64
Rollup merge of #86846 - tlyu:stdio-locked-tracking, r=joshtriplett
stdio_locked: add tracking issue

Add the tracking issue number #86845 to the stability attributes for the implementation in #86799.

r? `@joshtriplett`
`@rustbot` label +A-io +C-cleanup +T-libs-api
2021-07-13 08:54:30 +09:00
Yuki Okushi
749a589746
Rollup merge of #86811 - soerenmeier:remove_remaining, r=yaahc
Remove unstable `io::Cursor::remaining`

Adding `io::Cursor::remaining` in #86037 caused a conflict with the implementation of `bytes::Buf` for `io::Cursor`, leading to an error in nightly, see https://github.com/rust-lang/rust/issues/86369#issuecomment-867723485.

This fixes the error by temporarily removing the `remaining` function.

r? `@yaahc`
2021-07-13 08:54:28 +09:00
Benoît du Garreau
6e47c8db73 Add tracking issue number to wasi_ext 2021-07-12 15:01:39 +02:00
Yuki Okushi
5541d1ac16
Rollup merge of #86951 - cyberia-ng:fp-negative-zero-sqrt-docs, r=Mark-Simulacrum
[docs] Clarify behaviour of f64 and f32::sqrt when argument is negative zero

From IEEE 754 section 6.3:
> Except that squareRoot(−0) shall be −0, every numeric squareRoot result shall have a positive sign.
2021-07-12 04:31:59 +09:00
bors
dfd7b8d03f Auto merge of #85953 - inquisitivecrystal:weak-linkat-in-fs-hardlink, r=joshtriplett
Fix linker error

Currently, `fs::hard_link` determines whether platforms have `linkat` based on the OS, and uses `link` if they don't. However, this heuristic does not work well if a platform provides `linkat` on newer versions but not on older ones. On old MacOS, this currently causes a linking error.

This commit fixes `fs::hard_link` by telling it to use `weak!` on macOS. This means that, on  that operating system, we now check for `linkat` at runtime and use `link` if it is not available.

Fixes #80804.

`@rustbot` label T-libs-impl
2021-07-10 21:42:40 +00:00
Aris Merchant
5999a5fbdc Make tests pass on old macos
On old macos systems, `fs::hard_link()` will follow symlinks.
This changes the test `symlink_hard_link` to exit early on
these systems, so that tests can pass.
2021-07-10 12:59:25 -07:00
Aris Merchant
fd0cb0cdc2 Change weak! and linkat! to macros 2.0
`weak!` is needed in a test in another module. With macros
1.0, importing `weak!` would require reordering module
declarations in `std/src/lib.rs`, which is a bit too
evil.
2021-07-10 12:55:09 -07:00
Yuki Okushi
0ca5fc2e33
Rollup merge of #87011 - RalfJung:thread-id-supply-shortage, r=nagisa
avoid reentrant lock acquire when ThreadIds run out

Discovered by `@bjorn3`
2021-07-11 01:15:40 +09:00
Ralf Jung
dbc2b55baf rename variable 2021-07-10 14:14:09 +02:00
Ralf Jung
2750d3ac6a avoid reentrant lock acquire when ThreadIds run out 2021-07-10 11:54:38 +02:00
Aris Merchant
5022c0638d Update docs for fs::hard_link 2021-07-09 23:24:36 -07:00
Aris Merchant
dc38d87505 Fix linker error
This makes `fs::hard_link` use weak! for some platforms,
thereby preventing a linker error.
2021-07-09 23:24:36 -07:00
Kornel
bc67f6bc95 Debug formatting of raw_arg() 2021-07-09 14:24:34 +01:00
Kornel
8f9d0f12eb Use AsRef in CommandExt for raw_arg 2021-07-09 14:09:48 +01:00
Kornel
d868da7796 Unescaped command-line arguments for Windows
Fixes #29494
2021-07-09 14:09:48 +01:00
Kornel
fcd5cecdcf Test escaping of trialing slashes in Windows command-line args 2021-07-09 14:09:48 +01:00
Guillaume Gomez
d12b16887b
Rollup merge of #86726 - sexxi-goose:use-diagnostic-item-for-rfc2229-migration, r=nikomatsakis
Use diagnostic items instead of lang items for rfc2229 migrations

This PR removes the `Send`, `UnwindSafe` and `RefUnwindSafe` lang items introduced in https://github.com/rust-lang/rust/pull/84730, and uses diagnostic items instead to check for `Send`, `UnwindSafe` and `RefUnwindSafe` traits for RFC2229 migrations.

r? ```@nikomatsakis```
2021-07-08 18:30:33 +02:00
Mara Bos
e3044432c7 Move [debug_]assert_matches to mod {core, std}::assert. 2021-07-08 02:33:36 +02:00
cyberia
a853a49425 Clarify behaviour of f64 and f32::sqrt when argument is negative zero 2021-07-07 18:22:17 +01:00
Christiaan Dirkx
a674ae6f76 Add documentation for Ipv6MulticastScope 2021-07-07 14:41:06 +02:00
Yuki Okushi
9aee3c2883
Rollup merge of #86916 - godmar:@godmar/thread-yield-documentation-fix, r=joshtriplett
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).
2021-07-07 12:17:44 +09:00
Yuki Okushi
9bbc470e97
Rollup merge of #80918 - yoshuawuyts:int-log2, r=m-ou-se
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)
2021-07-07 12:17:32 +09:00
Godmar Back
fb464a3b39 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 implementing using yield_now. (They are not, except for
a corner case).
2021-07-06 15:50:42 -04:00
Yoh Deadfall
4867a21225 Stabilize Vec<T>::shrink_to 2021-07-06 10:37:49 +03:00
Aris Merchant
d9752c7d84 Improve env var getter docs 2021-07-05 22:19:30 -07:00
Aris Merchant
a12107afaa Make getenv return an Option instead of a Result 2021-07-05 22:19:23 -07:00
Aris Merchant
f2c0f29248 Change env var getters to error recoverably
Before this, `std`'s env var getter functions would panic on
receiving certain invalid inputs. This commit makes them
return a `None` or `Err` instead.
2021-07-05 22:13:38 -07:00
Yuki Okushi
470ed70a86
Rollup merge of #86852 - Amanieu:remove_doc_aliases, r=joshtriplett
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`
2021-07-06 02:33:16 +09:00
Yuki Okushi
2bc7d4d70a
Rollup merge of #86794 - inquisitivecrystal:seek-rewind, r=m-ou-se
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.
2021-07-06 02:33:15 +09:00
Yuki Okushi
add24d2f4f
Rollup merge of #85377 - ijackson:abort-docs, r=m-ou-se
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
2021-07-06 02:33:13 +09:00
Yuki Okushi
1fcd9abbb1
Rollup merge of #83581 - arennow:dir_entry_ext_unix_borrow_name, r=m-ou-se
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(())
}
```
2021-07-06 02:33:06 +09:00
Mara Bos
469f4674fb
Enable dir_entry_ext2 feature in doc test.
Co-authored-by: Yuki Okushi <jtitor@2k36.org>
2021-07-05 16:26:54 +02:00
Mara Bos
08d912fdcc s/die/terminate/ in abort documentation. 2021-07-05 12:43:45 +02:00
Ian Jackson
4e7c348140 abort docs: Document buffer non-flushing
There is discussion of this in #40230 which requests clarification.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-07-05 12:43:02 +02:00
Ian Jackson
a8bb7fa76b 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 (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>
2021-07-05 12:43:00 +02:00
Yuki Okushi
0e4c4cd076
Rollup merge of #86864 - GuillaumeGomez:example-write-vectored, r=JohnTitor
Add missing code example for Write::write_vectored
2021-07-05 07:13:28 +09:00
Guillaume Gomez
f742cde948 Add missing code example for Write::write_vectored 2021-07-04 19:23:29 +02:00
bors
71a567fae4 Auto merge of #86833 - crlf0710:remove-std-raw-mod, r=SimonSapin
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`
2021-07-04 04:04:47 +00:00
bors
1540711946 Auto merge of #85270 - ChrisDenton:win-env-case, 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
2021-07-04 01:24:05 +00:00
Taylor Yu
24d6536be9 stdio_locked: add tracking issue 2021-07-03 11:35:47 -05:00
bors
a8b8558f08 Auto merge of #86799 - tlyu:stdio-locked, r=joshtriplett
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
2021-07-03 10:40:53 +00:00
Charles Lew
0d1919c7ab Remove the deprecated core::raw and std::raw module. 2021-07-03 14:03:27 +08:00
bors
fdd9a07147 Auto merge of #79965 - ijackson:moreerrnos, r=joshtriplett
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)
2021-07-03 04:12:36 +00:00
Christiaan Dirkx
c93cb40b90 Move os_str_bytes to sys::unix and reuse it on other platforms. 2021-07-03 03:01:36 +02:00
Taylor Yu
c58ceb7a42 stdio_locked: updates based on feedback
Rename methods to `into_locked`. Remove type aliases for owned locks.
2021-07-02 15:56:56 -05:00
Yuki Okushi
df55204afb
Rollup merge of #86807 - tversteeg:patch-1, r=bjorn3
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
2021-07-03 03:15:13 +09:00
Yuki Okushi
6107340483
Rollup merge of #86803 - xfix:remove-unnecessary-ampersand-from-command-args-calls, r=joshtriplett
Remove & from Command::args calls in documentation

Now that arrays implement `IntoIterator`, using `&` is no longer necessary. This makes examples easier to understand.
2021-07-03 03:15:12 +09:00
Yuki Okushi
fb736d96c3
Rollup merge of #85001 - CDirkx:bytestring, r=JohnTitor
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`.
2021-07-03 03:15:09 +09:00
Sören Meier
626bab5a7c Remove unstable Cursor::remaining 2021-07-02 16:23:44 +02:00
Thomas Versteeg
d3bf89b302
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.
2021-07-02 09:37:00 +00:00
Konrad Borowski
18715c0753 Remove & from Command::args calls in documentation
Now that arrays implement `IntoIterator`, using
`&` is no longer necessary. This makes examples
easier to understand.
2021-07-02 11:14:42 +02:00
bors
f9fa13f705 Auto merge of #85746 - m-ou-se:io-error-other, r=joshtriplett
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`
2021-07-02 09:01:42 +00:00
Taylor Yu
b3db5cd46c 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.
2021-07-01 20:55:46 -05:00
Aris Merchant
6d34a2e007 Stabilize Seek::rewind 2021-07-01 15:08:20 -07:00
Yuki Okushi
3ec8e6c5fd
Rollup merge of #86783 - mark-i-m:mutex-drop-unsized, r=Xanewok
Move Mutex::unlock to T: ?Sized

r? ``@mbrubeck``

cc https://github.com/rust-lang/rust/issues/81872
2021-07-02 06:20:33 +09:00
Janik Rabe
2dd69aaafc Document iteration order of retain functions
For `HashSet` and `HashMap`, this simply copies the comment from
`BinaryHeap::retain`.

For `BTreeSet` and `BTreeMap`, this adds an additional guarantee that
wasn't previously documented. I think that because these data structures
are inherently ordered and other functions guarantee ordered iteration,
it makes sense to provide this guarantee for `retain` as well.
2021-07-01 22:15:13 +01:00
Mark Mansi
057bc91399 Move Mutex::unlock to T: ?Sized 2021-07-01 12:04:41 -05:00
bstrie
2db05230d3 impl From<[(K, V); N]> for std::collections 2021-06-30 17:28:17 -04:00
Amanieu d'Antras
e2536bb271 Remove "length" doc aliases 2021-06-30 20:28:51 +01:00
Amanieu d'Antras
fc2705d707 Remove "delete" doc aliases 2021-06-30 20:28:51 +01:00
Ian Jackson
a7e88e0dad impl Default, Copy, Clone for std::io::Sink and Empty
The omission of Sink: Default is causing me a slight inconvenience in
a test harness.  There seems little reason for this and Empty not to
be Clone and Copy too.

I have made all three of these insta-stable, because:

AIUI Copycan only be derived, and I was not able to find any
examples of how to unstably derive it.  I think it is probably not
possible.

I hunted through the git history for precedent and found

  79b8ad84c8
  Implement `Copy` for `IoSlice`
  https://github.com/rust-lang/rust/pull/69403

which was also insta-stable.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-30 11:58:25 +01:00
Roxane Fruytier
06afafd492 Use diagnostic items to check for Send, UnwindSafe and RefUnwindSafe traits 2021-06-29 17:47:57 -04:00
Roxane Fruytier
3e569dd2df Remove lang items Send, UnwindSafe and RefUnwindSafe 2021-06-29 17:47:57 -04:00
Mark Rousskov
06661ba759 Update to new bootstrap compiler 2021-06-28 11:30:49 -04:00
bors
17ea490310 Auto merge of #82624 - ojeda:rwlock-example-deadlock, r=JohnTitor
RWLock: Add deadlock example

Suggested in https://github.com/rust-lang/rust/pull/82596 but it was a bit too late.

`@matklad` `@azdavis` `@sfackler`
2021-06-28 09:58:06 +00:00
bors
481971978f Auto merge of #86586 - Smittyvb:https-everywhere, r=petrochenkov
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)
2021-06-26 08:24:31 +00:00
bors
6830052c7b Auto merge of #86637 - ehuss:spellings, r=dtolnay
Fix a few misspellings.
2021-06-26 05:09:27 +00:00
Eric Huss
6235e6f93f Fix a few misspellings. 2021-06-25 13:18:56 -07:00
Mara Bos
cc90733008 Restore original ordering of ErrorKind::Other. 2021-06-25 19:04:08 +00:00
Yoshua Wuyts
9f579968cd Add Integer::{log,log2,log10} variants 2021-06-25 18:52:46 +02:00
Yuki Okushi
9e4649995f
Rollup merge of #86592 - jhpratt:non_exhaustive, r=JohnTitor
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
2021-06-26 00:42:12 +09:00
bors
cbeda5cbeb Auto merge of #86467 - ChrisDenton:win-env-clear, r=JohnTitor
Windows: Fix `Command::env_clear` so it works if no variables are set

Previously, it would error unless at least one new environment variable was added. The missing null presumably meant that Windows was reading random memory in that case.

See: [CreateProcessW](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) (scroll down to `lpEnvironment`). Essentially the environment block is a null terminated list of null terminated strings and an empty list is `\0\0` and not `\0`.

EDIT: Oh, [CreateEnvironmentBlock](https://docs.microsoft.com/en-gb/windows/win32/api/userenv/nf-userenv-createenvironmentblock) states this much more explicitly.

Fixes #31259
2021-06-24 17:37:29 +00:00
Chris Denton
16145a9952
Test that env_clear works on Windows 2021-06-24 09:32:24 +01:00
Jacob Pratt
3f14f4b3ce
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]`.
2021-06-24 04:16:11 -04:00
Smitty
bdfcb88e8b Use HTTPS links where possible 2021-06-23 16:26:46 -04:00
bors
75ed34223a Auto merge of #84910 - eopb:stabilize_int_error_matching, r=yaahc
stabilize `int_error_matching`

closes #22639

> It has been over half a year since https://github.com/rust-lang/rust/pull/77640#pullrequestreview-511263516, and the indexing question is rejected in https://github.com/rust-lang/rust/pull/79728#pullrequestreview-633030341, so I guess we can submit another stabilization attempt? 😉

_Originally posted by `@kennytm` in https://github.com/rust-lang/rust/issues/22639#issuecomment-831738266_
2021-06-22 09:30:15 +00:00
Ethan Brierley
52a6885c50 postpone stabilizaton by one release 2021-06-22 10:20:56 +01:00
bors
2c04f0bb17 Auto merge of #86527 - JohnTitor:rollup-cbu78g4, r=JohnTitor
Rollup of 11 pull requests

Successful merges:

 - #85054 (Revert SGX inline asm syntax)
 - #85182 (Move `available_concurrency` implementation to `sys`)
 - #86037 (Add `io::Cursor::{remaining, remaining_slice, is_empty}`)
 - #86114 (Reopen #79692 (Format symbols under shared frames))
 - #86297 (Allow to pass arguments to rustdoc-gui tool)
 - #86334 (Resolve type aliases to the type they point to in intra-doc links)
 - #86367 (Fix comment about rustc_inherit_overflow_checks in abs().)
 - #86381 (Add regression test for issue #39161)
 - #86387 (Remove `#[allow(unused_lifetimes)]` which is now unnecessary)
 - #86398 (Add regression test for issue #54685)
 - #86493 (Say "this enum variant takes"/"this struct takes" instead of "this function takes")

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-06-22 01:14:31 +00:00
Yuki Okushi
7ee6b8bc43
Rollup merge of #86114 - JDuchniewicz:feat/panic-frame-fmt, r=yaahc
Reopen #79692 (Format symbols under shared frames)

Reopening #79692.
2021-06-22 07:37:47 +09:00
Yuki Okushi
4463b08652
Rollup merge of #86037 - soerenmeier:cursor_remaining, r=yaahc
Add `io::Cursor::{remaining, remaining_slice, is_empty}`

Tracking issue: #86369

I came across an inconvenience when answering the following [Stack Overflow](https://stackoverflow.com/questions/67831170) question.
To get the remaining slice you have to call `buff.fill_buf().unwrap()`. Which in my opinion doesn't really tell you what is returned (in the context of Cursor). To improve readability and convenience when using Cursor i propose adding the method `remaining`.

The next thing i found inconvenient (unnecessary long) was detecting if the cursor reached the end. There are a few ways this can be achieved right now:
- `buff.fill_buf().unwrap().is_empty()`
- `buff.position() >= buff.get_ref().len()`
- `buff.bytes().next().is_none()`

Which all seem a bit unintuitive, hidden in trait documentations or just a bit long for such a simple task.
Therefor i propose another method called `is_empty`, maybe with another name, since this one may leave room for interpretation on what really is empty (the underlying slice, the remaining slice or maybe the position).

Since it seemed easier to create this PR instead of an RFC i did that, if an RFC is wanted, i can close this PR and write an RFC first.
2021-06-22 07:37:46 +09:00
Yuki Okushi
7f1a4a287f
Rollup merge of #85182 - CDirkx:available_concurrency, r=JohnTitor
Move `available_concurrency` implementation to `sys`

This splits out the platform-specific implementation of `available_concurrency` to the corresponding platforms under `sys`. No changes are made to the implementation.

Tidy didn't lint against this code being originally added outside of `sys` because of a bug (see #84677), this PR also reverts the exclusion that was introduced in that bugfix.

Tracking issue of `available_concurrency`: #74479
2021-06-22 07:37:46 +09:00
Yuki Okushi
d6e344d45d
Rollup merge of #85054 - jethrogb:jb/sgx-inline-asm, r=Amanieu
Revert SGX inline asm syntax

This was erroneously changed in #83387
2021-06-22 07:37:42 +09:00
bors
4573a4a879 Auto merge of #86383 - shamatar:slice_len_lowering, r=bjorn3
Add MIR pass to lower call to `core::slice::len` into `Len` operand

During some larger experiment with range analysis I've found that code like `let l = slice.len()` produces different MIR then one found in bound checks. This optimization pass replaces terminators that are calls to `core::slice::len` with just a MIR operand and Goto terminator.

It uses some heuristics to remove the outer borrow that is made to call `core::slice::len`, but I assume it can be eliminated, just didn't find how.

Would like to express my gratitude to `@oli-obk` who helped me a lot on Zullip
2021-06-21 22:24:13 +00:00
Christiaan Dirkx
059008f033 Merge sys_common::bytestring into os_str_bytes 2021-06-21 12:57:14 +02:00
Christiaan Dirkx
888418a079 Use Unsupported on platforms where available_concurrency is not implemented. 2021-06-21 11:31:07 +02:00
Christiaan Dirkx
9063edaf3b Move available_concurrency implementation to sys 2021-06-21 11:01:46 +02:00
bors
dd941450fb Auto merge of #84967 - CDirkx:os_str_ext, r=m-ou-se
Move `OsStringExt` and `OsStrExt` to `std::os`

Moves the `OsStringExt` and `OsStrExt` traits and implementations from `sys_common` to `os`. `sys_common` is for abstractions over `sys` and shouldn't really contain publicly exported items.

This does introduce some duplication: the traits and implementations are now duplicated in `unix`, `wasi`, `hermit`, and `sgx`. However, I would argue that this duplication is no different to how something like `MetadataExt` is duplicated in `linux`, `vxworkx`, `redox`, `solaris` etc. The duplication also matches the fact that the traits on different platforms are technically distinct types: any platform is free to add it's own extra methods to the extension trait.
2021-06-20 16:42:13 +00:00
Ian Jackson
333d42de2c ErrorKind: Add missing full stops
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-20 17:16:24 +01:00
Ian Jackson
f00975ea7d ErrorKind::FilesystemLoop: Generalise dscription
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-20 17:05:18 +01:00
Alex Vlasov
aa53928ed7 Squashed implementation of the pass 2021-06-20 16:09:42 +02:00
Christiaan Dirkx
ad7b8975e0 Add comment to std::os::unix::ffi::os_str explaining that the module is reused on other platforms. 2021-06-20 12:06:19 +02:00
Christiaan Dirkx
835561ac5b Make os_str_bytes::{Buf, Slice} pub and repr(transparent) 2021-06-20 11:55:26 +02:00
Christiaan Dirkx
1a96d2272e Move OsStringExt and OsStrExt to std::os 2021-06-20 11:55:01 +02:00
bors
192920c22b Auto merge of #86463 - fee1-dead:fixed-encode_wide, r=m-ou-se
Account for self.extra in size_hint for EncodeWide

Fixes #86414.
2021-06-20 02:18:51 +00:00
bors
6b354a1382 Auto merge of #86034 - nagisa:nagisa/rt-soundness, r=m-ou-se
Change entry point to 🛡️ against 💥 💥-payloads

Guard against panic payloads panicking within entrypoints, where it is
UB to do so.

Note that there are a number of tradeoffs to consider. For instance, I
considered guarding against accidental panics inside the `rt::init` and
`rt::cleanup` code as well, as it is not all that obvious these may not
panic, but doing so would mean that we initialize certain thread-local
slots unconditionally, which has its own problems.

Fixes #86030
r? `@m-ou-se`
2021-06-19 17:05:08 +00:00
Christiaan Dirkx
a26237e634 Remove Ipv4Addr::is_ietf_protocol_assignment 2021-06-19 15:03:02 +02:00
Simonas Kazlauskas
9c9a0da132 Change entry point to 🛡️ against 💥 💥-payloads
Guard against panic payloads panicking within entrypoints, where it is
UB to do so.

Note that there are a number of implementation approaches to consider.
Some simpler, some more complicated. This particular solution is nice in
that it also guards against accidental implementation issues in
various pieces of runtime code, something we cannot prevent statically
right now.

Fixes #86030
2021-06-19 11:46:56 +03:00
Chris Denton
365a3586a9
Windows: Fix Command::env_clear so it works
Previously, it would error unless at least one new environment variable was added.
2021-06-19 09:46:34 +01:00
bors
39260f6d49 Auto merge of #86426 - hi-rustin:rustin-patch-lint-warn, r=Aaron1011
Lint for unused borrows as part of UNUSED_MUST_USE

close https://github.com/rust-lang/rust/issues/76264

base on https://github.com/rust-lang/rust/pull/76894

r? `@RalfJung`
2021-06-19 08:41:58 +00:00
Deadbeef
15cdb28f5b Account for self.extra in size_hint for EncodeWide 2021-06-19 12:59:22 +08:00
bors
ce1d5611a2 Auto merge of #85815 - YuhanLiin:buf-read-data-left, r=m-ou-se
Add has_data_left() to BufRead

This is a continuation of #40747 and also addresses #40745. The problem with the previous PR was that it had "eof" in its method name. This PR uses a more descriptive method name, but I'm open to changing it.
2021-06-18 20:11:51 +00:00
Ian Jackson
c8bddf3bd1 ErrorKind::NotSeekable: Fix reference to File::open()
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 19:40:31 +01:00
Ian Jackson
622a45d1b8 ErrorKind: Windows: Fix tidy
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 19:30:55 +01:00
Ian Jackson
58d0cec678 ErrorKind: Windows: Fix botched rebase
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 19:18:10 +01:00
Ian Jackson
1ec9454403 ErrorKind: Provide many more ErrorKinds, motivated by Unix errnos
Rationale for the mappings etc. is extensively discussed in the MR
  https://github.com/rust-lang/rust/pull/79965

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:51:53 +01:00
Ian Jackson
655053ed91 Windows error codes: Add two missing ones
For some reason these aren't in the mingw list.

We'll need them shortly.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:51:53 +01:00
Ian Jackson
8a4b1e4c0b Windows error codes: Add very very many from mingw
Dump mingw-64's error codes into our source tree.

I have verified with these runes:

  $ f=library/std/src/sys/windows/c/errors.rs
  $ diff -ub <(git-cat-file blob HEAD~:$f | sort) <(cat $f | perl -pe 's/WSABASEERR \+ (\d+)/10000 + $1/e' |sort) |grep ^- |less

that this does not change any existing values.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:51:53 +01:00
Ian Jackson
9580f3336b Windows error codes: Move to a separate module
We're going to add many more of these.

This commit is pure code motion, plus the necessary administrivia, as
I have veried with the following runes:

  $ git-diff HEAD~ | grep '^+' |sort >plus
  $ git-diff HEAD~ | grep '^-' | perl -pe 's/^-/+/' |sort >min
  $ diff -ub min plus |less

The output is precisely the expected `mod` and `use` directives.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:51:47 +01:00
Ian Jackson
e7fb1a71cd windows errors: Change type name for ERROR_SHARING_VIOLATION
DWORD is a type alias for u32, so this makes no difference.
But this entry is anomalous and in my forthcoming commits I am going
to import many errors wholesale, and I spotted that my wholesale
import didn't match what was here.

CC: Chris Denton <christophersdenton@gmail.com>
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:51:47 +01:00
Ian Jackson
2a38dfbe04 ErrorKind: Fix a spurious space
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 18:46:50 +01:00
bors
88ba8ad730 Auto merge of #85747 - maxwase:path-symlinks-methods, r=m-ou-se
Path methods — symlinks improvement

This PR adds symlink method for the `Path`.

Tracking issue: #85748
For the discussion you can see [internals topic](https://internals.rust-lang.org/t/path-methods-symlinks-improvement/14776)

P.S.
I'm not fully sure about `stable` attribute, correct me if I'm wrong.
2021-06-18 17:13:19 +00:00
Ian Jackson
d59d52e455 ErrorKind: Reformat the mapping table (windows)
use ErrorKind::*;

I don't feel confident enough about Windows things to reorder this
alphabetically

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 17:53:19 +01:00
Ian Jackson
5513faa512 ErrorKind: Reformat the mapping table (unix)
* Sort the single matches alphabetically.
* use ErrorKind::*;

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 17:45:04 +01:00
Ian Jackson
f092501737 ErrorKind: Reformat the error string table
* Sort alphabetically.
* use ErrorKind::*;

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-06-18 17:43:08 +01:00
Max Wase
01435fc83a no_run and ignore doc attributes 2021-06-18 14:17:21 +03:00
hi-rustin
88abd7d81d Lint for unused borrows as part of UNUSED_MUST_USE 2021-06-18 15:09:40 +08:00
YuhanLiin
99939c44c3 Update tracking issue 2021-06-17 23:17:16 -04:00
Mara Bos
a5dce6c99a
Rollup merge of #86357 - de-vri-es:simplify-repeated-cfg-ifs, r=m-ou-se
Rely on libc for correct integer types in os/unix/net/ancillary.rs.

This PR is a small maintainability improvement. It simplifies `unix/net/ancillary.rs` in `std` by removing the `cfg_ifs` for casting to the correct integer type, and just rely on libc to define the struct correctly.
2021-06-17 23:41:00 +02:00
Mara Bos
b7dd942e15
Rollup merge of #86202 - a1phyr:spec_io_bytes_size_hint, r=m-ou-se
Specialize `io::Bytes::size_hint` for more types

Improve the result of `<io::Bytes as Iterator>::size_hint` for some readers. I did not manage to specialize `SizeHint` for `io::Cursor`

Side question: would it be interesting for `io::Read` to have an optional `size_hint` method ?
2021-06-17 23:40:58 +02:00
Mara Bos
fcac478966
Rollup merge of #85925 - clarfonthey:lerp, r=m-ou-se
Linear interpolation

#71016 is a previous attempt at implementation that was closed by the author. I decided to reuse the feature request issue (#71015) as a tracking issue. A member of the rust-lang org will have to edit the original post to be formatted correctly as I am not the issue's original author.

The common name `lerp` is used because it is the term used by most code in a wide variety of contexts; it also happens to be the recently chosen name of the function that was added to C++20.

To ensure symmetry as a method, this breaks the usual ordering of the method from `lerp(a, b, t)` to `t.lerp(a, b)`. This makes the most sense to me personally, and there will definitely be discussion before stabilisation anyway.

Implementing lerp "correctly" is very dififcult even though it's a very common building-block used in all sorts of applications. A good prior reading is [this proposal](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0811r2.html#linear-interpolation) for the C++20 lerp which talks about the various guarantees, which I've simplified down to:

1. Exactness: `(0.0).lerp(start, end) == start` and `(1.0).lerp(start, end) == end`
2. Consistency: `anything.lerp(x, x) == x`
3. Monotonicity: once you go up don't go down

Fun story: the version provided in that proposal, from what I understand, isn't actually monotonic.

I messed around with a *lot* of different lerp implementations because I kind of got a bit obsessed and I ultimately landed on one that uses the fused `mul_add` instruction. Floating-point lerp lore is hard to come by, so, just trust me when I say that this ticks all the boxes. I'm only 90% certain that it's monotonic, but I'm sure that people who care deeply about this will be there to discuss before stabilisation.

The main reason for using `mul_add` is that, in general, it ticks more boxes with fewer branches to be "correct." Although it will be slower on architectures without the fused `mul_add`, that's becoming more and more rare and I have a feeling that most people who will find themselves needing `lerp` will also have an efficient `mul_add` instruction available.
2021-06-17 23:40:57 +02:00
Maarten de Vries
259bf5f47a Rely on libc for correct integer types in os/unix/net/ancillary.rs. 2021-06-17 15:56:47 +02:00
Yuki Okushi
31ee68067e
Rollup merge of #85802 - Thomasdezeeuw:ioslice-advance, r=m-ou-se
Rename IoSlice(Mut)::advance to advance_slice and add IoSlice(Mut)::advance

Also changes the signature of `advance_slice` to accept a `&mut &mut [IoSlice]`, not returning anything. This will better match the `IoSlice::advance` function.

Updates https://github.com/rust-lang/rust/issues/62726.
2021-06-17 21:56:41 +09:00
Mara Bos
5e7a8c6eb1
Fix typos in code examples. 2021-06-17 12:13:06 +02:00
Chris Denton
a200c01e4f
Document how Windows compares environment variables 2021-06-17 07:15:33 +01:00
Sören Meier
664bde0770 rename remaining to remaining_slice and add a new remaining 2021-06-17 02:14:53 +02:00
Yuki Okushi
0d14acad7e
Rollup merge of #86141 - amorison:link-ref-in-doc-dyn-keyword, r=kennytm
Link reference in `dyn` keyword documentation

The "read more" sentence formatted "object safety" as inline code
instead of providing a link to more information.  This PR adds a link
to the Reference about this matter, as well as the page regarding trait
objects.

---

We could also put these links in the very first line (instead of the link to the
Book) and in the first paragraph which mentions the "object safe" requirement.
Personally, I think it's good to keep the link to the Book up-front as it's more
accessible than the Reference.
2021-06-17 05:54:55 +09:00
Sören Meier
212e91a356
Update tracking issue 2021-06-16 17:25:47 +02:00
bors
9fef8d91b4 Auto merge of #86179 - the8472:revere-path-cmp, r=kennytm
optimize Eq implementation for paths

Filesystems generally have a tree-ish structure which means paths are more likely to share a prefix than a suffix. Absolute paths are especially prone to share long prefixes.

quick benchmark consisting of a search through through a vec containing the absolute paths of all (1850) files in `compiler/`:

```
# old
test path::tests::bench_path_cmp                                  ... bench:     227,407 ns/iter (+/- 2,162)

# new
test path::tests::bench_path_cmp                                  ... bench:      64,976 ns/iter (+/- 1,142)
```
2021-06-16 15:18:19 +00:00