Commit Graph

759 Commits

Author SHA1 Message Date
bors f9ba43ce14 Auto merge of #113295 - clarfonthey:ascii-step, r=cuviper
Implement Step for ascii::Char

This allows iterating over ranges of `ascii::Char`, similarly to ranges of `char`.

Note that `ascii::Char` is still unstable, tracked in #110998.
2023-09-02 00:02:50 +00:00
Matthias Krüger d2644d9fe9
Rollup merge of #114238 - jhpratt:fix-duration-div, r=thomcc
Fix implementation of `Duration::checked_div`

I ran across this while running some sanity checks on `time`. Quickcheck immediately found a bug, and as I'd modified the code from `std` I knew there was a bug here as well.

tl;dr this code fails ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1189a3efcdfc192c27d6d87815359353))

```rust
use std::time::Duration;

fn main() {
    assert_eq!(
        Duration::new(1, 1).checked_div(7),
        Some(Duration::new(0, 142_857_143)),
    );
}
```

The existing code determines that 1/7 = 0 (seconds), 1/7 = 0 (nanoseconds), 1 billion / 7 = 142,857,142 (extra nanoseconds). The billion comes from multiplying the remainder of the seconds (1) by the number of nanoseconds in a second. However, **this wrongly ignores any remaining nanoseconds**. This PR takes that into consideration, adds a test, and also changes the roundabout way of calculating the remainder into directly computing it.

Note: This is _not_ a rounding error. This result divides evenly.

`@rustbot` label +A-time +C-bug +S-waiting-on-reviewer +T-libs
2023-08-28 08:13:57 +02:00
bors 4cea2bc339 Auto merge of #113464 - waynr:remove-provider-trait, r=Amanieu
core/any: remove Provider trait, rename Demand to Request

This touches on two WIP features:

* `error_generic_member_access`
  * tracking issue: https://github.com/rust-lang/rust/issues/99301
  * RFC (WIP): https://github.com/rust-lang/rfcs/pull/2895
* `provide_any`
  * tracking issue: https://github.com/rust-lang/rust/issues/96024
  * RFC: https://github.com/rust-lang/rfcs/pull/3192

The changes in this PR are intended to address libs meeting feedback summarized by `@Amanieu` in https://github.com/rust-lang/rust/issues/96024#issuecomment-1554773172

The specific items this PR addresses so far are:

> We feel that the names "demand" and "request" are somewhat synonymous and would like only one of those to be used for better consistency.

I went with `Request` here since it sounds nicer, but I'm mildly concerned that at first glance it could be confused with the use of the word in networking context.

> The Provider trait should be deleted and its functionality should be merged into Error. We are happy to only provide an API that is only usable with Error. If there is demand for other uses then this can be provided through an external crate.

The net impact this PR has is that examples which previously looked like
```
    core::any::request_ref::<String>(&err).unwramp()
```

now look like
```
    (&err as &dyn core::error::Error).request_value::<String>().unwrap()
```

These are methods that based on the type hint when called return an `Option<T>` of that type. I'll admit I don't fully understand how that's done, but it involves `core::any::tags::Type` and `core::any::TaggedOption`, neither of which are exposed in the public API, to construct a `Request` which is then passed to the `Error.provide` method.

Something that I'm curious about is whether or not they are essential to the use of `Request` types (prior to this PR referred to as `Demand`) and if so does the fact that they are kept private imply that `Request`s are only meant to be constructed privately within the standard library? That's what it looks like to me.

These methods ultimately call into code that looks like:
```
/// Request a specific value by tag from the `Error`.
fn request_by_type_tag<'a, I>(err: &'a (impl Error + ?Sized)) -> Option<I::Reified>
where
    I: tags::Type<'a>,
{
    let mut tagged = core::any::TaggedOption::<'a, I>(None);
    err.provide(tagged.as_request());
    tagged.0
}
```

As far as the `Request` API is concerned, one suggestion I would like to make is that the previous example should look more like this:
```
/// Request a specific value by tag from the `Error`.
fn request_by_type_tag<'a, I>(err: &'a (impl Error + ?Sized)) -> Option<I::Reified>
where
    I: tags::Type<'a>,
{
    let tagged_request = core::any::Request<I>::new_tagged();
    err.provide(tagged_request);
    tagged.0
}
```
This makes it possible for anyone to construct a `Request` for use in their own projects without exposing an implementation detail like `TaggedOption` in the API surface.

Otherwise noteworthy is that I had to add `pub(crate)` on both `core::any::TaggedOption` and `core::any::tags` since `Request`s now need to be constructed in the `core::error` module. I considered moving `TaggedOption` into the `core::error` module but again I figured it's an implementation detail of `Request` and belongs closer to that.

At the time I am opening this PR, I have not yet looked into the following bit of feedback:

> We took a look at the generated code and found that LLVM is unable to optimize multiple .provide_* calls into a switch table because each call fetches the type id from Erased::type_id separately each time and the compiler doesn't know that these calls all return the same value. This should be fixed.

This is what I'll focus on next while waiting for feedback on the progress so far. I suspect that learning more about the type IDs will help me understand the need for `TaggedOption` a little better.
2023-08-14 18:18:03 +00:00
ltdk ef3305449b Implement Step for AsciiChar 2023-08-14 01:34:47 -04:00
wayne warren a646b39965 core/any: remove Provider trait
* remove `impl Provider for Error`
* rename `Demand` to `Request`
* update docstrings to focus on the conceptual API provided by `Request`
* move `core::any::{request_ref, request_value}` functions into `core::error`
* move `core::any::tag`, `core::any::Request`, an `core::any::TaggedOption` into `core::error`
* replace `provide_any` feature name w/ `error_generic_member_access`
* move `core::error::request_{ref,value} tests into core::tests::error module
* update unit and doc tests
2023-08-13 13:07:53 -06:00
Frank King 97c953f561 Add Iterator::map_windows
This is inherited from the old PR.

This method returns an iterator over mapped windows of the starting
iterator. Adding the more straight-forward `Iterator::windows` is not
easily possible right now as the items are stored in the iterator type,
meaning the `next` call would return references to `self`. This is not
allowed by the current `Iterator` trait design. This might change once
GATs have landed.

The idea has been brought up by @m-ou-se here:
https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Iterator.3A.3A.7Bpairwise.2C.20windows.7D/near/224587771

Co-authored-by: Lukas Kalbertodt <lukas.kalbertodt@gmail.com>
2023-08-11 07:26:51 +08:00
Jacob Pratt f1d4e48c9c
Fix implementation of `Duration::checked_div` 2023-07-30 04:00:02 -04:00
bors a5e2eca40e Auto merge of #112699 - bluebear94:mf/more-is-sorted-tests, r=cuviper
Add more comprehensive tests for is_sorted and friends

See #53485 and #55045.
2023-07-21 23:25:04 +00:00
KaDiWa c3462a0676
remove the unstable `core::sync::atomic::ATOMIC_*_INIT` constants 2023-07-18 09:45:52 +02:00
Mark Rousskov 67b0cfc761 Flip cfg's for bootstrap bump 2023-07-12 21:38:55 -04:00
Ralf Jung e1338cc254 enable test_join test in Miri 2023-07-03 14:05:55 +02:00
The 8472 6c87448b57 optimize Cstr/EscapeAscii display
old:
    ascii::bench_ascii_escape_display_mixed      17.97µs/iter +/- 204.00ns
    ascii::bench_ascii_escape_display_no_escape 545.00ns/iter   +/- 6.00ns
new:
    ascii::bench_ascii_escape_display_mixed      4.99µs/iter +/- 56.00ns
    ascii::bench_ascii_escape_display_no_escape 91.00ns/iter  +/- 1.00ns
2023-06-29 01:55:03 +02:00
bors ae8ffa663c Auto merge of #111850 - the8472:external-step-by, r=scottmcm
Specialize `StepBy<Range<{integer}>>`

OLD

    iter::bench_range_step_by_fold_u16      700.00ns/iter +/- 10.00ns
    iter::bench_range_step_by_fold_usize    519.00ns/iter  +/- 6.00ns
    iter::bench_range_step_by_loop_u32      555.00ns/iter  +/- 7.00ns
    iter::bench_range_step_by_sum_reducible  37.00ns/iter  +/- 0.00ns

NEW

    iter::bench_range_step_by_fold_u16       49.00ns/iter +/- 0.00ns
    iter::bench_range_step_by_fold_usize    194.00ns/iter +/- 1.00ns
    iter::bench_range_step_by_loop_u32       98.00ns/iter +/- 0.00ns
    iter::bench_range_step_by_sum_reducible   1.00ns/iter +/- 0.00ns

NEW + `-Ctarget-cpu=x86-64-v3`

    iter::bench_range_step_by_fold_u16      22.00ns/iter +/- 0.00ns
    iter::bench_range_step_by_fold_usize    80.00ns/iter +/- 1.00ns
    iter::bench_range_step_by_loop_u32      41.00ns/iter +/- 0.00ns
    iter::bench_range_step_by_sum_reducible  1.00ns/iter +/- 0.00ns

I have only optimized for walltime of those methods, I haven't tested whether it eliminates bounds checks when indexing into slices via things like `(0..slice.len()).step_by(16)`.
2023-06-26 00:28:30 +00:00
The 8472 070ce235f2 Specialize StepBy<Range<{integer}>>
For ranges < usize we determine the number of items
StepBy would yield and then store that in the range.end
instead of the actual end. This significantly
simplifies calculation of the loop induction variable
especially in cases where StepBy::step (an usize)
could overflow the Range's item type
2023-06-23 00:17:34 +02:00
Benjamin Lee 50246b0587
Implement slice::split_once and slice::rsplit_once
Feature gate is slice_split_once and tracking issue is #112811.
2023-06-19 17:54:52 -07:00
Michael Goulet e24fe97bd9
Rollup merge of #112606 - clarfonthey:ip-display, r=thomcc
Alter `Display` for `Ipv6Addr` for IPv4-compatible addresses

ACP: rust-lang/libs-team#239
2023-06-19 17:53:35 -07:00
+merlan #flirora c2e4e981b3 Add more comprehensive tests for is_sorted and friends
See #53485 and #55045.
2023-06-16 03:04:34 -04:00
许杰友 Jieyou Xu (Joe) 72b3b58efc
Extend `unused_must_use` to cover block exprs 2023-06-15 17:59:13 +08:00
ltdk 2dce58d0f6 Fix `SocketAddrV6: Display` tests 2023-06-14 15:21:15 -04:00
ltdk 2f2c3f55a9 Fix `Ipv6Addr: Display` tests 2023-06-14 14:25:25 -04:00
bors 371994e0d8 Auto merge of #112314 - ferrocene:pa-core-alloc-abort, r=bjorn3
Ignore `core`, `alloc` and `test` tests that require unwinding on `-C panic=abort`

Some of the tests for `core` and `alloc` require unwinding through their use of `catch_unwind`. These tests fail when testing using `-C panic=abort` (in my case through a target without unwinding support, and `-Z panic-abort-tests`), while they should be ignored as they don't indicate a failure.

This PR marks all of these tests with this attribute:

```rust
#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]
```

I'm not aware of a way to test this on rust-lang/rust's CI, as we don't test any target with `-C panic=abort`, but I tested this locally on a Ferrocene target and it does indeed make the test suite pass.
2023-06-13 19:03:27 +00:00
Pietro Albini 44556eed36
ignore core, alloc and test tests that require unwinding on panic=abort 2023-06-13 15:53:24 +02:00
Urgau d9d1c76ded Allow undropped_manually_drops for some tests 2023-06-08 11:41:34 +02:00
Mark Rousskov 42e757192d Bump to latest beta compiler 2023-05-30 08:00:10 -04:00
Lukas Markeffsky 7cdb23b98a don't skip inference for type in `offset_of!` 2023-05-20 15:20:27 +02:00
est31 30c0e4e72b Add more tests for the offset_of!() macro
* ensuring that offset_of!(Self, ...) works iff inside an impl block
* ensuring that the output type is usize and doesn't coerce. this can be
  changed in the future, but if it is done, it should be a conscious descision
* improving the privacy checking test
* ensuring that generics don't let you escape the unsized check
2023-05-18 13:16:17 +02:00
bors 18bfe5d8a9 Auto merge of #92048 - Urgau:num-midpoint, r=scottmcm
Add midpoint function for all integers and floating numbers

This pull-request adds the `midpoint` function to `{u,i}{8,16,32,64,128,size}`, `NonZeroU{8,16,32,64,size}` and `f{32,64}`.

This new function is analog to the [C++ midpoint](https://en.cppreference.com/w/cpp/numeric/midpoint) function, and basically compute `(a + b) / 2` with a rounding towards ~~`a`~~ negative infinity in the case of integers. Or simply said: `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a sufficiently-large signed integral type.

Note that unlike the C++ function this pull-request does not implement this function on pointers (`*const T` or `*mut T`). This could be implemented in a future pull-request if desire.

### Implementation

For `f32` and `f64` the implementation in based on the `libcxx` [one](18ab892ff7/libcxx/include/__numeric/midpoint.h (L65-L77)). I originally tried many different approach but all of them failed or lead me with a poor version of the `libcxx`. Note that `libstdc++` has a very similar one; Microsoft STL implementation is also basically the same as `libcxx`. It unfortunately doesn't seems like a better way exist.

For unsigned integers I created the macro `midpoint_impl!`, this macro has two branches:
 - The first one take `$SelfT` and is used when there is no unsigned integer with at least the double of bits. The code simply use this formula `a + (b - a) / 2` with the arguments in the correct order and signs to have the good rounding.
 - The second branch is used when a `$WideT` (at least double of bits as `$SelfT`) is provided, using a wider number means that no overflow can occur, this greatly improve the codegen (no branch and less instructions).

For signed integers the code basically forwards the signed numbers to the unsigned version of midpoint by mapping the signed numbers to their unsigned numbers (`ex: i8 [-128; 127] to [0; 255]`) and vice versa.
I originally created a version that worked directly on the signed numbers but the code was "ugly" and not understandable. Despite this mapping "overhead" the codegen is better than my most optimized version on signed integers.

~~Note that in the case of unsigned numbers I tried to be smart and used `#[cfg(target_pointer_width = "64")]` to determine if using the wide version was better or not by looking at the assembly on godbolt. This was applied to `u32`, `u64` and `usize` and doesn't change the behavior only the assembly code generated.~~
2023-05-14 19:33:02 +00:00
bors 81c2459af6 Stabilize const_ptr_read 2023-05-05 20:36:21 +02:00
Deadbeef e92806704b fix rustdoc and core test 2023-04-29 08:50:56 +00:00
Matthias Krüger 9babe98562
Rollup merge of #110419 - jsoref:spelling-library, r=jyn514
Spelling library

Split per https://github.com/rust-lang/rust/pull/110392

I can squash once people are happy w/ the changes. It's really uncommon for large sets of changes to be perfectly acceptable w/o at least some changes.

I probably won't have time to respond until tomorrow or the next day
2023-04-26 18:51:41 +02:00
Loïc BRANSTETT bf73234d92 Implement midpoint for all floating point f32 and f64 2023-04-26 10:18:53 +02:00
Loïc BRANSTETT 1a72d7c7c4 Implement midpoint for all signed and unsigned integers 2023-04-26 10:18:53 +02:00
Josh Soref 9cb9346005 Spelling library/
* advance
* aligned
* borrowed
* calculate
* debugable
* debuggable
* declarations
* desugaring
* documentation
* enclave
* ignorable
* initialized
* iterator
* kaboom
* monomorphization
* nonexistent
* optimizer
* panicking
* process
* reentrant
* rustonomicon
* the
* uninitialized

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>
2023-04-26 02:10:22 -04:00
DrMeepster a642563d49 major test improvements 2023-04-21 02:45:48 -07:00
DrMeepster 2bcb018253 fmt 2023-04-21 02:14:03 -07:00
DrMeepster b92c2f792c fix incorrect param env in dead code lint 2023-04-21 02:14:03 -07:00
DrMeepster b95852b93c test improvements 2023-04-21 02:14:03 -07:00
DrMeepster 511e457c4b offset_of 2023-04-21 02:14:02 -07:00
John Millikin 4e2797dd76 Implement `Neg` for signed non-zero integers.
Negating a non-zero integer currently requires unpacking to a
primitive and re-wrapping. Since negation of non-zero signed
integers always produces a non-zero result, it is safe to
implement `Neg` for `NonZeroI{N}`.

The new `impl` is marked as stable because trait implementations
for two stable types can't be marked unstable.
2023-04-20 14:27:29 +09:00
bors 3a5c8e91f0 Auto merge of #110393 - fee1-dead-contrib:rm-const-traits, r=oli-obk
Rm const traits in libcore

See [zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/.60const.20Trait.60.20removal.20or.20rework)

* [x] Bless ui tests
* [ ] Re constify some unstable functions with workarounds if they are needed
2023-04-19 13:03:40 +00:00
Deadbeef 4c6ddc036b fix library and rustdoc tests 2023-04-16 11:38:52 +00:00
Deadbeef 76dbe29104 rm const traits in libcore 2023-04-16 06:49:27 +00:00
est31 77821b2eb9 Remove unused unused_macros
The macro is always used
2023-04-16 08:35:39 +02:00
Tobias Decking 65c9c79d3f
remove obsolete test 2023-04-10 21:57:45 +02:00
Tobias Decking 0f96c71792 Improve the floating point parser in `dec2flt`.
* Remove all remaining traces of unsafe.
* Put `parse_8digits` inside a loop.
* Rework parsing of inf/NaN values.
2023-04-10 00:47:08 +02:00
Deadbeef 04a5d61161 Revert "Mark DoubleEndedIterator as #[const_trait] using rustc_do_not_const_check, implement const Iterator and DoubleEndedIterator for Range."
This reverts commit 8a9d6bf4fd.
2023-04-08 08:18:29 +00:00
Trevor Gross dc4ba57566 Stabilize a portion of 'once_cell'
Move items not part of this stabilization to 'lazy_cell' or 'once_cell_try'
2023-03-29 18:04:44 -04:00
bors cdbbce0a9e Auto merge of #108095 - soc:drop-contains, r=Amanieu
Drop unstable `Option::contains`, `Result::contains`, `Result::contains_err`

This is a proposal to drop the three functions `Option::contains`, `Result::contains` and `Result::contains_err`.

The discovery of `Option::is_some_with`/`Result::is_ok_with`/`Result::is_err_with` in https://github.com/rust-lang/rust/pull/93051 obviates the need for these methods (non-stabilization tracked in https://github.com/rust-lang/rust/issues/62358).

An additional benefit of change is that it avoids spurious error messages in IDEs, when `contains` is supplied by a third-party library:
![option-result-unstable](https://user-images.githubusercontent.com/42493/219127961-13cb559e-6ee8-4449-8dc9-d28d07270ad5.png)
2023-03-28 23:20:30 +00:00
The 8472 e29b27b4a4 replace advance_by returning usize with Result<(), NonZeroUsize> 2023-03-27 16:03:14 +02:00
The 8472 69db91b8b2 Change advance(_back)_by to return `usize` instead of `Result<(), usize>`
A successful advance is now signalled by returning `0` and other values now represent the remaining number
of steps that couldn't be advanced as opposed to the amount of steps that have been advanced during a partial advance_by.

This simplifies adapters a bit, replacing some `match`/`if` with arithmetic. Whether this is beneficial overall depends
on whether `advance_by` is mostly used as a building-block for other iterator methods and adapters or whether
we also see uses by users where `Result` might be more useful.
2023-03-27 14:11:49 +02:00
onestacked 8a9d6bf4fd Mark DoubleEndedIterator as #[const_trait] using rustc_do_not_const_check, implement const Iterator and DoubleEndedIterator for Range. 2023-03-18 09:17:37 +01:00
Mara Bos 96d252160e Update format_args!() test to account for inlining. 2023-03-16 11:21:50 +01:00
est31 999405059c Match unmatched backticks in library/ 2023-03-03 03:03:29 +01:00
Ralf Jung 229aef1f7d add missing feature in core/tests 2023-02-28 10:07:57 +01:00
Linus Färnstrand 6cb34492a6 Move IpAddr and SocketAddr to core 2023-02-26 13:50:08 +01:00
soc 3aa9f76a3a
Remove `#![feature(option_result_contains)]` from library/core/tests/lib.rs 2023-02-15 19:30:02 +00:00
bors 2d91939bb7 Auto merge of #107634 - scottmcm:array-drain, r=thomcc
Improve the `array::map` codegen

The `map` method on arrays [is documented as sometimes performing poorly](https://doc.rust-lang.org/std/primitive.array.html#note-on-performance-and-stack-usage), and after [a question on URLO](https://users.rust-lang.org/t/try-trait-residual-o-trait-and-try-collect-into-array/88510?u=scottmcm) prompted me to take another look at the core [`try_collect_into_array`](7c46fb2111/library/core/src/array/mod.rs (L865-L912)) function, I had some ideas that ended up working better than I'd expected.

There's three main ideas in here, split over three commits:
1. Don't use `array::IntoIter` when we can avoid it, since that seems to not get SRoA'd, meaning that every step writes things like loop counters into the stack unnecessarily
2. Don't return arrays in `Result`s unnecessarily, as that doesn't seem to optimize away even with `unwrap_unchecked` (perhaps because it needs to get moved into a new LLVM type to account for the discriminant)
3. Don't distract LLVM with all the `Option` dances when we know for sure we have enough items (like in `map` and `zip`).  This one's a larger commit as to do it I ended up adding a new `pub(crate)` trait, but hopefully those changes are still straight-forward.

(No libs-api changes; everything should be completely implementation-detail-internal.)

It's still not completely fixed -- I think it needs pcwalton's `memcpy` optimizations still (#103830) to get further -- but this seems to go much better than before.  And the remaining `memcpy`s are just `transmute`-equivalent (`[T; N] -> ManuallyDrop<[T; N]>` and `[MaybeUninit<T>; N] -> [T; N]`), so hopefully those will be easier to remove with LLVM16 than the previous subobject copies 🤞

r? `@thomcc`

As a simple example, this test
```rust
pub fn long_integer_map(x: [u32; 64]) -> [u32; 64] {
    x.map(|x| 13 * x + 7)
}
```
On nightly <https://rust.godbolt.org/z/xK7548TGj> takes `sub rsp, 808`
```llvm
start:
  %array.i.i.i.i = alloca [64 x i32], align 4
  %_3.sroa.5.i.i.i = alloca [65 x i32], align 4
  %_5.i = alloca %"core::iter::adapters::map::Map<core::array::iter::IntoIter<u32, 64>, [closure@/app/example.rs:2:11: 2:14]>", align 8
```
(and yes, that's a 6**5**-element array `alloca` despite 6**4**-element input and output)

But with this PR it's only `sub rsp, 520`
```llvm
start:
  %array.i.i.i.i.i.i = alloca [64 x i32], align 4
  %array1.i.i.i = alloca %"core::mem::manually_drop::ManuallyDrop<[u32; 64]>", align 4
```

Similarly, the loop it emits on nightly is scalar-only and horrifying
```nasm
.LBB0_1:
        mov     esi, 64
        mov     edi, 0
        cmp     rdx, 64
        je      .LBB0_3
        lea     rsi, [rdx + 1]
        mov     qword ptr [rsp + 784], rsi
        mov     r8d, dword ptr [rsp + 4*rdx + 528]
        mov     edi, 1
        lea     edx, [r8 + 2*r8]
        lea     r8d, [r8 + 4*rdx]
        add     r8d, 7
.LBB0_3:
        test    edi, edi
        je      .LBB0_11
        mov     dword ptr [rsp + 4*rcx + 272], r8d
        cmp     rsi, 64
        jne     .LBB0_6
        xor     r8d, r8d
        mov     edx, 64
        test    r8d, r8d
        jne     .LBB0_8
        jmp     .LBB0_11
.LBB0_6:
        lea     rdx, [rsi + 1]
        mov     qword ptr [rsp + 784], rdx
        mov     edi, dword ptr [rsp + 4*rsi + 528]
        mov     r8d, 1
        lea     esi, [rdi + 2*rdi]
        lea     edi, [rdi + 4*rsi]
        add     edi, 7
        test    r8d, r8d
        je      .LBB0_11
.LBB0_8:
        mov     dword ptr [rsp + 4*rcx + 276], edi
        add     rcx, 2
        cmp     rcx, 64
        jne     .LBB0_1
```

whereas with this PR it's unrolled and vectorized
```nasm
	vpmulld	ymm1, ymm0, ymmword ptr [rsp + 64]
	vpaddd	ymm1, ymm1, ymm2
	vmovdqu	ymmword ptr [rsp + 328], ymm1
	vpmulld	ymm1, ymm0, ymmword ptr [rsp + 96]
	vpaddd	ymm1, ymm1, ymm2
	vmovdqu	ymmword ptr [rsp + 360], ymm1
```
(though sadly still stack-to-stack)
2023-02-13 10:18:48 +00:00
Matthias Krüger 454ae9fb8b
Rollup merge of #107954 - RalfJung:tree-borrows-fix, r=m-ou-se
avoid mixing accesses of ptrs derived from a mutable ref and parent ptrs

``@Vanille-N`` is working on a successor for Stacked Borrows. It will mostly accept strictly more code than Stacked Borrows did, with one exception: the following pattern no longer works.
```rust
let mut root = 6u8;
let mref = &mut root;
let ptr = mref as *mut u8;
*ptr = 0; // Write
assert_eq!(root, 0); // Parent Read
*ptr = 0; // Attempted Write
```
This worked in Stacked Borrows kind of by accident: when doing the "parent read", under SB we Disable `mref`, but the raw ptrs derived from it remain usable. The fact that we can still use the "children" of a reference that is no longer usable is quite nasty and leads to some undesirable effects (in particular it is the major blocker for resolving https://github.com/rust-lang/unsafe-code-guidelines/issues/257). So in Tree Borrows we no longer do that; instead, reading from `root` makes `mref` and all its children read-only.

Due to other improvements in Tree Borrows, the entire Miri test suite still passes with this new behavior, and even the entire libcore and liballoc test suite, except for these 2 cases this PR fixes. Both of these involve code where the programmer wrote `&mut` but then used pointers derived from that reference in ways that alias with the parent pointer, which arguably is violating uniqueness. They are fixed by properly using raw pointers throughout.
2023-02-12 22:29:49 +01:00
Ralf Jung c3a2e7a809 avoid mixing accesses of ptrs derived from a mutable ref and parent ptrs 2023-02-12 15:16:27 +01:00
bors adb4bfd25d Auto merge of #105671 - lukas-code:depreciate-char, r=scottmcm
Use associated items of `char` instead of freestanding items in `core::char`

The associated functions and constants on `char` have been stable since 1.52 and the freestanding items have soft-deprecated since 1.62 (https://github.com/rust-lang/rust/pull/95566). This PR ~~marks them as "deprecated in future", similar to the integer and floating point modules (`core::{i32, f32}` etc)~~ replaces all uses of `core::char::*` with `char::*` to prepare for future deprecation of `core::char::*`.
2023-02-12 11:09:06 +00:00
Scott McMurray 5bc328fdef Allow canonicalizing the `array::map` loop in trusted cases 2023-02-04 16:44:51 -08:00
Scott McMurray 5a7342c3dd Stop using `into_iter` in `array::map` 2023-02-04 16:41:35 -08:00
Nikolai Vazquez 734a91358b Remove unnecessary `&format!`
These were likely from before the `PartialEq<str>` impl for `&String`.
2023-01-21 22:06:42 -05:00
André Vennberg 0b35f448f8 Remove various double spaces in source comments. 2023-01-14 17:22:04 +01:00
Lukas Markeffsky 76e216f29b Use associated items of `char` instead of freestanding items in `core::char` 2023-01-14 11:58:41 +01:00
Daniel Henry-Mantilla 48b7e2a5b9
Stabilize `::{core,std}::pin::pin!` 2023-01-11 14:09:14 -08:00
nils c962b07ed3
Rollup merge of #106570 - Xaeroxe:div-duration-tests, r=JohnTitor
add tests for div_duration_* functions

Per https://github.com/rust-lang/rust/issues/63139#issuecomment-817070719

this adds unit tests for the functions that will hopefully effectively demonstrate that `div_duration` is ready to be stabilized.
2023-01-11 17:30:54 +01:00
Jacob Kiesel 9fd744b3e3 add tests for div_duration_* functions 2023-01-07 11:05:33 -07:00
Thom Chiovoloni a4bf36e87b
Update rand in the stdlib tests, and remove the getrandom feature from it 2023-01-04 14:52:41 -08:00
David Tolnay 257e766c0c
Remove test of static Context
Context is no longer Sync so this doesn't work.

    error[E0277]: `*mut ()` cannot be shared between threads safely
      --> library/core/tests/task.rs:24:21
       |
    24 |     static CONTEXT: Context<'static> = Context::from_waker(&WAKER);
       |                     ^^^^^^^^^^^^^^^^ `*mut ()` cannot be shared between threads safely
       |
       = help: within `Context<'static>`, the trait `Sync` is not implemented for `*mut ()`
       = note: required because it appears within the type `PhantomData<*mut ()>`
       = note: required because it appears within the type `Context<'static>`
       = note: shared static variables must have a type that implements `Sync`
2023-01-02 10:33:23 -08:00
jonathanCogan 78691e3589 Update paths in comments. 2022-12-30 14:00:42 +01:00
jonathanCogan db47071df2 Replace libstd, libcore, liballoc in line comments. 2022-12-30 14:00:42 +01:00
Pietro Albini 11191279b7 Update bootstrap cfg 2022-12-28 09:18:43 -05:00
Michael Goulet 4b668a1fee
Rollup merge of #103718 - matklad:infer-lazy, r=dtolnay
More inference-friendly API for lazy

The signature for new was

```
fn new<F>(f: F) -> Lazy<T, F>
```

Notably, with `F` unconstrained, `T` can be literally anything, and just `let _ = Lazy::new(|| 92)` would not typecheck.

This historiacally was a necessity -- `new` is a `const` function, it couldn't have any bounds. Today though, we can move `new` under the `F: FnOnce() -> T` bound, which gives the compiler enough data to infer the type of T from closure.
2022-12-27 12:33:33 -08:00
Michal Nazarewicz 28162ad970 char: µoptimise UTF-16 surrogates decoding
According to Godbolt¹, on x86_64 using binary and produces slightly
better code than using subtraction.  Readability of both is pretty
much equivalent so might just as well use the shorter option.

¹ https://rust.godbolt.org/z/9jM3ejbMx
2022-12-23 14:15:33 +01:00
Scott McMurray 9d68a1a74c Tune RepeatWith::try_fold and Take::for_each and Vec::extend_trusted 2022-11-24 19:14:19 -08:00
Manish Goregaokar 1dd515f273
Rollup merge of #83608 - Kimundi:index_many, r=Mark-Simulacrum
Add slice methods for indexing via an array of indices.

Disclaimer: It's been a while since I contributed to the main Rust repo, apologies in advance if this is large enough already that it should've been an RFC.

---

# Update:

- Based on feedback, removed the `&[T]` variant of this API, and removed the requirements for the indices to be sorted.

# Description

This adds the following slice methods to `core`:

```rust
impl<T> [T] {
    pub unsafe fn get_many_unchecked_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut T; N];
    pub fn get_many_mut<const N: usize>(&mut self, indices: [usize; N]) -> Option<[&mut T; N]>;
}
```

This allows creating multiple mutable references to disjunct positions in a slice, which previously required writing some awkward code with `split_at_mut()` or `iter_mut()`. For the bound-checked variant, the indices are checked against each other and against the bounds of the slice, which requires `N * (N + 1) / 2` comparison operations.

This has a proof-of-concept standalone implementation here: https://crates.io/crates/index_many

Care has been taken that the implementation passes miri borrow checks, and generates straight-forward assembly (though this was only checked on x86_64).

# Example

```rust
let v = &mut [1, 2, 3, 4];
let [a, b] = v.get_many_mut([0, 2]).unwrap();
std::mem::swap(a, b);
*v += 100;
assert_eq!(v, &[3, 2, 101, 4]);
```

# Codegen Examples

<details>
  <summary>Click to expand!</summary>

Disclaimer: Taken from local tests with the standalone implementation.

## Unchecked Indexing:

```rust
pub unsafe fn example_unchecked(slice: &mut [usize], indices: [usize; 3]) -> [&mut usize; 3] {
    slice.get_many_unchecked_mut(indices)
}
```

```nasm
example_unchecked:
 mov     rcx, qword, ptr, [r9]
 mov     r8, qword, ptr, [r9, +, 8]
 mov     r9, qword, ptr, [r9, +, 16]
 lea     rcx, [rdx, +, 8*rcx]
 lea     r8, [rdx, +, 8*r8]
 lea     rdx, [rdx, +, 8*r9]
 mov     qword, ptr, [rax], rcx
 mov     qword, ptr, [rax, +, 8], r8
 mov     qword, ptr, [rax, +, 16], rdx
 ret
```

## Checked Indexing (Option):

```rust
pub unsafe fn example_option(slice: &mut [usize], indices: [usize; 3]) -> Option<[&mut usize; 3]> {
    slice.get_many_mut(indices)
}
```

```nasm
 mov     r10, qword, ptr, [r9, +, 8]
 mov     rcx, qword, ptr, [r9, +, 16]
 cmp     rcx, r10
 je      .LBB0_7
 mov     r9, qword, ptr, [r9]
 cmp     rcx, r9
 je      .LBB0_7
 cmp     rcx, r8
 jae     .LBB0_7
 cmp     r10, r9
 je      .LBB0_7
 cmp     r9, r8
 jae     .LBB0_7
 cmp     r10, r8
 jae     .LBB0_7
 lea     r8, [rdx, +, 8*r9]
 lea     r9, [rdx, +, 8*r10]
 lea     rcx, [rdx, +, 8*rcx]
 mov     qword, ptr, [rax], r8
 mov     qword, ptr, [rax, +, 8], r9
 mov     qword, ptr, [rax, +, 16], rcx
 ret
.LBB0_7:
 mov     qword, ptr, [rax], 0
 ret
```

## Checked Indexing (Panic):

```rust
pub fn example_panic(slice: &mut [usize], indices: [usize; 3]) -> [&mut usize; 3] {
    let len = slice.len();
    match slice.get_many_mut(indices) {
        Some(s) => s,
        None => {
            let tmp = indices;
            index_many::sorted_bound_check_failed(&tmp, len)
        }
    }
}
```

```nasm
example_panic:
 sub     rsp, 56
 mov     rax, qword, ptr, [r9]
 mov     r10, qword, ptr, [r9, +, 8]
 mov     r9, qword, ptr, [r9, +, 16]
 cmp     r9, r10
 je      .LBB0_6
 cmp     r9, rax
 je      .LBB0_6
 cmp     r9, r8
 jae     .LBB0_6
 cmp     r10, rax
 je      .LBB0_6
 cmp     rax, r8
 jae     .LBB0_6
 cmp     r10, r8
 jae     .LBB0_6
 lea     rax, [rdx, +, 8*rax]
 lea     r8, [rdx, +, 8*r10]
 lea     rdx, [rdx, +, 8*r9]
 mov     qword, ptr, [rcx], rax
 mov     qword, ptr, [rcx, +, 8], r8
 mov     qword, ptr, [rcx, +, 16], rdx
 mov     rax, rcx
 add     rsp, 56
 ret
.LBB0_6:
 mov     qword, ptr, [rsp, +, 32], rax
 mov     qword, ptr, [rsp, +, 40], r10
 mov     qword, ptr, [rsp, +, 48], r9
 lea     rcx, [rsp, +, 32]
 mov     edx, 3
 call    index_many::bound_check_failed
 ud2
```
</details>

# Extensions

There are multiple optional extensions to this.

## Indexing With Ranges

This could easily be expanded to allow indexing with `[I; N]` where `I: SliceIndex<Self>`.  I wanted to keep the initial implementation simple, so I didn't include it yet.

## Panicking Variant

We could also add this method:

```rust
impl<T> [T] {
    fn index_many_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut T; N];
}
```

This would work similar to the regular index operator and panic with out-of-bound indices. The advantage would be that we could more easily ensure good codegen with a useful panic message, which is non-trivial with the `Option` variant.

This is implemented in the standalone implementation, and used as basis for the codegen examples here and there.
2022-11-22 01:26:05 -05:00
Marvin Löbel 3fe37b8c6e Add get_many_mut methods to slice 2022-11-20 11:19:11 -05:00
Ralf Jung 428ab59fb7 enable fuzzy_provenance_casts in libcore+tests 2022-11-20 16:04:16 +01:00
Ralf Jung 2bb28c174b avoid non-strict-provenance casts in libcore tests 2022-11-20 09:58:29 +01:00
Yuki Okushi 785237d392
Rollup merge of #104435 - scottmcm:iter-repeat-n, r=thomcc
`VecDeque::resize` should re-use the buffer in the passed-in element

Today it always copies it for *every* appended element, but one of those clones is avoidable.

This adds `iter::repeat_n` (https://github.com/rust-lang/rust/issues/104434) as the primitive needed to do this.  If this PR is acceptable, I'll also use this in `Vec` rather than its custom `ExtendElement` type & infrastructure that is harder to share between multiple different containers:

101e1822c3/library/alloc/src/vec/mod.rs (L2479-L2492)
2022-11-20 13:15:59 +09:00
Lukas Markeffsky c9c017dfb5 update provenance test
* fix allocation alignment for 16bit platforms
* add edge case where `stride % align != 0` on pointers with provenance
2022-11-19 16:58:02 +01:00
Lukas Markeffsky 9e5d497b67 fix const `align_offset` implementation 2022-11-19 16:57:58 +01:00
Lukas Markeffsky 2ef9a8ae0f add coretests for `is_aligned` 2022-11-19 16:47:42 +01:00
Lukas Markeffsky 8cf6b16185 add coretests for const `align_offset` 2022-11-19 16:47:38 +01:00
Manish Goregaokar 6b09d60f82
Rollup merge of #103378 - nagisa:fix-infinite-offset, r=scottmcm
Fix mod_inv termination for the last iteration

On usize=u64 platforms, the 4th iteration would overflow the `mod_gate` back to 0. Similarly for usize=u32 platforms, the 3rd iteration would overflow much the same way.

I tested various approaches to resolving this, including approaches with `saturating_mul` and `widening_mul` to a double usize. Turns out LLVM likes `mul_with_overflow` the best. In fact now, that LLVM can see the iteration count is limited, it will happily unroll the loop into a nice linear sequence.

You will also notice that the code around the loop got simplified somewhat. Now that LLVM is handling the loop nicely, there isn’t any more reasons to manually unroll the first iteration out of the loop (though looking at the code today I’m not sure all that complexity was necessary in the first place).

Fixes #103361
2022-11-18 17:48:16 -05:00
bors e702534763 Auto merge of #102935 - ajtribick:display-float-0.5-fixed-0, r=scottmcm
Fix inconsistent rounding of 0.5 when formatted to 0 decimal places

As described in #70336, when displaying values to zero decimal places the value of 0.5 is rounded to 1, which is inconsistent with the display of other half-integer values which round to even.

From testing the flt2dec implementation, it looks like this comes down to the condition in the fixed-width Dragon implementation where an empty buffer is treated as a case to apply rounding up. I believe the change below fixes it and updates only the relevant tests.

Nevertheless I am aware this is very much a core piece of functionality, so please take a very careful look to make sure I haven't missed anything. I hope this change does not break anything in the wider ecosystem as having a consistent rounding behaviour in floating point formatting is in my opinion a useful feature to have.

Resolves #70336
2022-11-16 07:20:30 +00:00
Scott McMurray d62b903892 `VecDeque::resize` should re-use the buffer in the passed-in element
Today it always copies it for *every* appended element, but one of those clones is avoidable.
2022-11-15 00:53:26 -08:00
bors 338cfd3cce Auto merge of #103858 - Mark-Simulacrum:bump-bootstrap, r=pietroalbini
Bump bootstrap compiler to 1.66

This PR:

- Bumps version placeholders to release
- Bumps to latest beta
- cfg-steps code

r? `@pietroalbini`
2022-11-14 00:07:19 +00:00
Manish Goregaokar 150e0ec393
Rollup merge of #104060 - ink-feather-org:const_hash, r=fee1-dead
Make `Hash`, `Hasher` and `BuildHasher` `#[const_trait]` and make `Sip` const `Hasher`

This PR enables using Hashes in const context.

r? ``@fee1-dead``
2022-11-10 10:47:38 -05:00
Dylan DPC 1db7f690b1
Rollup merge of #103570 - lukas-code:stabilize-ilog, r=scottmcm
Stabilize integer logarithms

Stabilizes feature `int_log`.

I've also made the functions const stable, because they don't depend on any unstable const features. `rustc_allow_const_fn_unstable` is just there for `Option::expect`, which could be replaced with a `match` and `panic!`. cc ``@rust-lang/wg-const-eval``

closes https://github.com/rust-lang/rust/issues/70887 (tracking issue)

~~blocked on FCP finishing: https://github.com/rust-lang/rust/issues/70887#issuecomment-1289028216~~
FCP finished: https://github.com/rust-lang/rust/issues/70887#issuecomment-1302121266
2022-11-09 19:21:21 +05:30
onestacked 56e59bcb27 Test const `Hash`, fix nits 2022-11-08 17:39:40 +01:00
The 8472 43c353fff7 simplification: do not process the ArrayChunks remainder in fold() 2022-11-07 21:44:25 +01:00
Mark Rousskov 40290505fb cfg-step code 2022-11-06 17:21:21 -05:00
Michael Goulet e24df2778f Format dyn Trait better in type_name intrinsic 2022-11-01 20:41:47 +00:00
Ralf Jung d366471e58 interpret: fix align_of_val on packed types 2022-10-29 15:58:32 +02:00
Aleksey Kladov 3cddc8bff6 More inference-friendly API for lazy
The signature for new was

```
fn new<F>(f: F) -> Lazy<T, F>
```

Notably, with `F` unconstrained, `T` can be literally anything, and just
`let _ = Lazy::new(|| 92)` would not typecheck.

This historiacally was a necessity -- `new` is a `const` function, it
couldn't have any bounds. Today though, we can move `new` under the `F:
FnOnce() -> T` bound, which gives the compiler enough data to infer the
type of T from closure.
2022-10-29 09:56:20 +01:00
Lukas Markeffsky 9e36fd926c stabilize `int_log` 2022-10-26 11:58:33 +02:00
Dylan DPC 2326f42ce2 stabilise array methods 2022-10-25 18:07:21 +05:30
Dylan DPC d2d44f619f
Rollup merge of #98204 - Kixiron:stable-unzip, r=thomcc
Stabilize `Option::unzip()`

Stabilizes `Option::unzip()`, closes #87800

```@rustbot``` modify labels: +T-libs-api
2022-10-25 14:43:13 +05:30
Yuki Okushi c1f9d985d7
Rollup merge of #102271 - lopopolo:lopopolo/stabilize-duration-try-from-secs-float, r=dtolnay
Stabilize `duration_checked_float`

## Stabilization Report

This stabilization report is for a stabilization of `duration_checked_float`, tracking issue: https://github.com/rust-lang/rust/issues/83400.

### Implementation History

- https://github.com/rust-lang/rust/pull/82179
- https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051
- Changed error type to `FromFloatSecsError` in https://github.com/rust-lang/rust/pull/90247
- https://github.com/rust-lang/rust/pull/96051 changes the rounding mode to round-to-nearest instead of truncate.

## API Summary

This stabilization report proposes the following API to be stabilized in `core`, along with their re-exports in `std`:

```rust
// core::time

impl Duration {
    pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, TryFromFloatSecsError>;
    pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TryFromFloatSecsError { ... }

impl core::fmt::Display for TryFromFloatSecsError { ... }
impl core::error::Error for TryFromFloatSecsError { ... }
```

These functions are made const unstable under `duration_consts_float`, tracking issue #72440.

There is an open question in the tracking issue around what the error type should be called which I was hoping to resolve in the context of an FCP.

In this stabilization PR, I have altered the name of the error type to `TryFromFloatSecsError`. In my opinion, the error type shares the name of the method (adjusted to accommodate both types of floats), which is consistent with other error types in `core`, `alloc` and `std` like `TryReserveError` and `TryFromIntError`.

## Experience Report

Code such as this is ready to be converted to a checked API to ensure it is panic free:

```rust
impl Time {
    pub fn checked_add_f64(&self, seconds: f64) -> Result<Self, TimeError> {
        // Fail safely during `f64` conversion to duration
        if seconds.is_nan() || seconds.is_infinite() {
            return Err(TzOutOfRangeError::new().into());
        }

        if seconds.is_sign_positive() {
            self.checked_add(Duration::from_secs_f64(seconds))
        } else {
            self.checked_sub(Duration::from_secs_f64(-seconds))
        }
    }
}
```

See: https://github.com/artichoke/artichoke/issues/2194.

`@rustbot` label +T-libs-api -T-libs

cc `@mbartlett21`
2022-10-24 19:32:26 +09:00
Simonas Kazlauskas a3c3f722b7 Fix mod_inv termination for the last iteration
On usize=u64 platforms, the 4th iteration would overflow the `mod_gate`
back to 0. Similarly for usize=u32 platforms, the 3rd iteration would
overflow much the same way.

I tested various approaches to resolving this, including approaches with
`saturating_mul` and `widening_mul` to a double usize. Turns out LLVM
likes `mul_with_overflow` the best. In fact now, that LLVM can see the
iteration count is limited, it will happily unroll the loop into a nice
linear sequence.

You will also notice that the code around the loop got simplified
somewhat. Now that LLVM is handling the loop nicely, there isn’t any
more reasons to manually unroll the first iteration out of the loop
(though looking at the code today I’m not sure all that complexity was
necessary in the first place).

Fixes #103361
2022-10-22 03:46:48 +03:00
Andrew Tribick aa9837ba29 Add tests for rounding of ties during float formatting 2022-10-20 22:09:24 +02:00
Thom Chiovoloni afd08175de
Adjust `transmute{,_copy}` to be clearer about which of `T` and `U` is input vs output 2022-10-19 22:36:14 -07:00
Alex Saveau 55d71c61b8
Remove all uses of array_assume_init
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17 13:03:54 -07:00
Ryan Lopopolo 95040a70d7
Stabilize `duration_checked_float`
Tracking issue:

- https://github.com/rust-lang/rust/issues/83400
2022-10-15 12:02:13 -07:00
bors 8147e6e427 Auto merge of #103069 - matthiaskrgr:rollup-xxsx6sk, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #102092 (refactor: use grep -E/-F instead of fgrep/egrep)
 - #102781 (Improved documentation for `std::io::Error`)
 - #103017 (Avoid dropping TLS Key on sgx)
 - #103039 (checktools: fix comments)
 - #103045 (Remove leading newlines from integer primitive doc examples)
 - #103047 (Update browser-ui-test version to fix some flaky tests)
 - #103054 (Clean up rust-logo rustdoc GUI test)
 - #103059 (Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`)
 - #103067 (More alphabetical sorting)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-14 22:56:53 +00:00
bors bf15a9e526 Auto merge of #101030 - woppopo:const_location, r=scottmcm
Constify `Location` methods

Tracking issue: #102911

Example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4789884c2f16ec4fb0e0405d86b794f5
2022-10-14 20:15:51 +00:00
beetrees c9948f5c5f
Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)` 2022-10-14 16:07:09 +01:00
Rageking8 7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
Dylan DPC d8091f8991
Rollup merge of #102578 - lukas-code:ilog-panic, r=m-ou-se
Panic for invalid arguments of `{integer primitive}::ilog{,2,10}` in all modes

Decision made in https://github.com/rust-lang/rust/issues/100422#issuecomment-1245864700

resolves https://github.com/rust-lang/rust/issues/100422

tracking issue: https://github.com/rust-lang/rust/issues/70887

r? `@m-ou-se`
2022-10-12 11:11:25 +05:30
Andrew Tribick 848744403a Fix inconsistent rounding of 0.5 when formatted to 0 decimal places 2022-10-11 23:09:23 +02:00
woppopo a53e3acca9 Change tracking issue from #76156 to #102911 2022-10-11 06:40:37 +00:00
Maybe Waffle 7434b9f0d1 fixup lint name 2022-10-09 13:07:21 +00:00
Maybe Waffle 75ae20a42f allow `for_loop_over_fallibles` in a `core` test 2022-10-09 13:07:20 +00:00
woppopo f0b8167a4e Fix test (location_const_file) 2022-10-08 11:48:53 +00:00
Ralf Jung fd59d44f58 make const_err a hard error 2022-10-07 18:08:49 +02:00
Matthias Krüger a5488826a9
Rollup merge of #101308 - nerdypepper:feature/is-ascii-octdigit, r=joshtriplett
introduce `{char, u8}::is_ascii_octdigit`

This feature adds two new APIs: `char::is_ascii_octdigit` and `u8::is_ascii_octdigit`, under the feature gate `is_ascii_octdigit`. These methods are shorthands for `char::is_digit(self, 8)` and `u8::is_digit(self, 8)`:

```rust
// core::char

impl char {
    pub fn is_ascii_octdigit(self) -> bool;
}

// core::num

impl u8 {
    pub fn is_ascii_octdigit(self) -> bool;
}
```

---

Couple of things I need help understanding:

- `const`ness: have I used the right attribute in this case?
- is there a way to run the tests for `core::char` alone, instead of `./x.py test library/core`?
2022-10-03 20:58:56 +02:00
Lukas Markeffsky 6acc29f88b add tests for panicking integer logarithms 2022-10-02 14:25:36 +02:00
beetrees e409ce2159
Fix integer overflow in `format!("{:.0?}", Duration::MAX)` 2022-09-29 23:06:22 +01:00
woppopo 7b993885d0 Sort mod 2022-09-27 19:53:58 +00:00
woppopo ca55a88161 Fix indent 2022-09-27 19:40:53 +00:00
woppopo 767a7771c7 Add newlines 2022-09-27 19:23:52 +00:00
woppopo 834cab7244 Add test cases for const `Location` 2022-09-27 19:09:32 +00:00
Urgau 9ad2f00f6a Stabilize bench_black_box 2022-09-27 17:38:51 +02:00
Akshay 591c1f25b2 introduce `{char, u8}::is_ascii_octdigit` 2022-09-27 11:55:13 +05:30
y86-dev 9a78faba71 Made from_waker, waker, from_raw const 2022-09-14 14:53:16 +02:00
bors 7200da0217 Auto merge of #93873 - Stovent:big-ints, r=m-ou-se
Reimplement `carrying_add` and `borrowing_sub` for signed integers.

As per the discussion in #85532, this PR reimplements `carrying_add` and `borrowing_sub` for signed integers.

It also adds unit tests for both unsigned and signed integers, emphasing on the behaviours of the methods.
2022-09-09 00:59:08 +00:00
Guillaume Gomez 0e82dc969f
Rollup merge of #99583 - shepmaster:provider-plus-plus, r=yaahc
Add additional methods to the Demand type

This adds on to the original tracking issue #96024

r? `````@yaahc`````
2022-09-02 11:34:46 +02:00
Dylan DPC 395ce34a95
Rollup merge of #100819 - WaffleLapkin:use_ptr_byte_methods, r=scottmcm
Make use of `[wrapping_]byte_{add,sub}`

These new methods trivially replace old `.cast().wrapping_offset().cast()` & similar code.
Note that [`arith_offset`](https://doc.rust-lang.org/std/intrinsics/fn.arith_offset.html) and `wrapping_offset` are the same thing.

r? ``@scottmcm``

_split off from #100746_
2022-08-29 16:49:43 +05:30
Yuki Okushi ba31a9b505
Rollup merge of #100604 - dtolnay:okorerr, r=m-ou-se
Remove unstable Result::into_ok_or_err

Pending FCP: https://github.com/rust-lang/rust/issues/82223#issuecomment-1214920203

```@rustbot``` label +waiting-on-fcp
2022-08-26 09:51:44 +09:00
Matthias Krüger 6deca5f067
Rollup merge of #100220 - scottmcm:fix-by-ref-sized, r=joshtriplett
Properly forward `ByRefSized::fold` to the inner iterator

cc ``@timvermeulen,`` who noticed this mistake in https://github.com/rust-lang/rust/pull/100214#issuecomment-1207317625
2022-08-24 18:20:08 +02:00
Maybe Waffle 53565b23ac Make use of `[wrapping_]byte_{add,sub}`
...replacing `.cast().wrapping_offset().cast()` & similar code.
2022-08-23 19:32:37 +04:00
Jake Goulding 38de102cff Support eager and lazy methods for providing references and values
There are times where computing a value may be cheap, or where
computing a reference may be expensive, so this fills out the
possibilities.
2022-08-23 09:58:50 -04:00
Matthias Krüger d49906519b
Rollup merge of #99544 - dylni:expose-utf8lossy, r=Mark-Simulacrum
Expose `Utf8Lossy` as `Utf8Chunks`

This PR changes the feature for `Utf8Lossy` from `str_internals` to `utf8_lossy` and improves the API. This is done to eventually expose the API as stable.

Proposal: rust-lang/libs-team#54
Tracking Issue: #99543
2022-08-20 19:32:07 +02:00
dylni e8ee0b7b2b Expose `Utf8Lossy` as `Utf8Chunks` 2022-08-20 12:49:20 -04:00
bors 6c943bad02 Auto merge of #99541 - timvermeulen:flatten_cleanup, r=the8472
Refactor iteration logic in the `Flatten` and `FlatMap` iterators

The `Flatten` and `FlatMap` iterators both delegate to `FlattenCompat`:
```rust
struct FlattenCompat<I, U> {
    iter: Fuse<I>,
    frontiter: Option<U>,
    backiter: Option<U>,
}
```
Every individual iterator method that `FlattenCompat` implements needs to carefully manage this state, checking whether the `frontiter` and `backiter` are present, and storing the current iterator appropriately if iteration is aborted. This has led to methods such as `next`, `advance_by`, and `try_fold` all having similar code for managing the iterator's state.

I have extracted this common logic of iterating the inner iterators with the option to exit early into a `iter_try_fold` method:
```rust
impl<I, U> FlattenCompat<I, U>
where
    I: Iterator<Item: IntoIterator<IntoIter = U>>,
{
    fn iter_try_fold<Acc, Fold, R>(&mut self, acc: Acc, fold: Fold) -> R
    where
        Fold: FnMut(Acc, &mut U) -> R,
        R: Try<Output = Acc>,
    { ... }
}
```
It passes each of the inner iterators to the given function as long as it keep succeeding. It takes care of managing `FlattenCompat`'s state, so that the actual `Iterator` methods don't need to. The resulting code that makes use of this abstraction is much more straightforward:
```rust
fn next(&mut self) -> Option<U::Item> {
    #[inline]
    fn next<U: Iterator>((): (), iter: &mut U) -> ControlFlow<U::Item> {
        match iter.next() {
            None => ControlFlow::CONTINUE,
            Some(x) => ControlFlow::Break(x),
        }
    }

    self.iter_try_fold((), next).break_value()
}
```
Note that despite being implemented in terms of `iter_try_fold`, `next` is still able to benefit from `U`'s `next` method. It therefore does not take the performance hit that implementing `next` directly in terms of `Self::try_fold` causes (in some benchmarks).

This PR also adds `iter_try_rfold` which captures the shared logic of `try_rfold` and `advance_back_by`, as well as `iter_fold` and `iter_rfold` for folding without early exits (used by `fold`, `rfold`, `count`, and `last`).

Benchmark results:
```
                                             before                after
bench_flat_map_sum                       423,255 ns/iter      414,338 ns/iter
bench_flat_map_ref_sum                 1,942,139 ns/iter    2,216,643 ns/iter
bench_flat_map_chain_sum               1,616,840 ns/iter    1,246,445 ns/iter
bench_flat_map_chain_ref_sum           4,348,110 ns/iter    3,574,775 ns/iter
bench_flat_map_chain_option_sum          780,037 ns/iter      780,679 ns/iter
bench_flat_map_chain_option_ref_sum    2,056,458 ns/iter      834,932 ns/iter
```

I added the last two benchmarks specifically to demonstrate an extreme case where `FlatMap::next` can benefit from custom internal iteration of the outer iterator, so take it with a grain of salt. We should probably do a perf run to see if the changes to `next` are worth it in practice.
2022-08-19 02:34:30 +00:00
David Tolnay 83f081fc01
Remove unstable Result::into_ok_or_err 2022-08-17 17:20:42 -07:00
Scott McMurray 7680c8b690 Properly forward `ByRefSized::fold` to the inner iterator 2022-08-14 22:55:30 -07:00
austinabell 00bc9e8ac4
fix(iter::skip): Optimize `next` and `nth` implementations of `Skip` 2022-08-14 13:25:13 -04:00
Dylan DPC 482a6eaf10
Rollup merge of #100026 - WaffleLapkin:array-chunks, r=scottmcm
Add `Iterator::array_chunks` (take N+1)

A revival of https://github.com/rust-lang/rust/pull/92393.

r? `@Mark-Simulacrum`
cc `@rossmacarthur` `@scottmcm` `@the8472`

I've tried to address most of the review comments on the previous attempt. The only thing I didn't address is `try_fold` implementation, I've left the "custom" one for now, not sure what exactly should it use.
2022-08-14 17:09:14 +05:30
Dylan DPC 51eed00ca9
Rollup merge of #100030 - WaffleLapkin:nice_pointer_sis, r=scottmcm
cleanup code w/ pointers in std a little

Use pointer methods (`byte_add`, `null_mut`, etc) to make code in std a little nicer.
2022-08-12 20:39:10 +05:30
Matthias Krüger 275d4e779a
Rollup merge of #100112 - RalfJung:assert_send_and_sync, r=m-ou-se
Fix test: chunks_mut_are_send_and_sync

Follow-up to https://github.com/rust-lang/rust/pull/100023 to make the test actually effective
2022-08-11 22:53:03 +02:00
bors 908fc5b26d Auto merge of #99174 - scottmcm:reoptimize-layout-array, r=joshtriplett
Reoptimize layout array

This way it's one check instead of two, so hopefully (cc #99117) it'll be simpler for rustc perf too 🤞

Quick demonstration:
```rust
pub fn demo(n: usize) -> Option<Layout> {
    Layout::array::<i32>(n).ok()
}
```

Nightly: <https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=e97bf33508aa03f38968101cdeb5322d>
```nasm
	mov	rax, rdi
	mov	ecx, 4
	mul	rcx
	seto	cl
	movabs	rdx, 9223372036854775805
	xor	esi, esi
	cmp	rax, rdx
	setb	sil
	shl	rsi, 2
	xor	edx, edx
	test	cl, cl
	cmove	rdx, rsi
	ret
```

This PR (note no `mul`, in addition to being much shorter):
```nasm
	xor	edx, edx
	lea	rax, [4*rcx]
	shr	rcx, 61
	sete	dl
	shl	rdx, 2
	ret
```

This is built atop `@CAD97` 's #99136; the new changes are cb8aba66ef6a0e17f08a0574e4820653e31b45a0.

I added a bunch more tests for `Layout::from_size_align` and `Layout::array` too.
2022-08-10 23:50:18 +00:00
Eric Holk c18f22058b Rename integer log* methods to ilog*
This reflects the concensus from the libs team as reported at
https://github.com/rust-lang/rust/issues/70887#issuecomment-1209513261

Co-authored-by: Yosh Wuyts <github@yosh.is>
2022-08-09 10:20:49 -07:00
Maybe Waffle 127b6c4c18 cleanup code w/ pointers in std a little 2022-08-05 16:47:49 +04:00
Tim Vermeulen 3f7004920c Move `fold` logic to `iter_fold` method and reuse it in `count` and `last` 2022-08-05 03:43:39 +02:00
Ralf Jung a61c841385 actually call assert_send_and_sync 2022-08-03 12:44:21 -04:00
Maybe Waffle 4db628a801 Remove incorrect impl `TrustedLen` for `ArrayChunks`
As explained in the review of the previous attempt to add `ArrayChunks`,
adapters that shrink the length can't implement `TrustedLen`.
2022-08-01 19:16:24 +04:00
Ben Kimock 22dfbdd707 Add back Send and Sync impls on ChunksMut iterators
These were accidentally removed in #94247 because the representation was
changed from &mut [T] to *mut T, which has !Send + !Sync.
2022-08-01 10:32:45 -04:00