Add a chapter on the test harness.
There isn't really any online documentation on the test harness, so this adds a chapter to the rustc book which provides information on how the harness works and details on the command-line options.
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
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
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.
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))
}
Specialize slice::fill with Copy type and u8/i8/bool
I don't expect rustperf could measure any perf improvements with this changes
since `slice::fill` is newly added.
Godbolt link for this change: <https://rust.godbolt.org/z/r3fzee>.
r? `@matthewjasper` since this patch added new specialization.
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
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``````
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```
[librustdoc] Only split lang string on `,`, ` `, and `\t`
Split markdown lang strings into tokens on `,`.
The previous behavior was to split lang strings into tokens on any
character that wasn't a `_`, `_`, or alphanumeric.
This is a potentially breaking change, so please scrutinize! See discussion in #78344.
I noticed some test cases that made me wonder if there might have been some reason for the original behavior:
```
t("{.no_run .example}", false, true, Ignore::None, true, false, false, false, v(), None);
t("{.sh .should_panic}", true, false, Ignore::None, false, false, false, false, v(), None);
t("{.example .rust}", false, false, Ignore::None, true, false, false, false, v(), None);
t("{.test_harness .rust}", false, false, Ignore::None, true, true, false, false, v(), None);
```
It seemed pretty peculiar to specifically test lang strings in braces, with all the tokens prefixed by `.`.
I did some digging, and it looks like the test cases were added way back in [this commit from 2014](https://github.com/rust-lang/rust/commit/3fef7a74ca9a) by `@skade.`
It looks like they were added just to make sure that the splitting was permissive, and aren't testing that those strings in particular are accepted.
Closes https://github.com/rust-lang/rust/issues/78344.
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>
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.
Make char and u8 methods const
char methods `len_utf8`, `len_utf16`, `to_ascii_lowercase`, `eq_ignore_ascii_case` can be made const.
`u8` methods `to_ascii_lowercase`, `to_ascii_uppercase` are required to be const as well.
`u8::eq_ignore_ascii_case` was additionally made const.
Rebase of https://github.com/rust-lang/rust/pull/79549 originally authored by ``@YenForYang.`` Changes from that PR:
- Squashed all commits from #79549.
- rebased to latest upstream master.
- Removed const attributes for `char::escape_unicode` and `char::escape_default`.
- Updated `since` attributes for `const` stabilization to 1.52.0.
cc ``@m-ou-se.``
Make ptr::write const
~~The code in this PR as of right now is not much more than an experiment.~~
~~This should, if I am not mistaken, in theory compile and pass the tests once the bootstraping compiler is updated. Thus the PR is blocked on that which should happen some time after the February the 9th. Also we might want to wait for #79989 to avoid regressing performance due to using `mem::forget` over `intrinsics::forget`~~.
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.
Convert core/num/mod.rs to intra-doc links
Helps with #75080.
This can't convert the associated constants `MAX` and `MIN` until #74489 is merged.
r? `@poliorcetics`
Expand FlattenCompat folds
The former `chain`+`chain`+`fold` implementation looked nice from a
functional-programming perspective, but it introduced unnecessary layers
of abstraction on every `flat_map`/`flatten` fold. It's straightforward
to just fold each part in turn, and this makes it look like a simplified
version of the existing `try_fold` implementation.
For the `iter::bench_flat_map*` benchmarks, I get a large improvement in
`bench_flat_map_chain_sum`, from 1,598,473 ns/iter to 499,889 ns/iter,
and the rest are unchanged.
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>
`escape_unicode`, `escape_default`, `len_utf8`, `len_utf16`, to_ascii_lowercase`, `eq_ignore_ascii_case`
`u8` methods `to_ascii_lowercase`, `to_ascii_uppercase` also must be made const
u8 methods made const
Update methods.rs
Update mod.rs
Update methods.rs
Fix `since` in rustc_const_stable to next stable
Fix `since` in rustc_const_stable to next stable
Update methods.rs
Update mod.rs
Improve non_fmt_panic lint.
This change:
- fixes the span used by this lint in the case the panic argument is a single macro expansion (e.g. `panic!(a!())`);
- adds a suggestion for `panic!(format!(..))` to remove `format!()` instead of adding `"{}", ` or using `panic_any` like it does now; and
- fixes the incorrect suggestion to replace `panic![123]` by `panic_any(123]`.
Fixes#82109.
Fixes#82110.
Fixes#82111.
Example output:
```
warning: panic message is not a string literal
--> src/main.rs:8:12
|
8 | panic!(format!("error: {}", "oh no"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(non_fmt_panic)]` on by default
= note: this is no longer accepted in Rust 2021
= note: the panic!() macro supports formatting, so there's no need for the format!() macro here
help: remove the `format!(..)` macro call
|
8 | panic!("error: {}", "oh no");
| -- --
```
r? `@estebank`
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.
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.
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]
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```
Avoid `cfg_if` in `std::os`
rust-analyzer cannot currently load the `cfg_if` crate, which means that rust-analyzer is unable to see `std::os::{unix, windows, linux}` here. This works around that by avoiding `cfg_if`; the `#[cfg]` expressions are simple enough to reasonably write by hand.
Fixes https://github.com/rust-analyzer/rust-analyzer/issues/6038
Slight perf improvement on char::to_ascii_lowercase
`char::to_ascii_lowercase()` was checking if it was ascii and then if it was in the right range. Instead propose to check once (I think removing a compare and a shift in the process: [godbolt](https://godbolt.org/z/e5Tora) ).
before:
```
test char::methods::bench_to_ascii_lowercase ... bench: 11,196 ns/iter (+/- 632)
test char::methods::bench_to_ascii_uppercase ... bench: 11,656 ns/iter (+/- 671)
```
after:
```
test char::methods::bench_to_ascii_lowercase ... bench: 9,612 ns/iter (+/- 979)
test char::methods::bench_to_ascii_uppercase ... bench: 8,241 ns/iter (+/- 701)
```
(calling u8::to_ascii_lowercase and letting that flip the 5th bit is also an option, but it's more instructions. I'm thinking for things around ascii and char we want to be as efficient as possible.)
Improve design of `assert_len`
It was discussed in the [tracking issue](https://github.com/rust-lang/rust/issues/76393#issuecomment-761765448) that `assert_len`'s name and usage are confusing. This PR improves them based on a suggestion by ``@scottmcm`` in that issue.
I also improved the documentation to make it clearer when you might want to use this method.
Old example:
```rust
let range = range.assert_len(slice.len());
```
New example:
```rust
let range = range.ensure_subset_of(..slice.len());
```
Fixes#81157
BTree: move more shared iterator code into navigate.rs
The functions in navigate.rs only exist to support iterators, and these look easier on my eyes if there is a shared `struct` with the recurring pair of handles.
r? `@Mark-Simulacrum`
BTreeMap: gather and decompose reusable tree fixing functions
This is kind of pushing it as a standalone refactor, probably only useful for #81075 (or similar).
r? `@Mark-Simulacrum`
improve UnsafeCell docs
Sometimes [questions like this come up](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-lang.2Fwg-unsafe-code-guidelines/topic/UnsafeCells.20as.20raw.20pointers) because the UnsafeCell docs say "it's the only legal way to obtain aliasable data that is considered mutable". That is not entirely correct, since raw pointers also provide that option. So I propose we focus the docs on the interaction of `UnsafeCell` and *shared references* specifically, which is really where they are needed.
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>
Add internal `collect_into_array[_unchecked]` to remove duplicate code
Unlike the similar PRs #69985, #75644 and #79659, this PR only adds private functions and does not propose any new public API. The change is just for the purpose of avoiding duplicate code.
Many array methods already contained the same kind of code and there are still many array related methods to come (e.g. `Iterator::{chunks, map_windows, next_n, ...}`, `[T; N]::{cloned, copied, ...}`, ...) which all basically need this functionality. Writing custom `unsafe` code for each of those doesn't seem like a good idea. I added two functions in this PR (and not just the `unsafe` version) because I already know that I need the `Option`-returning version for `Iterator::map_windows`.
This is closely related to https://github.com/rust-lang/rust/issues/81615. I think that all options listed in that issue can be implemented using the function added in this PR. The only instance where `collect_array_into` might not be general enough is when the caller want to handle incomplete arrays manually. Currently, if `iter` yields fewer than `N` items, `None` is returned and the already yielded items are dropped. But as this is just a private function, it can be made more general in future PRs.
And while this was not the goal, this seems to lead to better assembly for `array::map`: https://rust.godbolt.org/z/75qKTa (CC ``@JulianKnodt)``
Let me know what you think :)
CC ``@matklad`` ``@bstrie``
Because child > 0, the two statements are equivalent, but using
saturating_sub and <= yields in faster code. This is most notable in the
binary_heap::bench_into_sorted_vec benchmark, which shows a speedup of
1.26x, which uses sift_down_range internally. The speedup of pop (that
uses sift_down_to_bottom internally) is much less significant as the
sifting method is not called in a loop.
Rollup of 11 pull requests
Successful merges:
- #81300 (BTree: share panicky test code & test panic during clear, clone)
- #81706 (Document BinaryHeap unsafe functions)
- #81833 (parallelize x.py test tidy)
- #81966 (Add new `rustc` target for Arm64 machines that can target the iphonesimulator)
- #82154 (Update RELEASES.md 1.50 to include methods stabilized in #79342)
- #82177 (Do not delete bootstrap.exe on Windows during clean)
- #82181 (Add check for ES5 in CI)
- #82229 (Add [A-diagnostics] bug report template)
- #82233 (try-back-block-type test: Use TryFromSliceError for From test)
- #82302 (Remove unsafe impl Send for CompletedTest & TestResult)
- #82349 (test: Print test name only once on timeout)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
test: Print test name only once on timeout
Pretty formatter when using multiple test threads displays test name twice on
timeout event. This implicitly suggest that those are two different events,
while in fact they are always printed together.
Print test name only once.
Before:
```
running 3 tests
test src/lib.rs - c (line 16) ... ok
test src/lib.rs - a (line 3) ... ok
test src/lib.rs - b (line 9) ... test src/lib.rs - b (line 9) has been running for over 60 seconds
test src/lib.rs - b (line 9) ... ok
```
After:
```
running 3 tests
test src/lib.rs - c (line 16) ... ok
test src/lib.rs - a (line 3) ... ok
test src/lib.rs - b (line 9) has been running for over 60 seconds
test src/lib.rs - b (line 9) ... ok
```
Document BinaryHeap unsafe functions
`BinaryHeap` contains some private safe functions but that are actually unsafe to call. This PR marks them `unsafe` and documents all the `unsafe` function calls inside them.
While doing this I might also have found a bug: some "SAFETY" comments in `sift_down_range` and `sift_down_to_bottom` are valid only if you assume that `child` doesn't overflow. However it may overflow if `end > isize::MAX` which can be true for ZSTs (but I think only for them). I guess the easiest fix would be to skip any sifting if `mem::size_of::<T> == 0`.
Probably conflicts with #81127 but solving the eventual merge conflict should be pretty easy.
BTree: share panicky test code & test panic during clear, clone
Bases almost all tests of panic on the same, richer definition, and extends it to cloning to test panic during clone.
r? ```@Mark-Simulacrum```
Improve assert_eq! and assert_ne!
This PR improves `assert_eq!` and `assert_ne!` by moving the panicking code in an external function.
It does not change the fast path, but the move of the formatting in the cold path (the panic) may have a positive effect on in instruction cache use and with inlining.
Moreover, the use of trait objects instead of generic may improve compile times for `assert_eq!`-heavy code.
Godbolt link: ~~https://rust.godbolt.org/z/TYa9MT~~ \
Updated: https://rust.godbolt.org/z/bzE84x
Pretty formatter when using multiple test threads displays test name twice on
timeout event. This implicitly suggest that those are two different events,
while in fact they are always printed together.
Print test name only once.
Before:
```
running 3 tests
test src/lib.rs - c (line 16) ... ok
test src/lib.rs - a (line 3) ... ok
test src/lib.rs - b (line 9) ... test src/lib.rs - b (line 9) has been running for over 60 seconds
test src/lib.rs - b (line 9) ... ok
```
After:
```
running 3 tests
test src/lib.rs - c (line 16) ... ok
test src/lib.rs - a (line 3) ... ok
test src/lib.rs - b (line 9) has been running for over 60 seconds
test src/lib.rs - b (line 9) ... ok
```
simplify eat_digits
Simplify eat_digits by checking values in iterator, plus decrease function size, by returning unchecked slices.
https://godbolt.org/z/cxjav4
libtest: Fix unwrap panic on duplicate TestDesc
It is possible for different tests to collide to the same `TestDesc` when macros are involved. That is a bug, but it didn’t cause a panic until #81367. For now, change the code to ignore this problem.
Fixes#81852.
This will need to be applied to `beta` too.
Add tests for Atomic*::fetch_{min,max}
This ensures that all atomic operations except for fences are tested. This has been useful to test my work on using atomic instructions for atomic operations in cg_clif instead of a global lock.
It is possible for different tests to collide to the same TestDesc
when macros are involved. That is a bug, but it didn’t cause a panic
until #81367. For now, change the code to ignore this problem.
Fixes#81852.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
Ensure valid TraitRefs are created for GATs
This fixes `ProjectionTy::trait_ref` to use the correct substs. Places that need all of the substs have been updated to not use `trait_ref`.
r? ````@jackh726````
[libtest] Run the test synchronously when hitting thread limit
libtest currently panics if it hits the thread limit. This often results in spurious test failures (<code>thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 11, kind: WouldBlock, message: "Resource temporarily unavailable" }'</code> ... `error: test failed, to rerun pass '--lib'`). This PR makes it continue to run the test synchronously if it runs out of threads.
Closes#78165.
``@rustbot`` label: A-libtest T-libs
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`
Add a `Result::into_ok_or_err` method to extract a `T` from `Result<T, T>`
When updating code to handle the semi-recent deprecation of `compare_and_swap` in favor of `compare_exchange`, which returns `Result<T, T>`, I wanted this. I've also wanted it with code using `slice::binary_search` before.
The name (and perhaps the documentation) is the hardest part here, but this name seems consistent with the other Result methods, and equivalently memorable.
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>
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>
Document that `assert!` format arguments are evaluated lazily
It can be useful to do some computation in `assert!` format arguments, in order to get better error messages. For example:
```rust
assert!(
some_condition,
"The state is invalid. Details: {}",
expensive_call_to_get_debugging_info(),
);
```
It seems like `assert!` only evaluates the format arguments if the assertion fails, which is useful but doesn't appear to be documented anywhere. This PR documents the behavior and adds some tests.
To digit simplification
I found out the other day that all the ascii digits have the first four bits as one would hope them to. (Eg. char `2` ends `0b0010`). There are two bits to indicate it's in the digit range ( `0b0011_0000`). If it is a true digit then all the higher bits aside from these two will be 0 (as ascii is the lowest part of the unicode u32 spectrum). So XORing with `0b11_0000` should mean we either get the number 0-9 or alternativly we get a larger number in the u32 space. If we get something that's not 0-9 then it will be discarded as it will be greater than the radix.
The code seems so fast though that there's quite a lot of noise in the benchmarks so it's not that easy to prove conclusively that it's faster as well as less instructions.
The non-fast path I was toying with as well wondering if we could do this as then we'd only have one return and less instructions still:
```
match self {
'a'..='z' => self as u32 - 'a' as u32 + 10,
'A'..='Z' => self as u32 - 'A' as u32 + 10,
_ => { radix = 10; self as u32 ^ ASCII_DIGIT_MASK},
}
```
Here's the [godbolt](https://godbolt.org/z/883c9n).
( H/T to ``@byteshadow`` for pointing out xor was what I needed)
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>
It can be useful to do some computation in `assert!` format arguments, in order to get better error messages. For example:
```rust
assert!(
some_condition,
"The state is invalid. Details: {}",
expensive_call_to_get_debugging_info(),
);
```
It seems like `assert!` only evaluates the format arguments if the assertion fails, which is useful but doesn't appear to be documented anywhere. This PR documents the behavior and adds some tests.
The former `chain`+`chain`+`fold` implementation looked nice from a
functional-programming perspective, but it introduced unnecessary layers
of abstraction on every `flat_map`/`flatten` fold. It's straightforward
to just fold each part in turn, and this makes it look like a simplified
version of the existing `try_fold` implementation.
For the `iter::bench_flat_map*` benchmarks, I get a large improvement in
`bench_flat_map_chain_sum`, from 1,598,473 ns/iter to 499,889 ns/iter,
and the rest are unchanged.
This does not suggest adding such a function to the public API. This is
just for the purpose of avoiding duplicate code. Many array methods
already contained the same kind of code and there are still many array
related methods to come (e.g. `Iterator::{chunks, map_windows, next_n,
...}`) which all basically need this functionality. Writing custom
`unsafe` code for each of those seems not like a good idea.
The `may_have_side_effect` is an implementation detail of `TrustedRandomAccess`
trait. It describes if obtaining an iterator element may have side effects. It
is currently implemented as an associated function.
Turn `may_have_side_effect` into an associated constant. This makes the
value immediately available to the optimizer.
The use of module-level functions instead of associated functions
on `<*const T>` or `<*mut T>` follows the precedent of
`ptr::slice_from_raw_parts` and `ptr::slice_from_raw_parts_mut`.