about summary refs log tree commit diff
path: root/library/core/tests
AgeCommit message (Collapse)AuthorLines
2023-01-11Rollup merge of #106570 - Xaeroxe:div-duration-tests, r=JohnTitornils-0/+26
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-07add tests for div_duration_* functionsJacob Kiesel-0/+26
2023-01-04Update rand in the stdlib tests, and remove the getrandom feature from itThom Chiovoloni-9/+19
2023-01-02Remove test of static ContextDavid Tolnay-6/+2
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`
2022-12-30Update paths in comments.jonathanCogan-1/+1
2022-12-30Replace libstd, libcore, liballoc in line comments.jonathanCogan-2/+2
2022-12-28Update bootstrap cfgPietro Albini-20/+0
2022-12-27Rollup merge of #103718 - matklad:infer-lazy, r=dtolnayMichael Goulet-0/+6
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-23char: µoptimise UTF-16 surrogates decodingMichal Nazarewicz-0/+4
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-11-24Tune RepeatWith::try_fold and Take::for_each and Vec::extend_trustedScott McMurray-0/+20
2022-11-22Rollup merge of #83608 - Kimundi:index_many, r=Mark-SimulacrumManish Goregaokar-0/+61
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-20Add get_many_mut methods to sliceMarvin Löbel-0/+61
2022-11-20enable fuzzy_provenance_casts in libcore+testsRalf Jung-0/+1
2022-11-20avoid non-strict-provenance casts in libcore testsRalf Jung-1/+1
2022-11-20Rollup merge of #104435 - scottmcm:iter-repeat-n, r=thomccYuki Okushi-0/+50
`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: https://github.com/rust-lang/rust/blob/101e1822c3e54e63996c8aaa014d55716f3937eb/library/alloc/src/vec/mod.rs#L2479-L2492
2022-11-19update provenance testLukas Markeffsky-2/+46
* fix allocation alignment for 16bit platforms * add edge case where `stride % align != 0` on pointers with provenance
2022-11-19fix const `align_offset` implementationLukas Markeffsky-41/+63
2022-11-19add coretests for `is_aligned`Lukas Markeffsky-0/+50
2022-11-19add coretests for const `align_offset`Lukas Markeffsky-0/+166
2022-11-18Rollup merge of #103378 - nagisa:fix-infinite-offset, r=scottmcmManish Goregaokar-0/+12
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-16Auto merge of #102935 - ajtribick:display-float-0.5-fixed-0, r=scottmcmbors-4/+124
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-15`VecDeque::resize` should re-use the buffer in the passed-in elementScott McMurray-0/+50
Today it always copies it for *every* appended element, but one of those clones is avoidable.
2022-11-14Auto merge of #103858 - Mark-Simulacrum:bump-bootstrap, r=pietroalbinibors-1/+1
Bump bootstrap compiler to 1.66 This PR: - Bumps version placeholders to release - Bumps to latest beta - cfg-steps code r? `@pietroalbini`
2022-11-10Rollup merge of #104060 - ink-feather-org:const_hash, r=fee1-deadManish Goregaokar-11/+43
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-09Rollup merge of #103570 - lukas-code:stabilize-ilog, r=scottmcmDylan DPC-1/+0
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-08Test const `Hash`, fix nitsonestacked-11/+43
2022-11-07simplification: do not process the ArrayChunks remainder in fold()The 8472-1/+2
2022-11-06cfg-step codeMark Rousskov-1/+1
2022-11-01Format dyn Trait better in type_name intrinsicMichael Goulet-0/+18
2022-10-29interpret: fix align_of_val on packed typesRalf Jung-0/+22
2022-10-29More inference-friendly API for lazyAleksey Kladov-0/+6
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-26stabilize `int_log`Lukas Markeffsky-1/+0
2022-10-25stabilise array methodsDylan DPC-1/+0
2022-10-25Rollup merge of #98204 - Kixiron:stable-unzip, r=thomccDylan DPC-1/+0
Stabilize `Option::unzip()` Stabilizes `Option::unzip()`, closes #87800 ```@rustbot``` modify labels: +T-libs-api
2022-10-24Rollup merge of #102271 - ↵Yuki Okushi-1/+0
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-22Fix mod_inv termination for the last iterationSimonas Kazlauskas-0/+12
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-20Add tests for rounding of ties during float formattingAndrew Tribick-0/+120
2022-10-19Adjust `transmute{,_copy}` to be clearer about which of `T` and `U` is input ↵Thom Chiovoloni-1/+5
vs output
2022-10-17Remove all uses of array_assume_initAlex Saveau-4/+4
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-15Stabilize `duration_checked_float`Ryan Lopopolo-1/+0
Tracking issue: - https://github.com/rust-lang/rust/issues/83400
2022-10-14Auto merge of #103069 - matthiaskrgr:rollup-xxsx6sk, r=matthiaskrgrbors-0/+9
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-14Auto merge of #101030 - woppopo:const_location, r=scottmcmbors-0/+35
Constify `Location` methods Tracking issue: #102911 Example: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=4789884c2f16ec4fb0e0405d86b794f5
2022-10-14Fix `Duration::{try_,}from_secs_f{32,64}(-0.0)`beetrees-0/+9
2022-10-14more dupe word typosRageking8-1/+1
2022-10-12Rollup merge of #102578 - lukas-code:ilog-panic, r=m-ou-seDylan DPC-0/+30
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-11Fix inconsistent rounding of 0.5 when formatted to 0 decimal placesAndrew Tribick-4/+4
2022-10-11Change tracking issue from #76156 to #102911woppopo-0/+1
2022-10-09fixup lint nameMaybe Waffle-1/+1
2022-10-09allow `for_loop_over_fallibles` in a `core` testMaybe Waffle-0/+1
2022-10-08Fix test (location_const_file)woppopo-1/+1