Commit Graph

1294 Commits

Author SHA1 Message Date
Mara 232caad395
Rollup merge of #82764 - m-ou-se:map-try-insert, r=Amanieu
Add {BTreeMap,HashMap}::try_insert

`{BTreeMap,HashMap}::insert(key, new_val)` returns `Some(old_val)` if the key was already in the map. It's often useful to assert no duplicate values are inserted.

We experimented with `map.insert(key, val).unwrap_none()` (https://github.com/rust-lang/rust/issues/62633), but decided that that's not the kind of method we'd like to have on `Option`s.

`insert` always succeeds because it replaces the old value if it exists. One could argue that `insert()` is never the right method for panicking on duplicates, since already handles that case by replacing the value, only allowing you to panic after that already happened.

This PR adds a `try_insert` method that instead returns a `Result::Err` when the key already exists. This error contains both the `OccupiedEntry` and the value that was supposed to be inserted. This means that unwrapping that result gives more context:
```rust
    map.insert(10, "world").unwrap_none();
    // thread 'main' panicked at 'called `Option::unwrap_none()` on a `Some` value: "hello"', src/main.rs:8:29
```

```rust
    map.try_insert(10, "world").unwrap();
    // thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
    // OccupiedError { key: 10, old_value: "hello", new_value: "world" }', src/main.rs:6:33
```

It also allows handling the failure in any other way, as you have full access to the `OccupiedEntry` and the value.

`try_insert` returns a reference to the value in case of success, making it an alternative to `.entry(key).or_insert(value)`.

r? ```@Amanieu```

Fixes https://github.com/rust-lang/rfcs/issues/3092
2021-03-05 10:57:22 +01:00
Mara 68f2934a15
Rollup merge of #82728 - calebsander:refactor/bufreader-buf, r=m-ou-se
Avoid unnecessary Vec construction in BufReader

As mentioned in #80460, creating a `Vec` and calling `Vec::into_boxed_slice()` emits unnecessary calls to `realloc()` and `free()`. Updated the code to use `Box::new_uninit_slice()` to create a boxed slice directly. I think this also makes it more explicit that the initial contents of the buffer are uninitialized.

r? ``@m-ou-se``
2021-03-05 10:57:20 +01:00
Mara 60138110d7
Rollup merge of #81136 - Xavientois:io_reader_size_hint, r=cramertj
Improved IO Bytes Size Hint

After trying to implement better `size_hint()` return values for `File` in [this PR](https://github.com/rust-lang/rust/pull/81044) and changing to implementing it for `BufReader` in [this PR](https://github.com/rust-lang/rust/pull/81052), I have arrived at this implementation that provides tighter bounds for the `Bytes` iterator of various readers including `BufReader`, `Empty`, and `Chain`.

Unfortunately, for `BufReader`, the size_hint only improves after calling `fill_buffer` due to it using the contents of the buffer for the hint. Nevertheless, the the tighter bounds  should result in better pre-allocation of space to handle the contents of the `Bytes` iterator.

Closes #81052
2021-03-05 10:57:17 +01:00
Mara e6a6df5daa
Rollup merge of #80723 - rylev:noop-lint-pass, r=estebank
Implement NOOP_METHOD_CALL lint

Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`).

This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs:
* [ ] No UFCS support
* [ ] The warning message is pretty plain
* [ ] Doesn't work for `ToOwned`

The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type.

Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-05 10:57:14 +01:00
Mara Bos 0a8e401188 Add debug_assert_matches macro. 2021-03-04 18:12:33 +01:00
Mara Bos eb18746bc6 Add assert_matches!(expr, pat). 2021-03-04 18:07:20 +01:00
Mara Bos eddd4f0501 Add tracking issue for map_try_insert. 2021-03-04 16:54:28 +01:00
Mara Bos 1aedb4c3a3 Remove unnecessary bound from HashMap::try_insert. 2021-03-04 16:46:41 +01:00
Mara Bos da01455813 Ignore file length tidy warning in hash/map.rs. 2021-03-04 16:25:24 +01:00
Mara Bos d85d82ab22 Implement Error for OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos 69d95e232a Improve Debug implementations of OccupiedError. 2021-03-04 15:58:50 +01:00
Mara Bos f6fe24aab3 Add HashMap::try_insert and hash_map::OccupiedError. 2021-03-04 15:58:50 +01:00
Ian Jackson 8e4433ab3e ExitStatus tests: Make less legible to satisfy "tidy"
I strongly disagree with tidy in this case but AIUI there is no way to
override it.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-03-04 12:44:19 +00:00
Ian Jackson a240ff5a77 ExitStatus unknown wait status test: Make it Linux only
If different unices have different bit patterns for WIFSTOPPED and
WIFCONTINUED then simply being glibc is probably not good enough for
this rather ad-hoc test to work.  Do it on Linux only.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-03-04 12:26:27 +00:00
Ian Jackson 67cfc22ee2 ExitStatus stop signal display test: Make it Linux only
MacOS uses a different representation.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-03-04 12:18:04 +00:00
Ryan Lopopolo 05ea200213
Add impls for iterators of Cow<OsStr> 2021-03-03 11:52:14 -08:00
Caleb Sander 9425e304b1 Avoid unnecessary Vec construction in BufReader 2021-03-03 12:26:20 -05:00
Ryan Levick c5ff54cbdb Fix std tests 2021-03-03 11:22:51 +01:00
bors 770ed1cf4b Auto merge of #82718 - JohnTitor:rollup-vpfx3j2, r=JohnTitor
Rollup of 10 pull requests

Successful merges:

 - #81223 ([rustdoc] Generate redirect map file)
 - #82439 (BTree: fix untrue safety)
 - #82469 (Use a crate to produce rustdoc tree comparisons instead of the `diff` command)
 - #82589 (unix: Non-mutable bufs in send_vectored_with_ancillary_to)
 - #82689 (meta: Notify Zulip for rustdoc nominated issues)
 - #82695 (Revert non-power-of-two vector restriction)
 - #82706 (use outer_expn_data() instead of outer_expn().expn_data())
 - #82710 (FloatToInit: Replacing round_unchecked_to --> to_int_unchecked)
 - #82712 (Remove unnecessary conditional `cfg(target_os)` for `redox` and `vxworks`)
 - #82713 (Update cargo)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-03-03 08:36:46 +00:00
Yuki Okushi 68d4ff04ee
Rollup merge of #82712 - CDirkx:cfg-target_os, r=dtolnay
Remove unnecessary conditional `cfg(target_os)` for `redox` and `vxworks`

`redox` and `vxworks` are now part of target_family `unix`, thus `cfg(unix)` already implies `cfg(target_os="redox")` and `cfg(target_os="vxworks")`

35dbef2350/compiler/rustc_target/src/spec/redox_base.rs (L26)

35dbef2350/compiler/rustc_target/src/spec/vxworks_base.rs (L27)
2021-03-03 16:27:47 +09:00
Yuki Okushi b16b6820d3
Rollup merge of #82589 - LinkTed:master, r=joshtriplett
unix: Non-mutable bufs in send_vectored_with_ancillary_to

This is the same PR as [#79753](https://github.com/rust-lang/rust/pull/79753). It was closed because of inactivity. Therefore, I create a new one. ````@lukaslihotzki````
2021-03-03 16:27:41 +09:00
bors cbca5689a5 Auto merge of #76345 - okready:sgx-mem-range-overflow-checks, r=joshtriplett
Add is_enclave_range/is_user_range overflow checks

Fixes #76343.

This adds overflow checking to `is_enclave_range` and `is_user_range` in `sgx::os::fortanix_sgx::mem` in order to mitigate possible security issues with enclave code. It also accounts for an edge case where the memory range provided ends exactly at the end of the address space, where calculating `p + len` would overflow back to zero despite the range potentially being valid.
2021-03-03 05:45:50 +00:00
Christiaan Dirkx 738f736066 Remove unnecessary conditional `cfg(target_os)` for `redox` and `vxworks`
`redox` and `vxworks` are part of target_family `unix`, thus `cfg(unix)` already implies `cfg(target_os="redox")` and `(target_os="vxworks")`
2021-03-03 01:14:17 +01:00
Yuki Okushi bc5669eef8
Rollup merge of #80189 - jyn514:convert-primitives, r=poliorcetics
Convert primitives in the standard library to intra-doc links

Blocked on https://github.com/rust-lang/rust/pull/80181. I forgot that this needs to wait for the beta bump so the standard library can be documented with `doc --stage 0`.

Notably I didn't convert `core::slice` because it's like 50 links and I got scared 😨
2021-03-02 21:23:12 +09:00
Guillaume Gomez 5a82251e92
Rollup merge of #82598 - GuillaumeGomez:rustdoc-rustc-pass, r=jyn514
Check stability and feature attributes in rustdoc

Fixes #82588.

cc `@Nemo157` `@camelid`
r? `@jyn514`
2021-03-02 00:50:08 +01:00
Guillaume Gomez d20fd62d70 Add missing stability attributes in libstd 2021-03-01 20:28:37 +01:00
Joshua Nelson 9a86a727c5
Rollup merge of #82645 - rkjnsn:patch-3, r=Mark-Simulacrum
Clarify that SyncOnceCell::set blocks.

Reading the discussion of this feature, I gained the mistaken impression that neither `set` nor `get` blocked, and thus calling `get` immediately after `set` was not guaranteed to succeed. It turns out that `set` *does* block, guaranteeing that the cell contains a value once `set` returns. This change updates the documentation to state that explicitly.

Happy to adjust the wording as desired.
2021-03-01 11:25:11 -05:00
Joshua Nelson efb9ee2df5
Rollup merge of #82578 - camsteffen:diag-items, r=oli-obk
Add some diagnostic items for Clippy
2021-03-01 11:25:07 -05:00
Cameron Steffen eada4d1c45 Add diagnostic items 2021-03-01 09:04:11 -06:00
Erik Jensen 2616960be2
Clarify that SyncOnceCell::set blocks.
Reading the discussion of this feature, I gained the mistaken impression that neither `set` nor `get` blocked, and thus calling `get` immediately after `set` was not guaranteed to succeed. It turns out that `set` *does* block, guaranteeing that the cell contains a value once `set` returns. This change updates the documentation to state that explicitly.
2021-02-28 12:57:38 -08:00
LinkTed 9e4e739209 unix: Non-mutable bufs in send_vectored_with_ancillary_to
Change the arguments of `send_vectored_with_ancillary` and
`send_vectored_with_ancillary_to` to take an non-mutable bufs.
2021-02-28 13:33:09 +01:00
bors 6e2801c44e Auto merge of #82594 - nagisa:nagisa/remove-rumprun, r=petrochenkov
Remove the x86_64-rumprun-netbsd target

Herein we remove the target from the compiler and the code from libstd intended to support the now-defunct rumprun project.

Closes #81514
2021-02-28 03:56:16 +00:00
Dylan DPC e38b3eb0b5
Rollup merge of #82596 - matklad:rwlock, r=sfackler
clarify RW lock's priority gotcha

In particular, the following program works on Linux, but deadlocks on
mac:

```rust
    use std::{
        sync::{Arc, RwLock},
        thread,
        time::Duration,
    };

    fn main() {
        let lock = Arc::new(RwLock::new(()));

        let r1 = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _rg = lock.read();
                eprintln!("r1/1");
                sleep(1000);

                let _rg = lock.read();
                eprintln!("r1/2");

                sleep(5000);
            }
        });
        sleep(100);
        let w = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _wg = lock.write();
                eprintln!("w");
            }
        });
        sleep(100);
        let r2 = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _rg = lock.read();
                eprintln!("r2");
                sleep(2000);
            }
        });

        r1.join().unwrap();
        r2.join().unwrap();
        w.join().unwrap();
    }

    fn sleep(ms: u64) {
        std:🧵:sleep(Duration::from_millis(ms))
    }
```

Context: I was completely mystified by a my CI deadlocking on mac ([here](https://github.com/matklad/xshell/pull/7)), until ``@azdavis`` debugged the issue. See a stand-alone reproduciton here: https://github.com/matklad/xshell/pull/15
2021-02-27 21:56:24 +01:00
Dylan DPC b1113abacd
Rollup merge of #82561 - tspiteri:cube-root, r=Dylan-DPC
doc: cube root, not cubic root

Like we say square root, not quadratic root.
2021-02-27 21:56:21 +01:00
Dylan DPC ea43e5e21d
Rollup merge of #82395 - pickfire:see-more, r=GuillaumeGomez
Add missing "see its documentation for more" stdio

StdoutLock and StderrLock does not have example, it would be better
to leave "see its documentation for more" like iter docs.
2021-02-27 21:56:16 +01:00
Aleksey Kladov 261c952ba6
Update library/std/src/sync/rwlock.rs
Co-authored-by: Steven Fackler <sfackler@gmail.com>
2021-02-27 19:44:17 +03:00
Aleksey Kladov d94b4e81e4 clarify RW lock's priority gotcha
In particular, the following program works on Linux, but deadlocks on
mac:

    use std::{
        sync::{Arc, RwLock},
        thread,
        time::Duration,
    };

    fn main() {
        let lock = Arc::new(RwLock::new(()));

        let r1 = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _rg = lock.read();
                eprintln!("r1/1");
                sleep(1000);

                let _rg = lock.read();
                eprintln!("r1/2");

                sleep(5000);
            }
        });
        sleep(100);
        let w = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _wg = lock.write();
                eprintln!("w");
            }
        });
        sleep(100);
        let r2 = thread::spawn({
            let lock = Arc::clone(&lock);
            move || {
                let _rg = lock.read();
                eprintln!("r2");
                sleep(2000);
            }
        });

        r1.join().unwrap();
        r2.join().unwrap();
        w.join().unwrap();
    }

    fn sleep(ms: u64) {
        std:🧵:sleep(Duration::from_millis(ms))
    }
2021-02-27 19:21:50 +03:00
Simonas Kazlauskas a757fae245 Remove the x86_64-rumprun-netbsd target
Closes #81514
2021-02-27 17:55:22 +02:00
Dylan DPC b664e4bdb5
Rollup merge of #82473 - de-vri-es:android-x86-accept4, r=m-ou-se
Use libc::accept4 on Android instead of raw syscall.

This PR replaces the use of a raw `accept4` syscall with `libc::accept4`. This was originally added (by me) because `std` couldn't update to the latest `libc` with `accept4` support for android. By now, libc is already on 0.2.85, so the workaround can be removed.

`@rustbot` label +O-android +T-libs-impl
2021-02-27 02:34:31 +01:00
Dylan DPC d80033f048
Rollup merge of #82421 - sunfishcode:wasi-metadata-size, r=alexcrichton
Add a `size()` function to WASI's `MetadataExt`.

WASI's `filestat` type includes a size field, so expose it in
`MetadataExt` via a `size()` function, similar to the corresponding Unix
function.

r? ``````@alexcrichton``````
2021-02-27 02:34:28 +01:00
Dylan DPC f5b68a4444
Rollup merge of #82420 - sunfishcode:wasi-docs, r=alexcrichton
Enable API documentation for `std::os::wasi`.

This adds API documentation support for `std::os::wasi` modeled after
how `std::os::unix` works, so that WASI can be documented [here] along
with the other platforms.

[here]: https://doc.rust-lang.org/stable/std/os/index.html

Two changes of particular interest:

 - This changes the `AsRawFd` for `io::Stdin` for WASI to return
   `libc::STDIN_FILENO` instead of `sys::stdio::Stdin.as_raw_fd()` (and
   similar for `Stdout` and `Stderr`), which matches how the `unix`
   version works. `STDIN_FILENO` etc. may not always be explicitly
   reserved at the WASI level, but as long as we have Rust's `std` and
   `libc`, I think it's reasonable to guarantee that we'll always use
   `libc::STDIN_FILENO` for stdin.

 - This duplicates the `osstr2str` utility function, rather than
   trying to share it across all the configurations that need it.

r? ```@alexcrichton```
2021-02-27 02:34:27 +01:00
Trevor Spiteri dd502cb343 doc: cube root, not cubic root
Like we say square root, not quadratic root.
2021-02-26 19:03:44 +01:00
Guillaume Gomez 0db8349fff
Rollup merge of #81940 - jhpratt:stabilize-str_split_once, r=m-ou-se
Stabilize str_split_once

Closes #74773
2021-02-26 15:52:29 +01:00
Joshua Nelson 9a75f4fed1 Convert primitives to use intra-doc links 2021-02-25 20:31:53 -05:00
Aaron Hill befa2dffda
Rollup merge of #82467 - ojeda:tidy-normalize-safety-comments, r=kennytm
library: Normalize safety-for-unsafe-block comments

Almost all safety comments are of the form `// SAFETY:`,
so normalize the rest and fix a few of them that should
have been a `/// # Safety` section instead.

Furthermore, make `tidy` only allow the uppercase form. While
currently `tidy` only checks `core`, it is a good idea to prevent
`core` from drifting to non-uppercase comments, so that later
we can start checking `alloc` etc. too.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-02-25 16:06:21 -05:00
Aaron Hill 503d50b94c
Rollup merge of #82464 - ehuss:unix-command-comment, r=kennytm
Update outdated comment in unix Command.

The big comment in the `Command` struct has been incorrect for some time (at least since #46789 which removed `envp`). Rather than try to remove the allocations, this PR just updates the comment to reflect reality. There is an explanation for the reasoning at https://github.com/rust-lang/rust/pull/31409#issuecomment-182122895, discussing the potential of being able to call `Command::exec` after `libc::fork`.  That can still be done in the future, but I think for now it would be good to just correct the comment.
2021-02-25 16:06:20 -05:00
Dylan DPC 351d947e54
Rollup merge of #80553 - derekdreery:arc_error, r=m-ou-se
Add an impl of Error on `Arc<impl Error>`.

`Display` already exists so this should be a non-controversial change (famous last words).

Would have to be insta-stable.
2021-02-25 14:33:50 +01:00
Mara 76fd8d7e74 Use intra-doc links.
Co-authored-by: Joshua Nelson <joshua@yottadb.com>
2021-02-25 13:45:57 +01:00
Mara Bos 1ab9fe5d44 Add {core,std}::prelude::{rust_2015,rust_2018,rust_2021}.
rust_2015 and rust_2018 are just re-exports of v1.
rust_2021 is a module that for now just re-exports everything from v1,
such that we can add more things later.
2021-02-25 12:46:46 +01:00
Christiaan Dirkx 2cbea9f98e Reuse `std::sys::unsupported::pipe` on `hermit` 2021-02-24 23:11:02 +01:00
Dan Gohman 7d5242a03a x.py fmt 2021-02-24 10:58:21 -08:00
Dan Gohman 94e75acf1f Mention "wasi" in the comment about "main modules". 2021-02-24 10:47:26 -08:00
Dan Gohman e66e263544 Make the main `wasi` module `cfg(not(doc))`. 2021-02-24 10:43:50 -08:00
Dan Gohman 0208fca342 Use `super::` to refer to WASI-specific names.
This ensures that these names resolve to the right place even when
building the WASI support on other platforms for generating the
documentation.
2021-02-24 10:37:05 -08:00
Dan Gohman 9ce567efc2 Cast `libc::STDIN_FILENO` to `RawFd`.
WASI's `RawFd` is a `u32`, while `libc` uses `c_int`.
2021-02-24 10:35:40 -08:00
Maarten de Vries f291131f2e Bump minimum libc version to 0.2.85 for std. 2021-02-24 12:47:28 +01:00
Maarten de Vries 3ac62cafa3 Use libc::accept4 on Android instead of raw syscall. 2021-02-24 12:24:36 +01:00
Miguel Ojeda eefec8abda library: Normalize safety-for-unsafe-block comments
Almost all safety comments are of the form `// SAFETY:`,
so normalize the rest and fix a few of them that should
have been a `/// # Safety` section instead.

Furthermore, make `tidy` only allow the uppercase form. While
currently `tidy` only checks `core`, it is a good idea to prevent
`core` from drifting to non-uppercase comments, so that later
we can start checking `alloc` etc. too.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2021-02-24 06:13:42 +01:00
Eric Huss 476c6c27e7 Update outdated comment in unix Command. 2021-02-23 20:19:15 -08:00
LeSeulArtichaut a6eb836ff0 Use #[doc = include_str!()] in std 2021-02-23 15:54:55 +01:00
Dan Gohman 132ec261b0 Enable API documentation for `std::os::wasi`.
This adds API documentation support for `std::os::wasi` modeled after
how `std::os::unix` works, so that WASI can be documented [here] along
with the other platforms.

[here]: https://doc.rust-lang.org/stable/std/os/index.html

Two changes of particular interest:

 - This changes the `AsRawFd` for `io::Stdin` for WASI to return
   `libc::STDIN_FILENO` instead of `sys::stdio::Stdin.as_raw_fd()` (and
   similar for `Stdout` and `Stderr`), which matches how the `unix`
   version works. `STDIN_FILENO` etc. may not always be explicitly
   reserved at the WASI level, but as long as we have Rust's `std` and
   `libc`, I think it's reasonable to guarantee that we'll always use
   `libc::STDIN_FILENO` for stdin.

 - This duplicates the `osstr2str` utility function, rather than
   trying to share it across all the configurations that need it.
2021-02-23 05:40:08 -08:00
bors cd64446196 Auto merge of #82076 - jyn514:update-bootstrap, r=Mark-Simulacrum
Update the bootstrap compiler

This updates the bootstrap compiler, notably leaving out a change to enable semicolon in macro expressions lint, because stdarch still depends on the old behavior.
2021-02-23 07:19:41 +00:00
Joshua Nelson 68f41b8328 Add more links between hash and btree collections
- Link from `core::hash` to `HashMap` and `HashSet`
- Link from HashMap and HashSet to the module-level documentation on
  when to use the collection
- Link from several collections to Wikipedia articles on the general
  concept
2021-02-23 00:41:41 -05:00
Dylan DPC b8d4354099
Rollup merge of #82128 - anall:feature/add_diagnostic_items, r=davidtwco
add diagnostic items for OsString/PathBuf/Owned as well as to_vec on slice

This is adding diagnostic items to be used by rust-lang/rust-clippy#6730, but my understanding is the clippy-side change does need to be done over there since I am adding a new clippy feature.

Add diagnostic items to the following types:
  OsString (os_string_type)
  PathBuf (path_buf_type)
  Owned (to_owned_trait)

As well as the to_vec method on slice/[T]
2021-02-23 02:51:51 +01:00
Dylan DPC 7b9ef2fde4
Rollup merge of #81984 - sunfishcode:wasi-link, r=alexcrichton
Make WASI's `hard_link` behavior match other platforms.

Following #78026, `std::fs::hard_link` on most platforms does not follow
symlinks. Change the WASI implementation to also not follow symlinks.

r? ```@alexcrichton```
2021-02-23 02:51:49 +01:00
Ian Jackson 4bb8425af6 ExitStatus: Improve documentation re wait status vs exit status
The use of `ExitStatus` as the Rust type name for a Unix *wait
status*, not an *exit status*, is very confusing, but sadly probably
too late to change.

This area is confusing enough in Unix already (and many programmers
are already confuxed).  We can at least document it.

I chose *not* to mention the way shells like to exit with signal
numbers, thus turning signal numbers into exit statuses.  This is only
relevant for Rust programs using `std::process` if they run shells.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-02-23 00:58:10 +00:00
Ian Jackson d8cfd56985 process::unix: Test wait status formatting
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-02-23 00:58:10 +00:00
Dan Gohman e8dcc02dc5 Add a `size()` function to WASI's `MetadataExt`.
WASI's `filestat` type includes a size field, so expose it in
`MetadataExt` via a `size()` function, similar to the corresponding Unix
function.
2021-02-22 14:42:59 -08:00
The8472 81602fb670 fix io::copy specialization when writer was opened with O_APPEND 2021-02-22 21:41:32 +01:00
The8472 5c0d76dbe1 add test for failing io::copy specialization 2021-02-22 21:41:32 +01:00
Jonas Schievink 7bc501687b Avoid `cfg_if` in `std::os` 2021-02-22 19:56:20 +01:00
Ian Jackson fbd575aedf process::unix: Handle other wait statuses in ExitStatus as Display
Currently, on Nightly, this panics:

```
use std::process::ExitStatus;
use std::os::unix::process::ExitStatusExt;

fn main() {
    let st = ExitStatus::from_raw(0x007f);
    println!("st = {}", st);
}
```

This is because the impl of Display assumes that if .code() is None,
.signal() must be Some.  That was a false assumption, although it was
true with buggy code before
  5b1316f781
  unix ExitStatus: Do not treat WIFSTOPPED as WIFSIGNALED

This is not likely to have affected many people in practice, because
`Command` will never produce such a wait status (`ExitStatus`).

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-02-22 18:15:42 +00:00
Richard Dodd 0d6640a5b0 Add impl `Error` for `Arc` 2021-02-22 12:49:42 +00:00
Ivan Tham bff4e937ab Add missing "see its documentation for more" stdio
StdoutLock and StderrLock does not have example, it would be better
to leave "see its documentation for more" like iter docs.
2021-02-22 18:48:32 +08:00
Yuki Okushi a5f6668920
Rollup merge of #82228 - ijackson:nonzero-cint, r=KodrAus
Provide NonZero_c_* integers

I'm pretty sure I am going want this for #73125 and it seems like an
omission that would be in any case good to remedy.

<strike>Because the raw C types are in `std`, not `core`, to achieve this we
must export the relevant macros from `core` so that `std` can use
them.  That's done with a new `num_internals` perma-unstable feature.

The macros need to take more parameters for the module to get the
types from and feature attributes to use.

I have eyeballed the docs output for core, to check that my changes to
these macros have made no difference to the core docs output.</strike>
2021-02-22 18:26:06 +09:00
Ashley Mannix 60a9dcc4e3
update tracking issue for raw_os_nonzero 2021-02-21 19:43:42 +10:00
Joshua Nelson 3733275854 Update the bootstrap compiler
Note this does not change `core::derive` since it was merged after the
beta bump.
2021-02-20 17:19:30 -05:00
Guillaume Gomez c26a8bbd6d
Rollup merge of #82244 - pickfire:patch-6, r=dtolnay
Keep consistency in example for Stdin StdinLock

Stdin uses handle whereas StdinLock uses stdin_lock, changed it to handle.
2021-02-20 20:37:01 +01:00
Dan Gohman 1abcdfe449 x.py fmt 2021-02-19 07:31:01 -08:00
Dylan DPC c821063a53
Rollup merge of #81873 - mark-i-m:unlock, r=m-ou-se
Add Mutex::unlock

Tracking issue: https://github.com/rust-lang/rust/issues/81872

Discussion: https://github.com/rust-lang/rust/pull/79434#issuecomment-757135874

r? `@m-ou-se`
2021-02-19 02:49:06 +01:00
mark e92e5fd787 add Mutex::unlock 2021-02-18 11:56:19 -06:00
LeSeulArtichaut ec20993c4d Stabilize `unsafe_op_in_unsafe_fn` lint 2021-02-18 17:12:15 +01:00
bors 25a2c13e9d Auto merge of #82249 - JohnTitor:rollup-3jbqija, r=JohnTitor
Rollup of 8 pull requests

Successful merges:

 - #82055 (Add diagnostics for specific cases for const/type mismatch err)
 - #82155 (Use !Sync std::lazy::OnceCell in usefulness checking)
 - #82202 (add specs for riscv32/riscv64 musl targets)
 - #82203 (Move some tests to more reasonable directories - 4)
 - #82211 (make `suggest_setup` help messages better)
 - #82212 (Remove redundant rustc_data_structures path component)
 - #82240 (remove useless ?s (clippy::needless_question_marks))
 - #82243 (Add more intra-doc links to std::io)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-02-18 07:22:30 +00:00
Yuki Okushi 21283dae9e
Rollup merge of #82243 - pickfire:patch-5, r=jyn514
Add more intra-doc links to std::io
2021-02-18 15:57:34 +09:00
bors d1462d8558 Auto merge of #81172 - SimonSapin:ptr-metadata, r=oli-obk
Implement RFC 2580: Pointer metadata & VTable

RFC: https://github.com/rust-lang/rfcs/pull/2580

~~Before merging this PR:~~

* [x] Wait for the end of the RFC’s [FCP to merge](https://github.com/rust-lang/rfcs/pull/2580#issuecomment-759145278).
* [x] Open a tracking issue: https://github.com/rust-lang/rust/issues/81513
* [x] Update `#[unstable]` attributes in the PR with the tracking issue number

----

This PR extends the language with a new lang item for the `Pointee` trait which is special-cased in trait resolution to implement it for all types. Even in generic contexts, parameters can be assumed to implement it without a corresponding bound.

For this I mostly imitated what the compiler was already doing for the `DiscriminantKind` trait. I’m very unfamiliar with compiler internals, so careful review is appreciated.

This PR also extends the standard library with new unstable APIs in `core::ptr` and `std::ptr`:

```rust
pub trait Pointee {
    /// One of `()`, `usize`, or `DynMetadata<dyn SomeTrait>`
    type Metadata: Copy + Send + Sync + Ord + Hash + Unpin;
}

pub trait Thin = Pointee<Metadata = ()>;

pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {}

pub const fn from_raw_parts<T: ?Sized>(*const (), <T as Pointee>::Metadata) -> *const T {}
pub const fn from_raw_parts_mut<T: ?Sized>(*mut (),<T as Pointee>::Metadata) -> *mut T {}

impl<T: ?Sized> NonNull<T> {
    pub const fn from_raw_parts(NonNull<()>, <T as Pointee>::Metadata) -> NonNull<T> {}

    /// Convenience for `(ptr.cast(), metadata(ptr))`
    pub const fn to_raw_parts(self) -> (NonNull<()>, <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *const T {
    pub const fn to_raw_parts(self) -> (*const (), <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *mut T {
    pub const fn to_raw_parts(self) -> (*mut (), <T as Pointee>::Metadata) {}
}

/// `<dyn SomeTrait as Pointee>::Metadata == DynMetadata<dyn SomeTrait>`
pub struct DynMetadata<Dyn: ?Sized> {
    // Private pointer to vtable
}

impl<Dyn: ?Sized> DynMetadata<Dyn> {
    pub fn size_of(self) -> usize {}
    pub fn align_of(self) -> usize {}
    pub fn layout(self) -> crate::alloc::Layout {}
}

unsafe impl<Dyn: ?Sized> Send for DynMetadata<Dyn> {}
unsafe impl<Dyn: ?Sized> Sync for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Debug for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Unpin for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Copy for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Clone for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Eq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialEq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Ord for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialOrd for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Hash for DynMetadata<Dyn> {}
```

API differences from the RFC, in areas noted as unresolved questions in the RFC:

* Module-level functions instead of associated `from_raw_parts` functions on `*const T` and `*mut T`, following the precedent of `null`, `slice_from_raw_parts`, etc.
* Added `to_raw_parts`
2021-02-18 04:22:16 +00:00
Ivan Tham 026be9dc26
Keep consistency in example for Stdin StdinLock
Stdin uses handle whereas StdinLock uses stdin_lock, changed it to handle.
2021-02-18 10:11:57 +08:00
Ivan Tham 250eeb4c3c
Add missing link from stdio doc 2021-02-18 09:58:15 +08:00
Dylan DPC db59950b6d
Rollup merge of #77728 - lygstate:master, r=Amanieu
Expose force_quotes on Windows.

On Windows, the arg quotes and not quotes have different effect
for the program it called, if the program called are msys2/cygwin program.
Refer to
https://github.com/msys2/MSYS2-packages/issues/2176

This also solve the issues comes from

https://internals.rust-lang.org/t/std-process-on-windows-is-escaping-raw-literals-which-causes-problems-with-chaining-commands/8163

Tracking issue:
https://github.com/rust-lang/rust/issues/82227
2021-02-17 23:51:12 +01:00
Ian Jackson e78b5012f5 Provide NonZero_c_* integers
I'm pretty sure I am going want this for #73125 and it seems like an
omission that would be in any case good to remedy.

It's a shame we don't have competent token pasting and case mangling
for use in macro_rules!.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-02-17 20:48:22 +00:00
Ian Jackson d6b9d9a1d6 std::src::os::raw: Refactor, introducing macro type_alias!
This file contained a lot of repetitive code.  This was about to get
considerably worse, with introduction of a slew of new aliases.

No functional change.  I've eyeballed the docs and they don't seem to
have changed either.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-02-17 20:36:59 +00:00
Yonggang Luo fa23ddf6e6 Expose force_quotes on Windows.
Quotes the arg and not quotes the arg have different effect on Windows when the program called
are msys2/cygwin program.
Refer to https://github.com/msys2/MSYS2-packages/issues/2176

Signed-off-by: Yonggang Luo <luoyonggang@gmail.com>
2021-02-17 17:54:04 +00:00
Ryan Lopopolo 2fcb8b5c20
Optimize FromIterator<OsString> to reuse the first allocation 2021-02-16 14:20:26 -08:00
Manish Goregaokar a98b22c837 Add caveat to Path::display() about lossiness 2021-02-16 11:45:46 -08:00
Andrea Nall 67fcaaaa7a a few more diagnostic items 2021-02-16 02:32:21 +00:00
Andrea Nall c6bb62810a requested/proposed changes 2021-02-15 22:59:47 +00:00
Jonas Schievink c87ef218f9
Rollup merge of #82120 - sfackler:arguments-as-str, r=dtolnay
Stabilize Arguments::as_str

Closes #74442
2021-02-15 16:07:08 +01:00
Jonas Schievink 2030a54f9d
Rollup merge of #82119 - m-ou-se:typo, r=dtolnay
Fix typo in link to CreateSymbolicLinkW documentation.
2021-02-15 16:07:06 +01:00
Jonas Schievink 7842b5d2ec
Rollup merge of #82063 - NULLx76:fix-minor-typo, r=jonas-schievink
Fixed minor typo in catch_unwind docs

Changed "a an exception" to "an exception" inside of the `std::panic::catch_unwind` docs.
2021-02-15 16:06:58 +01:00
Jonas Schievink bd0e8a5df3
Rollup merge of #81975 - Amanieu:seal2, r=m-ou-se
Seal the CommandExt, OsStrExt and OsStringExt traits

A crater run (https://github.com/rust-lang/rust/pull/81213#issuecomment-767651811) has shown that this does not break any existing code.

This also unblocks #77728.

Based on #81213.

r? ````@m-ou-se````
cc ````@lygstate````
2021-02-15 16:06:54 +01:00
Simon Sapin 21ceebf296 Fix intra-doc link to raw pointer method
CC https://github.com/rust-lang/rust/pull/80181
2021-02-15 14:27:50 +01:00