Commit graph

1399 commits

Author SHA1 Message Date
Stephen Albert-Moore
3855597186 Fix broken doc link reference 2021-03-20 00:36:41 -04:00
mark
553ceb0791 core/std/alloc: stabilize or_patterns 2021-03-19 19:45:42 -05:00
Dylan DPC
dbf589f970
Rollup merge of #83269 - bstrie:revertdep, r=m-ou-se
Revert the second deprecation of collections::Bound

Per the review at https://github.com/rust-lang/rust/pull/82122#discussion_r596448078 and the decision at https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/unavoidable.20breakage.20when.20deprecating.20an.20enum.3F , revert this small portion of #82122 for the time being. This doesn't affect the other components of that patch, i.e. `intrinsics::drop_in_place` is still deprecated-for-real, and uses of `collections::Bound` remain removed from the repo.
2021-03-19 23:01:39 +01:00
Dylan DPC
675ae2e366
Rollup merge of #83215 - bstrie:dephaikuraw, r=joshtriplett
Deprecate std::os::haiku::raw, which accidentally wasn't deprecated

In early 2016, all `std::os::*::raw` modules [were deprecated](aa23c98450) in accordance with [RFC 1415](https://github.com/rust-lang/rfcs/blob/master/text/1415-trim-std-os.md). However, at this same time support for Haiku was being added to libstd, landing shortly after the aforementioned commit, and due to some crossed wires a `std::os::haiku::raw` module was added and was not marked as deprecated.

I have been in correspondence with the author of the Haiku patch, ````@nielx,```` who has confirmed that this was simply an oversight and that the definitions from the libc crate should be preferred instead.
2021-03-19 15:03:26 +01:00
Dylan DPC
db4a97c4cb
Rollup merge of #82892 - jix:clarify-read-read, r=joshtriplett
Clarify docs for Read::read's return value

Right now the docs for `Read::read`'s return value are phrased in a way that makes it easy for the reader to assume that the return value is never larger than the passed buffer. This PR clarifies that this is a requirement for implementations of the trait, but that callers have to expect a buggy yet safe implementation failing to do so, especially if unchecked accesses to the buffer are done afterwards.

I fell into this trap recently, and when I noticed, I looked at the docs again and had the feeling that I might not have been the first one to miss this.

The same issue of trusting the return value of `read` was also present in std itself for about 2.5 years and only fixed recently, see #80895.

I hope that clarifying the docs might help others to avoid this issue.
2021-03-19 15:03:22 +01:00
Dylan DPC
4abcd4042c
Rollup merge of #82500 - CDirkx:hermit-pipe, r=joshtriplett
Reuse `std::sys::unsupported::pipe` on `hermit`

Pipes are not supported on `hermit` and `hermit/pipe.rs` is identical to `unsupported/pipe.rs`. This PR reduces duplication between the two by doing the following on `hermit`:

```rust
#[path = "../unsupported/pipe.rs"]
pub mod pipe;
```
2021-03-19 15:03:14 +01:00
Jannis Harder
9dfda62763 Clarify docs for Read::read's return value 2021-03-18 22:52:46 +01:00
Stephen Albert-Moore
b6a12d58f5
Fix pluralization in keyword docs 2021-03-18 17:04:58 -04:00
bstrie
1e322e33fe Revert the second deprecation of collections::Bound 2021-03-18 13:57:31 -04:00
bors
0464f638af Auto merge of #77566 - Marwes:smaller_hashmap, r=Amanieu
feat: Update hashbrown to instantiate less llvm IR

Includes https://github.com/rust-lang/hashbrown/pull/204 and https://github.com/rust-lang/hashbrown/pull/205 (not yet merged) which both serve to reduce the amount of IR generated for hashmaps.

Inspired by the llvm-lines data gathered in https://github.com/rust-lang/rust/pull/76680 (cc `@Julian-Wollersberger)`
2021-03-18 11:03:49 +00:00
Dylan DPC
03400455e1
Rollup merge of #83223 - JohnTitor:display-err-from-mmap, r=joshtriplett
Display error details when a `mmap` call fails

Fixes #82388
2021-03-18 00:28:15 +01:00
Dylan DPC
c99200fa53
Rollup merge of #82434 - jyn514:hash, r=JohnTitor
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

See also https://github.com/rust-lang/rust/pull/81989#issuecomment-783920840.
2021-03-18 00:28:07 +01:00
bors
36f1f04f18 Auto merge of #82122 - bstrie:dep4real, r=dtolnay
Deprecate `intrinsics::drop_in_place` and `collections::Bound`, which accidentally weren't deprecated

Fixes #82080.

I've taken the liberty of updating the `since` values to 1.52, since an unobservable deprecation isn't much of a deprecation (even the detailed release notes never bothered to mention these deprecations).

As mentioned in the issue I'm *pretty* sure that using a type alias for `Bound` is semantically equivalent to the re-export; [the reference implies](https://doc.rust-lang.org/reference/items/type-aliases.html) that type aliases only observably differ from types when used on unit structs or tuple structs, whereas `Bound` is an enum.
2021-03-17 19:39:03 +00:00
Yuki Okushi
3122510748
Rollup merge of #82826 - pierwill:fix-IPv, r=JohnTitor
(std::net::parser): Fix capitalization of IP version names

Also add some missing puctuation in doc and code comments.
2021-03-17 15:20:49 +09:00
Yuki Okushi
f414c33e5e Display error details when a mmap call fails 2021-03-17 12:01:55 +09:00
bstrie
cad3c4241d Deprecate std::os::haiku::raw 2021-03-16 17:43:33 -04:00
Yuki Okushi
39af66f651
Rollup merge of #83160 - m-ou-se:deprecate-rustc-serialize-derives, r=petrochenkov
Deprecate RustcEncodable and RustcDecodable.

We can't remove the `RustcEncodable` and `RustcDecodable` derive macros from the prelude, but we can deprecate them.
2021-03-16 23:54:00 +09:00
Yuki Okushi
62d38da9fa
Rollup merge of #81822 - Kixunil:path_try_exists, r=kennytm
Added `try_exists()` method to `std::path::Path`

This method is similar to the existing `exists()` method, except it
doesn't silently ignore the errors, leading to less error-prone code.

This change intentionally does NOT touch the documentation of `exists()`
nor recommend people to use this method while it's unstable.
Such changes are reserved for stabilization to prevent confusing people.

Apart from that it avoids conflicts with #80979.

`@joshtriplett` requested this PR in [internals discussion](https://internals.rust-lang.org/t/the-api-of-path-exists-encourages-broken-code/13817/25?u=kixunil)
2021-03-16 23:53:52 +09:00
Markus Westerlind
7cf8d3ac2b feat: Update hashbrown to instantiate less llvm IR
Includes https://github.com/rust-lang/hashbrown/pull/204 and https://github.com/rust-lang/hashbrown/pull/205 (not yet merged) which both server to reduce the amount of IR generated for hashmaps.

Inspired by the llvm-lines data gathered in https://github.com/rust-lang/rust/pull/76680
2021-03-16 11:20:26 +01:00
Martin Habovstiak
4330268181 Filled tracking issue for path_try_exists
This adds the ID of the tracking issue to the feature.
2021-03-16 08:41:14 +01:00
Camelid
34c6cee397 Rename #[doc(spotlight)] to #[doc(notable_trait)]
"spotlight" is not a very specific or self-explaining name.
Additionally, the dialog that it triggers is called "Notable traits".
So, "notable trait" is a better name.

* Rename `#[doc(spotlight)]` to `#[doc(notable_trait)]`
* Rename `#![feature(doc_spotlight)]` to `#![feature(doc_notable_trait)]`
* Update documentation
* Improve documentation
2021-03-15 13:59:54 -07:00
Mara Bos
924e522d16 Deprecate RustcEncodable and RustcDecodable. 2021-03-15 20:16:16 +01:00
bors
107896c32d Auto merge of #83121 - the8472:env-rwlock-2, r=joshtriplett
use RWlock when accessing os::env (take 2)

This reverts commit acdca316c3 (#82877) i.e. redoes #81850 since the invalid unlock attempts in the child process have been fixed in #82949

r? `@joshtriplett`
2021-03-15 18:32:10 +00:00
The8472
e22143c075 Revert "Revert "use RWlock when accessing os::env #81850""
This reverts commit acdca316c3.
2021-03-14 19:10:34 +01:00
Motoki Ikeda
5ec0540da5 Fix a typo in thread_local_dtor.rs 2021-03-14 16:39:29 +09:00
Yuki Okushi
dda9d0589f
Rollup merge of #82943 - kornelski:threadstdio, r=joshtriplett
Demonstrate best practice for feeding stdin of a child processes

Documentation change.

It's possible to create a deadlock with stdin/stdout I/O on a single thread:

* the child process may fill its stdout buffer, and have to wait for the parent process to read it,
* but the parent process may be waiting until its stdin write finishes before reading the stdout.

Therefore, the parent process should use separate threads for writing and reading.

These examples are not deadlocking in practice, because they use short strings, but I think it's better to demonstrate code that works even for long writes. The problem is non-obvious and tricky to debug (it seems that even libstd has a similar issue: #45572).

This also demonstrates how to use stdio with threads: it's not obvious that `.take()` can be used to avoid fighting with the borrow checker.

I've checked that the modified examples run fine.
2021-03-14 13:07:34 +09:00
Yuki Okushi
9ce0820eef
Rollup merge of #82804 - alexcrichton:fix-wasi, r=pnkfelix
std: Fix a bug on the wasm32-wasi target opening files

This commit fixes an issue pointed out in #82758 where LTO changed the
behavior of a program. It turns out that LTO was not at fault here, it
simply uncovered an existing bug. The bindings to
`__wasilibc_find_relpath` assumed that the relative portion of the path
returned was always contained within thee input `buf` we passed in. This
isn't actually the case, however, and sometimes the relative portion of
the path may reference a sub-portion of the input string itself.

The fix here is to use the relative path pointer coming out of
`__wasilibc_find_relpath` as the source of truth. The `buf` used for
local storage is discarded in this function and the relative path is
copied out unconditionally. We might be able to get away with some
`Cow`-like business or such to avoid the extra allocation, but for now
this is probably the easiest patch to fix the original issue.
2021-03-14 13:07:33 +09:00
Yuki Okushi
67bc866e59
Rollup merge of #82121 - lopopolo:pathbuf-osstring-extend, r=joshtriplett
Implement Extend and FromIterator for OsString

Add the following trait impls:

- `impl Extend<OsString> for OsString`
- `impl<'a> Extend<&'a OsStr> for OsString`
- `impl FromIterator<OsString> for OsString`
- `impl<'a> FromIterator<&'a OsStr> for OsString`

Because `OsString` is a platform string with no particular semantics, concatenating them together seems acceptable.

I came across a use case for these trait impls in https://github.com/artichoke/artichoke/pull/1089:

Artichoke is a Ruby interpreter. Its CLI accepts multiple `-e` switches for executing inline Ruby code, like:

```console
$ cargo -q run --bin artichoke -- -e '2.times {' -e 'puts "foo: #{__LINE__}"' -e '}'
foo: 2
foo: 2
```

I use `clap` for command line argument parsing, which collects these `-e` commands into a `Vec<OsString>`. To pass these commands to the interpreter for `Eval`, I need to join them together. Combining these impls with `Iterator::intersperse` https://github.com/rust-lang/rust/issues/79524 would enable me to build a single bit of Ruby code.

Currently, I'm doing something like:

```rust
let mut commands = commands.into_iter();
let mut buf = if let Some(command) = commands.next() {
    command
} else {
    return Ok(Ok(()));
};
for command in commands {
    buf.push("\n");
    buf.push(command);
}
```

If there's interest, I'd also like to add impls for `Cow<'a, OsStr>`, which would avoid allocating the `"\n"` `OsString` in the concatenate + intersperse use case.
2021-03-14 13:07:28 +09:00
bors
03e864fd86 Auto merge of #82417 - the8472:fix-copy_file_range-append, r=m-ou-se
Fix io::copy specialization using copy_file_range when writer was opened with O_APPEND

fixes #82410

While `sendfile()` returns `EINVAL` when the output was opened with O_APPEND,  `copy_file_range()` does not and returns `EBADF` instead, which – unlike other `EBADF` causes – is not fatal for this operation since a regular `write()` will likely succeed.

We now treat `EBADF` as a non-fatal error for `copy_file_range` and fall back to a read-write copy as we already did for several other errors.
2021-03-11 21:41:01 +00:00
Dylan DPC
d01648b60e
Rollup merge of #82949 - the8472:forget-envlock-on-fork, r=joshtriplett
Do not attempt to unlock envlock in child process after a fork.

This implements the first two points from https://github.com/rust-lang/rust/issues/64718#issuecomment-793030479

This is a breaking change for cases where the environment is accessed in a Command::pre_exec closure. Except for single-threaded programs these uses were not correct anyway since they aren't async-signal safe.

Note that we had a ui test that explicitly tried `env::set_var` in `pre_exec`. As expected it failed with these changes when I tested locally.
2021-03-10 17:55:43 +01:00
Dylan DPC
759204ffc4
Rollup merge of #82217 - m-ou-se:edition-prelude, r=nikomatsakis
Edition-specific preludes

This changes `{std,core}::prelude` to export edition-specific preludes under `rust_2015`, `rust_2018` and `rust_2021`. (As suggested in https://github.com/rust-lang/rust/issues/51418#issuecomment-395630382.) For now they all just re-export `v1::*`, but this allows us to add things to the 2021edition prelude soon.

This also changes the compiler to make the automatically injected prelude import dependent on the selected edition.

cc `@rust-lang/libs` `@djc`
2021-03-10 17:55:38 +01:00
philippeitis
c5ac064666
Stabilize bufreader_seek_relative 2021-03-10 01:52:11 -08:00
bstrie
49aa79ec11 Deprecate items that accidentally weren't deprecated
Fixes #82080
2021-03-09 19:09:20 -05:00
Yuki Okushi
74e74e9df8
Rollup merge of #82411 - ijackson:fix-exitstatus, r=dtolnay
Fixes to ExitStatus and its docs

* On Unix, properly display every possible wait status (and don't panic on weird values)
* In the documentation, be clear and consistent about "exit status" vs "wait status".
2021-03-10 08:01:27 +09:00
Yuki Okushi
c46f948a80
Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, r=nikomatsakis
Stabilize `unsafe_op_in_unsafe_fn` lint

This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896.

Tracking issue: #71668
r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung```

# Stabilization report

This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`.

## Summary

Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside.

The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block.

For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level.

For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md)

### Example

```rust
// An `unsafe fn` for demonstration purposes.
// Calling this is an unsafe operation.
unsafe fn unsf() {}

// #[allow(unsafe_op_in_unsafe_fn)] by default,
// the behavior of `unsafe fn` is unchanged
unsafe fn allowed() {
    // Here, no `unsafe` block is needed to
    // perform unsafe operations...
    unsf();

    // ...and any `unsafe` block is considered
    // unused and is warned on by the compiler.
    unsafe {
        unsf();
    }
}

#[warn(unsafe_op_in_unsafe_fn)]
unsafe fn warned() {
    // Removing this `unsafe` block will
    // cause the compiler to emit a warning.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}

#[deny(unsafe_op_in_unsafe_fn)]
unsafe fn denied() {
    // Removing this `unsafe` block will
    // cause a compilation error.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}
```
2021-03-10 08:01:25 +09:00
The8472
d854789ce1 Do not attempt to unlock envlock in child process after a fork.
This is a breaking change for cases where the environment is
accessed in a Command::pre_exec closure. Except for
single-threaded programs these uses were not correct
anyway since they aren't async-signal safe.
2021-03-09 22:14:07 +01:00
Kornel
ce2d95cd75 Demonstrate best practice for feeding stdin of a child processes
It's possible to create a deadlock with stdin/stdout I/O on a single thread:

* the child process may fill its stdout buffer, and have to wait for the parent process to read it,
* but the parent process may be waiting until its stdin write finishes before reading the stdout.

Therefore, the parent process should use separate threads for writing and reading.
2021-03-09 20:47:23 +00:00
Ian Jackson
11ca64401a
Always compile the fragile wait status test cases, just run them conditionally
Co-authored-by: David Tolnay <dtolnay@gmail.com>
2021-03-09 10:53:03 +00:00
Mara Bos
ba63a84acc
Rollup merge of #82731 - de-vri-es:bump-libc-for-std, r=Mark-Simulacrum
Bump libc dependency of std to 0.2.88.

This PR bumps the `libc` dependency of `std` to 0.2.88. This will fix `TcpListener::accept` for Android on x86 platforms (31a2777d8f).

This will really finally fix https://github.com/rust-lang/rust/issues/82400 for the main branch :)

r? ``@JohnTitor``
2021-03-09 09:05:22 +00:00
bors
bb3afe1e60 Auto merge of #82911 - m-ou-se:rollup-rjomgja, r=m-ou-se
Rollup of 11 pull requests

Successful merges:

 - #82711 (Add documentation for string->Cow conversions)
 - #82767 (Update minifier dependency version)
 - #82800 (Move rustdoc UI tests into a subdirectory)
 - #82810 (Typo fix in Unstable book: `cargo cov` -> `cargo profdata`)
 - #82829 (Handle negative literals in cast overflow warning)
 - #82854 (Account for `if (let pat = expr) {}`)
 - #82870 (Add note about the `#[doc(no-inline)]` usage)
 - #82874 (Add codegen tests for some issues closed by LLVM 12)
 - #82881 (diagnostics: Be clear about "crate root" and `::foo` paths in resolve diagnostics)
 - #82888 (Grammar Fixes)
 - #82897 ([.mailmap] Add entry for Ramkumar Ramachandra)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-03-09 01:47:39 +00:00
bors
eb476b172f Auto merge of #82877 - ehuss:revert-rwlock, r=m-ou-se
Revert switch of env locking to rwlock, to fix deadlock in process spawning

This reverts commit 354f19cf24, reversing changes made to 0cfba2fd09.

PR https://github.com/rust-lang/rust/pull/81850 switched the environment lock from a mutex to an rwlock. However, process spawning (when not able to use `posix_spawn`) locks the environment before forking, and unlocks it after forking (in both the parent and the child). With a mutex, this works (although probably not correct even with a mutex). With an rwlock, on at least some targets, unlocking in the child does not work correctly, resulting in a deadlock.

This has manifested as CI hangs on i686 Linux; that target doesn't use `posix_spawn` in the CI environment due to the age of the installed C library (currently glibc 2.23). (Switching to `posix_spawn` would just mask this issue, though, which would still arise in any case that can't use `posix_spawn`.)

Some additional cleanup of environment handling around process spawning may help, but for now, revert the PR and go back to a standard mutex.

Fixes #82221
2021-03-08 22:53:20 +00:00
Mara Bos
a55b192d59
Rollup merge of #82870 - jfrimmel:improve-docs, r=jyn514
Add note about the `#[doc(no-inline)]` usage

This is required to correctly build the documentation (including all submodules, that are only available in certain targets).

See the linked issue and #82861 for reference.
2021-03-08 20:09:03 +01:00
Dylan DPC
3b0a02a26b
Rollup merge of #82862 - athre0z:generalize-vec-write-impl, r=TimDiekmann
Generalize Write impl for Vec<u8> to Vec<u8, A>

As discussed in the [issue tracker for the wg-allocators working group][1], updating this impl for allocator support was most likely just forgotten previously. This PR fixes this.

r? `````@TimDiekmann`````

[1]: https://github.com/rust-lang/wg-allocators/issues/86
2021-03-08 13:13:27 +01:00
Julian Frimmel
c40ef91f76 Add note about the #[doc(no-inline)] usage
This is required to correctly build the documentation (including all
submodules, that are only available in certain targets).
2021-03-07 21:08:07 +01:00
Eric Huss
acdca316c3 Revert "use RWlock when accessing os::env #81850"
This reverts commit 354f19cf24, reversing
changes made to 0cfba2fd09.
2021-03-07 11:32:42 -08:00
Joel Höner
ab8995bbca Generalize Write impl for Vec<u8> to Vec<u8, A>
As discussed in the issue tracker for the wg-allocators working group[1], updating this implementation for allocator support was most likely just forgotten in the original PR.

[1]: https://github.com/rust-lang/wg-allocators/issues/86
2021-03-07 16:22:53 +01:00
Vadim Petrochenkov
5dad6c2575 Implement built-in attribute macro #[cfg_eval] 2021-03-06 23:03:19 +03:00
pierwill
b86c0d85e5 (std::net::parser): Fix capitalization of IP versions
Also add some missing punctuation in doc and code comments.
2021-03-05 22:27:38 -08:00
Maarten de Vries
c946d1d620 Bump libc dependency of std to 0.2.88. 2021-03-05 20:54:14 +01:00
zseri
93fda34bdb stabilize feature(osstring_ascii) 2021-03-05 20:02:48 +01:00
Alex Crichton
d6b06b8a32 std: Fix a bug on the wasm32-wasi target opening files
This commit fixes an issue pointed out in #82758 where LTO changed the
behavior of a program. It turns out that LTO was not at fault here, it
simply uncovered an existing bug. The bindings to
`__wasilibc_find_relpath` assumed that the relative portion of the path
returned was always contained within thee input `buf` we passed in. This
isn't actually the case, however, and sometimes the relative portion of
the path may reference a sub-portion of the input string itself.

The fix here is to use the relative path pointer coming out of
`__wasilibc_find_relpath` as the source of truth. The `buf` used for
local storage is discarded in this function and the relative path is
copied out unconditionally. We might be able to get away with some
`Cow`-like business or such to avoid the extra allocation, but for now
this is probably the easiest patch to fix the original issue.
2021-03-05 08:43:25 -08:00
Mara
04045cc83f
Rollup merge of #82770 - m-ou-se:assert-match, r=joshtriplett
Add assert_matches macro.

This adds `assert_matches!(expression, pattern)`.

Unlike the other asserts, this one ~~consumes the expression~~ may consume the expression, to be able to match the pattern. (It could add a `&` implicitly, but that's noticable in the pattern, and will make a consuming guard impossible.)

See https://github.com/rust-lang/rust/issues/62633#issuecomment-790737853

This re-uses the same `left: .. right: ..` output as the `assert_eq` and `assert_ne` macros, but with the pattern as the right part:

assert_eq:
```
assertion failed: `(left == right)`
  left: `Some("asdf")`,
 right: `None`
```
assert_matches:
```
assertion failed: `(left matches right)`
  left: `Ok("asdf")`,
 right: `Err(_)`
```

cc ```@cuviper```
2021-03-05 10:57:23 +01:00
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
Christiaan Dirkx
7539626c4a Move std::sys::unix::platform to std::sys::unix::ext 2021-03-02 00:00:04 +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
Christiaan Dirkx
5b84b9a8d8 Constify methods of std::net::SocketAddr, SocketAddrV4 and SocketAddrV6
The following methods are made unstable const under the `const_socketaddr` feature:

`SocketAddr`
 - `ip`
 - `port`
 - `is_ipv4`
 - `is_ipv6`

`SocketAddrV4`
 - `ip`
 - `port`

`SocketAddrV6`
 - `ip`
 - `port`
 - `flowinfo`
 - `scope_id`
2021-02-24 18:18:26 +01: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