summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2021-08-27make `BuildHasher` object safeibraheemdev-1/+4
2021-07-24Rollup merge of #87255 - RalfJung:miri-test-libcore, r=Mark-SimulacrumYuki Okushi-0/+4
better support for running libcore tests with Miri See https://github.com/rust-lang/miri-test-libstd/issues/4 for a description of the problem that this fixes. Thanks to `@hyd-dev` for suggesting this patch!
2021-07-23Rollup merge of #87034 - mgeier:doc-step_by, r=JohnTitorYuki Okushi-6/+7
DOC: fix hypothetical Rust code in `step_by()` docstring I don't know how important that is, but if I'm not mistaken, the hypothetical code in the docstring of `step_by()` (see https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.step_by) isn't correct. I guess writing `next()` instead of `self.next()` isn't a biggie, but this would also imply that `advance_n_and_return_first()` is a method, which AFAICT it isn't. I've also done some re-formatting in a separate commit and a parameter renaming in yet another commit. Feel free to take or leave any combination of those commits.
2021-07-22Rollup merge of #87343 - ↵Guillaume Gomez-25/+1
steffahn:fix_unsound_zip_optimization_only_regression_fix, r=cuviper Regression fix to avoid further beta backports: Remove unsound TrustedRandomAccess implementations Removes the implementations that depend on the user-definable trait `Copy`. Only fix regressions to ensure merge in 1.55: Does not modify `vec::IntoIter`. <hr> This PR applies the beta-`1.53` backport #86222 (merged as part of #86225), a reduced version of #85874 that only fixes regressions, to `master` in order to avoid the need for further backports from `1.55` onwards. Beta-`1.54` backport already happened with #87136. In case that #85874 gets merged quickly (within a week), this PR would be unnecessary. r? `@cuviper`
2021-07-21Rollup merge of #81864 - ijackson:globalalloc-example, r=AmanieuEric Huss-11/+56
docs: GlobalAlloc: completely replace example with one that works Since this is an example, this could really do with some review from someone familiar with unsafe stuff! I made the example no longer `no_run` since it works for me. Fixes #81847
2021-07-21Remove unsound TrustedRandomAccess implementationsFrank Steffahn-25/+1
Removes the implementations that depend on the user-definable trait `Copy`. Only fix regressions to ensure merge in 1.55: Does not modify `vec::IntoIter`.
2021-07-21docs: GlobalAlloc: Make example only require 4096-aligned staticIan Jackson-3/+3
Alignments > 4k are not supported, https://github.com/rust-lang/rust/issues/70022 https://github.com/rust-lang/rust/issues/70144 Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
2021-07-20Auto merge of #87168 - the8472:flatten-len, r=scottmcmbors-1/+93
implement TrustedLen for Flatten/FlatMap if the U: IntoIterator == [T; N] This only works if arrays are passed directly instead of array iterators because we need to be sure that they have not been advanced before Flatten does its size calculation. resolves #87094
2021-07-20docs: GlobalAlloc: completely replace example with one that worksIan Jackson-11/+56
Since this is an example, this could really do with some review from someone familiar with unsafe stuff ! I made the example no longer `no_run` since it works for me. Fixes #81847 Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk> Co-authored-by: Amanieu d'Antras <amanieu@gmail.com>
2021-07-19replace Option combinators with try blockThe8472-6/+2
2021-07-19Rollup merge of #87227 - bstrie:asm2arch, r=AmanieuGuillaume Gomez-42/+50
Move asm! and global_asm! to core::arch Follow-up to https://github.com/rust-lang/stdarch/pull/1183 . Implements the libs-api team decision from rust-lang/rust#84019 (comment) . In order to not break nightly users, this PR also adds the newly-moved items to the prelude. However, a decision will need to be made before stabilization as to whether these items should remain in the prelude. I will file an issue for this separately. Fixes #84019 . r? `@Amanieu`
2021-07-19Auto merge of #87196 - oxalica:option-insert-must-use, r=joshtriplettbors-0/+1
Mark `Option::insert` as must_use Some people seems misled by the function name and use it in case where a simple assignment just works. If the return value is not used, `option = Some(value);` should be preferred instead of `option.insert(value);`
2021-07-18Move asm! and global_asm! to core::archbstrie-42/+50
2021-07-18better support for running libcore and liballoc tests with MiriRalf Jung-0/+4
2021-07-18Rollup merge of #87183 - RalfJung:option-doctest, r=jyn514Yuki Okushi-1/+1
fix typo in compile_fail doctest Fixes a typo introduced by https://github.com/rust-lang/rust/pull/86211. For some reason this typo makes Miri go all crazy when running libcore doctests (https://github.com/rust-lang/miri/issues/1852). Kudos to ``@hyd-dev`` for noticing the typo. Cc ``@tlyu`` ``@joshtriplett``
2021-07-18Rollup merge of #87170 - xFrednet:clippy-5393-add-diagnostic-items, ↵Yuki Okushi-0/+14
r=Manishearth,oli-obk Add diagnostic items for Clippy This adds a bunch of diagnostic items to `std`/`core`/`alloc` functions, structs and traits used in Clippy. The actual refactorings in Clippy to use these items will be done in a different PR in Clippy after the next sync. This PR doesn't include all paths Clippy uses, I've only gone through the first 85 lines of Clippy's [`paths.rs`](https://github.com/rust-lang/rust-clippy/blob/ecf85f4bdc319f9d9d853d1fff68a8a25e64c7a8/clippy_utils/src/paths.rs) (after rust-lang/rust-clippy#7466) to get some feedback early on. I've also decided against adding diagnostic items to methods, as it would be nicer and more scalable to access them in a nicer fashion, like adding a `is_diagnostic_assoc_item(did, sym::Iterator, sym::map)` function or something similar (Suggested by `@camsteffen` [on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/147480-t-compiler.2Fwg-diagnostics/topic/Diagnostic.20Item.20Naming.20Convention.3F/near/225024603)) There seems to be some different naming conventions when it comes to diagnostic items, some use UpperCamelCase (`BinaryHeap`) and some snake_case (`hashmap_type`). This PR uses UpperCamelCase for structs and traits and snake_case with the module name as a prefix for functions. Any feedback on is this welcome. cc: rust-lang/rust-clippy#5393 r? `@Manishearth`
2021-07-17Auto merge of #86761 - Alexhuszagh:master, r=estebankbors-2396/+2146
Update Rust Float-Parsing Algorithms to use the Eisel-Lemire algorithm. # Summary Rust, although it implements a correct float parser, has major performance issues in float parsing. Even for common floats, the performance can be 3-10x [slower](https://arxiv.org/pdf/2101.11408.pdf) than external libraries such as [lexical](https://github.com/Alexhuszagh/rust-lexical) and [fast-float-rust](https://github.com/aldanor/fast-float-rust). Recently, major advances in float-parsing algorithms have been developed by Daniel Lemire, along with others, and implement a fast, performant, and correct float parser, with speeds up to 1200 MiB/s on Apple's M1 architecture for the [canada](https://github.com/lemire/simple_fastfloat_benchmark/blob/0e2b5d163d4074cc0bde2acdaae78546d6e5c5f1/data/canada.txt) dataset, 10x faster than Rust's 130 MiB/s. In addition, [edge-cases](https://github.com/rust-lang/rust/issues/85234) in Rust's [dec2flt](https://github.com/rust-lang/rust/tree/868c702d0c9a471a28fb55f0148eb1e3e8b1dcc5/library/core/src/num/dec2flt) algorithm can lead to over a 1600x slowdown relative to efficient algorithms. This is due to the use of Clinger's correct, but slow [AlgorithmM and Bellepheron](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.45.4152&rep=rep1&type=pdf), which have been improved by faster big-integer algorithms and the Eisel-Lemire algorithm, respectively. Finally, this algorithm provides substantial improvements in the number of floats the Rust core library can parse. Denormal floats with a large number of digits cannot be parsed, due to use of the `Big32x40`, which simply does not have enough digits to round a float correctly. Using a custom decimal class, with much simpler logic, we can parse all valid decimal strings of any digit count. ```rust // Issue in Rust's dec2fly. "2.47032822920623272088284396434110686182e-324".parse::<f64>(); // Err(ParseFloatError { kind: Invalid }) ``` # Solution This pull request implements the Eisel-Lemire algorithm, modified from [fast-float-rust](https://github.com/aldanor/fast-float-rust) (which is licensed under Apache 2.0/MIT), along with numerous modifications to make it more amenable to inclusion in the Rust core library. The following describes both features in fast-float-rust and improvements in fast-float-rust for inclusion in core. **Documentation** Extensive documentation has been added to ensure the code base may be maintained by others, which explains the algorithms as well as various associated constants and routines. For example, two seemingly magical constants include documentation to describe how they were derived as follows: ```rust // Round-to-even only happens for negative values of q // when q ≥ −4 in the 64-bit case and when q ≥ −17 in // the 32-bitcase. // // When q ≥ 0,we have that 5^q ≤ 2m+1. In the 64-bit case,we // have 5^q ≤ 2m+1 ≤ 2^54 or q ≤ 23. In the 32-bit case,we have // 5^q ≤ 2m+1 ≤ 2^25 or q ≤ 10. // // When q < 0, we have w ≥ (2m+1)×5^−q. We must have that w < 2^64 // so (2m+1)×5^−q < 2^64. We have that 2m+1 > 2^53 (64-bit case) // or 2m+1 > 2^24 (32-bit case). Hence,we must have 2^53×5^−q < 2^64 // (64-bit) and 2^24×5^−q < 2^64 (32-bit). Hence we have 5^−q < 2^11 // or q ≥ −4 (64-bit case) and 5^−q < 2^40 or q ≥ −17 (32-bitcase). // // Thus we have that we only need to round ties to even when // we have that q ∈ [−4,23](in the 64-bit case) or q∈[−17,10] // (in the 32-bit case). In both cases,the power of five(5^|q|) // fits in a 64-bit word. const MIN_EXPONENT_ROUND_TO_EVEN: i32; const MAX_EXPONENT_ROUND_TO_EVEN: i32; ``` This ensures maintainability of the code base. **Improvements for Disguised Fast-Path Cases** The fast path in float parsing algorithms attempts to use native, machine floats to represent both the significant digits and the exponent, which is only possible if both can be exactly represented without rounding. In practice, this means that the significant digits must be 53-bits or less and the then exponent must be in the range `[-22, 22]` (for an f64). This is similar to the existing dec2flt implementation. However, disguised fast-path cases exist, where there are few significant digits and an exponent above the valid range, such as `1.23e25`. In this case, powers-of-10 may be shifted from the exponent to the significant digits, discussed at length in https://github.com/rust-lang/rust/issues/85198. **Digit Parsing Improvements** Typically, integers are parsed from string 1-at-a-time, requiring unnecessary multiplications which can slow down parsing. An approach to parse 8 digits at a time using only 3 multiplications is described in length [here](https://johnnylee-sde.github.io/Fast-numeric-string-to-int/). This leads to significant performance improvements, and is implemented for both big and little-endian systems. **Unsafe Changes** Relative to fast-float-rust, this library makes less use of unsafe functionality and clearly documents it. This includes the refactoring and documentation of numerous unsafe methods undesirably marked as safe. The original code would look something like this, which is deceptively marked as safe for unsafe functionality. ```rust impl AsciiStr { #[inline] pub fn step_by(&mut self, n: usize) -> &mut Self { unsafe { self.ptr = self.ptr.add(n) }; self } } ... #[inline] fn parse_scientific(s: &mut AsciiStr<'_>) -> i64 { // the first character is 'e'/'E' and scientific mode is enabled let start = *s; s.step(); ... } ``` The new code clearly documents safety concerns, and does not mark unsafe functionality as safe, leading to better safety guarantees. ```rust impl AsciiStr { /// Advance the view by n, advancing it in-place to (n..). pub unsafe fn step_by(&mut self, n: usize) -> &mut Self { // SAFETY: same as step_by, safe as long n is less than the buffer length self.ptr = unsafe { self.ptr.add(n) }; self } } ... /// Parse the scientific notation component of a float. fn parse_scientific(s: &mut AsciiStr<'_>) -> i64 { let start = *s; // SAFETY: the first character is 'e'/'E' and scientific mode is enabled unsafe { s.step(); } ... } ``` This allows us to trivially demonstrate the new implementation of dec2flt is safe. **Inline Annotations Have Been Removed** In the previous implementation of dec2flt, inline annotations exist practically nowhere in the entire module. Therefore, these annotations have been removed, which mostly does not impact [performance](https://github.com/aldanor/fast-float-rust/issues/15#issuecomment-864485157). **Fixed Correctness Tests** Numerous compile errors in `src/etc/test-float-parse` were present, due to deprecation of `time.clock()`, as well as the crate dependencies with `rand`. The tests have therefore been reworked as a [crate](https://github.com/Alexhuszagh/rust/tree/master/src/etc/test-float-parse), and any errors in `runtests.py` have been patched. **Undefined Behavior** An implementation of `check_len` which relied on undefined behavior (in fast-float-rust) has been refactored, to ensure that the behavior is well-defined. The original code is as follows: ```rust #[inline] pub fn check_len(&self, n: usize) -> bool { unsafe { self.ptr.add(n) <= self.end } } ``` And the new implementation is as follows: ```rust /// Check if the slice at least `n` length. fn check_len(&self, n: usize) -> bool { n <= self.as_ref().len() } ``` Note that this has since been fixed in [fast-float-rust](https://github.com/aldanor/fast-float-rust/pull/29). **Inferring Binary Exponents** Rather than explicitly store binary exponents, this new implementation infers them from the decimal exponent, reducing the amount of static storage required. This removes the requirement to store [611 i16s](https://github.com/rust-lang/rust/blob/868c702d0c9a471a28fb55f0148eb1e3e8b1dcc5/library/core/src/num/dec2flt/table.rs#L8). # Code Size The code size, for all optimizations, does not considerably change relative to before for stripped builds, however it is **significantly** smaller prior to stripping the resulting binaries. These binary sizes were calculated on x86_64-unknown-linux-gnu. **new** Using rustc version 1.55.0-dev. opt-level|size|size(stripped) |:-:|:-:|:-:| 0|400k|300K 1|396k|292K 2|392k|292K 3|392k|296K s|396k|292K z|396k|292K **old** Using rustc version 1.53.0-nightly. opt-level|size|size(stripped) |:-:|:-:|:-:| 0|3.2M|304K 1|3.2M|292K 2|3.1M|284K 3|3.1M|284K s|3.1M|284K z|3.1M|284K # Correctness The dec2flt implementation passes all of Rust's unittests and comprehensive float parsing tests, along with numerous other tests such as Nigel Toa's comprehensive float [tests](https://github.com/nigeltao/parse-number-fxx-test-data) and Hrvoje Abraham [strtod_tests](https://github.com/ahrvoje/numerics/blob/master/strtod/strtod_tests.toml). Therefore, it is unlikely that this algorithm will incorrectly round parsed floats. # Issues Addressed This will fix and close the following issues: - resolves #85198 - resolves #85214 - resolves #85234 - fixes #31407 - fixes #31109 - fixes #53015 - resolves #68396 - closes https://github.com/aldanor/fast-float-rust/issues/15
2021-07-17Changed dec2flt to use the Eisel-Lemire algorithm.Alex Huszagh-2396/+2146
Implementation is based off fast-float-rust, with a few notable changes. - Some unsafe methods have been removed. - Safe methods with inherently unsafe functionality have been removed. - All unsafe functionality is documented and provably safe. - Extensive documentation has been added for simpler maintenance. - Inline annotations on internal routines has been removed. - Fixed Python errors in src/etc/test-float-parse/runtests.py. - Updated test-float-parse to be a library, to avoid missing rand dependency. - Added regression tests for #31109 and #31407 in core tests. - Added regression tests for #31109 and #31407 in ui tests. - Use the existing slice primitive to simplify shared dec2flt methods - Remove Miri ignores from dec2flt, due to faster parsing times. - resolves #85198 - resolves #85214 - resolves #85234 - fixes #31407 - fixes #31109 - fixes #53015 - resolves #68396 - closes https://github.com/aldanor/fast-float-rust/issues/15
2021-07-17Auto merge of #87195 - yaahc:move-assert_matches-again, r=oli-obkbors-4/+4
rename assert_matches module Fixes nightly breakage introduced in https://github.com/rust-lang/rust/pull/86947
2021-07-16i sweat to godJane Lusby-1/+1
2021-07-16pls this timeJane Lusby-2/+2
2021-07-16implement ConstSizeIntoIterator for &[T;N] in addition to [T;N]The8472-3/+52
Due to #20400 the corresponding TrustedLen impls need a helper trait instead of directly adding `Item = &[T;N]` bounds. Since TrustedLen is a public trait this in turn means the helper trait needs to be public. Since it's just a workaround for a compiler deficit it's marked hidden, unstable and unsafe.
2021-07-16Rollup merge of #87174 - inquisitivecrystal:array-map, r=kennytmGuillaume Gomez-3/+2
Stabilize `[T; N]::map()` This stabilizes the `[T; N]::map()` function, gated by the `array_map` feature. The FCP has [already completed.](https://github.com/rust-lang/rust/issues/75243#issuecomment-878448138) Closes #75243.
2021-07-16rename specializing trait to ConstSizeIntoIteratorThe8472-4/+4
2021-07-17Mark `Option::insert` as must_useoxalica-0/+1
2021-07-16rename assert_matches moduleJane Lusby-1/+1
2021-07-16fix typo in compile_fail doctestRalf Jung-1/+1
2021-07-16Rollup merge of #87138 - dhwthompson:fix-range-invariant, r=JohnTitorGuillaume Gomez-1/+1
Correct invariant documentation for `steps_between` Given that the previous example involves stepping forward from A to B, the equivalent example on this line would make most sense as stepping backward from B to A. I should probably add a caveat here that I’m fairly new to Rust, and this is my first contribution to this repo, so it’s very possible that I’ve misunderstood how this is supposed to work (either on a technical level or a social one). If this is the case, please do let me know.
2021-07-15Stabilize `[T; N]::map()`inquisitivecrystal-3/+2
2021-07-15Added diagnostic items to structs and traits for ClippyxFrednet-0/+5
2021-07-15Added diagnostic items to functions for ClippyxFrednet-0/+9
2021-07-15implement TrustedLen for Flatten/FlatMap if the U: IntoIterator == [T; N]The8472-1/+48
This only works if arrays are passed directly instead of array iterators because we need to be sure that they have not been advanced before Flatten does its size calculation.
2021-07-15Rollup merge of #87127 - poliorcetics:ptr-rotate-safety, r=scottmcmYuki Okushi-2/+54
Add safety comments in private core::slice::rotate::ptr_rotate function Helps with #66219. ```@rustbot``` label C-cleanup T-compiler T-libs
2021-07-15Rollup merge of #86947 - m-ou-se:assert-matches-to-submodule, r=yaahcYuki Okushi-6/+21
Move assert_matches to an inner module Fixes #82913
2021-07-14Auto merge of #86765 - cuviper:fuse-less-specialized, r=joshtriplettbors-188/+66
Make the specialized Fuse still deal with None Fixes #85863 by removing the assumption that we'll never see a cleared iterator in the `I: FusedIterator` specialization. Now all `Fuse` methods check for the possibility that `self.iter` is `None`, and the specialization only avoids _setting_ that to `None` in `&mut self` methods.
2021-07-14Correct invariant documentation for `steps_between`David Thompson-1/+1
Given that the previous example involves stepping forward from A to B, the equivalent example on this line would make most sense as stepping backward from B to A.
2021-07-14Rollup merge of #87027 - petrochenkov:builderhelp, r=oli-obkGuillaume Gomez-1/+2
expand: Support helper attributes for built-in derive macros This is needed for https://github.com/rust-lang/rust/pull/86735 (derive macro `Default` should have a helper attribute `default`). With this PR we can specify helper attributes for built-in derives using syntax `#[rustc_builtin_macro(MacroName, attributes(attr1, attr2, ...))]` which mirrors equivalent syntax for proc macros `#[proc_macro_derive(MacroName, attributes(attr1, attr2, ...))]`. Otherwise expansion infra was already ready for this. The attribute parsing code is shared between proc macro derives and built-in macros (`fn parse_macro_name_and_helper_attrs`).
2021-07-14Add safety comments in private core::slice::rotate::ptr_rotate functionAlexis Bourget-2/+54
2021-07-14DOC: Add missing arguments to hypothetical code for step_by()Matthias Geier-6/+7
2021-07-14Auto merge of #86211 - tlyu:option-result-overviews, r=joshtriplettbors-5/+583
create method overview docs for core::option and core::result The `Option` and `Result` types have large lists of methods. They each could use an overview page of methods grouped by category. These proposed overviews include "truth tables" for the underappreciated boolean operators/combinators of these types. The methods are already somewhat categorized in the source, but some logical groupings are broken up by the necessities of putting related methods in different `impl` blocks, for example. This is based on #86209, but those are small changes and unlikely to conflict.
2021-07-13expand: Support helper attributes for built-in derive macrosVadim Petrochenkov-1/+2
2021-07-13Rollup merge of #86344 - est31:maybe-uninit-extra, r=RalfJungYuki Okushi-15/+43
Split MaybeUninit::write into new feature gate and stabilize it This splits off the `MaybeUninit::write` function from the `maybe_uninit_extra` feature gate into a new `maybe_uninit_write` feature gate and stabilizes it. Earlier work to improve the documentation of the write function: #86220 Tracking issue: #63567
2021-07-12Use the write function in some more placesest31-6/+6
2021-07-10Fix tracking issue for `bool_to_option`Jacob Pratt-1/+1
2021-07-09Auto merge of #85828 - scottmcm:raw-eq, r=oli-obkbors-112/+181
Stop generating `alloca`s & `memcmp` for simple short array equality Example: ```rust pub fn demo(x: [u16; 6], y: [u16; 6]) -> bool { x == y } ``` Before: ```llvm define zeroext i1 `@_ZN10playground4demo17h48537f7eac23948fE(i96` %0, i96 %1) unnamed_addr #0 { start: %y = alloca [6 x i16], align 8 %x = alloca [6 x i16], align 8 %.0..sroa_cast = bitcast [6 x i16]* %x to i96* store i96 %0, i96* %.0..sroa_cast, align 8 %.0..sroa_cast3 = bitcast [6 x i16]* %y to i96* store i96 %1, i96* %.0..sroa_cast3, align 8 %_11.i.i.i = bitcast [6 x i16]* %x to i8* %_14.i.i.i = bitcast [6 x i16]* %y to i8* %bcmp.i.i.i = call i32 `@bcmp(i8*` nonnull dereferenceable(12) %_11.i.i.i, i8* nonnull dereferenceable(12) %_14.i.i.i, i64 12) #2, !alias.scope !2 %2 = icmp eq i32 %bcmp.i.i.i, 0 ret i1 %2 } ``` ```x86 playground::demo: # `@playground::demo` sub rsp, 32 mov qword ptr [rsp], rdi mov dword ptr [rsp + 8], esi mov qword ptr [rsp + 16], rdx mov dword ptr [rsp + 24], ecx xor rdi, rdx xor esi, ecx or rsi, rdi sete al add rsp, 32 ret ``` After: ```llvm define zeroext i1 `@_ZN4mini4demo17h7a8994aaa314c981E(i96` %0, i96 %1) unnamed_addr #0 { start: %2 = icmp eq i96 %0, %1 ret i1 %2 } ``` ```x86 _ZN4mini4demo17h7a8994aaa314c981E: xor rcx, r8 xor edx, r9d or rdx, rcx sete al ret ```
2021-07-09Auto merge of #86904 - m-ou-se:prelude-collision-check-trait, r=nikomatsakisbors-0/+1
Check FromIterator trait impl in prelude collision check. Fixes #86902.
2021-07-08PR feedbackScott McMurray-2/+6
- Add `:Sized` assertion in interpreter impl - Use `Scalar::from_bool` instead of `ScalarInt: From<bool>` - Remove unneeded comparison in intrinsic typeck - Make this UB to call with undef, not just return undef in that case
2021-07-08Stop generating `alloca`s+`memcmp` for simple array equalityScott McMurray-2/+67
2021-07-08Move the `PartialEq` and `Eq` impls for arrays to a separate fileScott McMurray-112/+112
2021-07-08Auto merge of #86930 - tspiteri:int_log10, r=kennytmbors-3/+144
special case for integer log10 Now that #80918 has been merged, this PR provides a faster version of `log10`. The PR also adds some tests for values close to all powers of 10.