about summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2024-06-09Rollup merge of #125253 - sunsided:feature/FRAC_1_SQRT_PI, r=Mark-Simulacrum许杰友 Jieyou Xu (Joe)-0/+23
Add `FRAC_1_SQRT_2PI` constant to f16/f32/f64/f128 This adds the `FRAC_1_SQRT_2PI` to the `f16`, `f32`, `f64` and `f128` as [`1/√(2π)`](https://www.wolframalpha.com/input?i=1%2Fsqrt%282*pi%29). The rationale is that while `FRAC_1_SQRT_PI` already exists, [Gaussian calculations](https://en.wikipedia.org/wiki/Gaussian_function) for random normal distributions require a `1/(σ√(2π))` term, which could then be directly expressed e.g. as `f32::FRAC_1_SQRT_2PI / sigma`. The actual value is approximately `1/√(2π) = 0.3989422804014326779399460599343818684758586311649346576659258296…`. Truncated/rounded forms were used for the individual types. --- ~~I did not any of the `#[unstable]` attributes since I am not aware of their implications.~~ **Edit:** I applied the stability attributes from the surrounding types according to what seemed most likely correct. I believe the `more_float_constants` feature marker is incorrectly applied, but I wasn't sure how to proceed.
2024-06-09fix `NonZero` doctest inconsistenciesivan-shrimp-10/+32
2024-06-08Rollup merge of #126138 - wbk:patch-1, r=lqdLeón Orell Valerian Liehr-1/+1
Fix typo in docs for std::pin
2024-06-08Rollup merge of #125951 - slanterns:error_in_core_stabilization, r=AmanieuLeón Orell Valerian Liehr-13/+3
Stabilize `error_in_core` Closes: https://github.com/rust-lang/rust/issues/103765. `@rustbot` label: +T-libs-api r? libs-api
2024-06-07Fix typo in docs for std::pinWalter Kalata-1/+1
2024-06-07Rollup merge of #126089 - wutchzone:option_take_if, r=scottmcmMatthias Krüger-3/+1
Stabilize Option::take_if Closes #98934 ed: FCP complete in https://github.com/rust-lang/rust/issues/98934#issuecomment-2104627082
2024-06-06Rollup merge of #125606 - diondokter:opt-size-int-fmt, r=cuviperJubilee-0/+33
Size optimize int formatting Let's use the new feature flag! This uses a simpler algorithm to format integers. It is slower, but also smaller. It also saves having to import the 200 byte rodata lookup table. In a test of mine this saves ~300 bytes total of a cortex-m binary that does integer formatting. For a 16KB device, that's almost 2%. Note though that for opt-level 3 the text size actually grows by 116 bytes. Still a win in total. I'm not sure why the generated code is bigger than the more fancy algo. Maybe the smaller algo lends itself more to inlining and duplicating?
2024-06-07fix doc comments about `error_generic_member_access`Slanterns-2/+2
2024-06-07Stabilize `error_in_core`Slanterns-11/+1
2024-06-06Rollup merge of #126096 - c410-f3r:tests-tests-tests, r=jhprattJubilee-1/+6
[RFC-2011] Allow `core_intrinsics` when activated Fix #120612
2024-06-06[RFC-2011] Allow `core_intrinsics` when activatedCaio-1/+6
2024-06-06Stabilize Option::take_ifDaniel Sedlak-3/+1
2024-06-06less garbage, more examplesRalf Jung-8/+76
2024-06-05Rollup merge of #125995 - kpreid:const-uninit-stable, r=NilstriebJubilee-12/+5
Use inline const blocks to create arrays of `MaybeUninit`. This PR contains 2 changes enabled by the fact that [`inline_const` is now stable](https://github.com/rust-lang/rust/pull/104087), and was split out of #125082. 1. Use inline const instead of `unsafe` to construct arrays in `MaybeUninit` examples. Rationale: Demonstrate good practice of avoiding `unsafe` code where it is not strictly necessary. 4. Use inline const instead of `unsafe` to implement `MaybeUninit::uninit_array()`. This is arguably giving the compiler more work to do, in exchange for eliminating just one single internal unsafe block, so it's less certain that this is good on net. r​? `@Nilstrieb`
2024-06-05Rollup merge of #123168 - joshtriplett:size-of-prelude, r=AmanieuJubilee-7/+5
Add `size_of` and `size_of_val` and `align_of` and `align_of_val` to the prelude (Note: need to update the PR to add `align_of` and `align_of_val`, and remove the second commit with the myriad changes to appease the lint.) Many, many projects use `size_of` to get the size of a type. However, it's also often equally easy to hardcode a size (e.g. `8` instead of `size_of::<u64>()`). Minimizing friction in the use of `size_of` helps ensure that people use it and make code more self-documenting. The name `size_of` is unambiguous: the name alone, without any prefix or path, is self-explanatory and unmistakeable for any other functionality. Adding it to the prelude cannot produce any name conflicts, as any local definition will silently shadow the one from the prelude. Thus, we don't need to wait for a new edition prelude to add it.
2024-06-04Use inline const instead of unsafe to implement `MaybeUninit::uninit_array()`.Kevin Reid-2/+1
2024-06-04Use inline const instead of unsafe to construct arrays in `MaybeUninit` ↵Kevin Reid-10/+4
examples.
2024-06-04Rollup merge of #125696 - workingjubilee:please-dont-say-you-are-lazy, ↵Guillaume Gomez-0/+15
r=Nilstrieb Explain differences between `{Once,Lazy}{Cell,Lock}` types The question of "which once-ish cell-ish type should I use?" has been raised multiple times, and is especially important now that we have stabilized the `LazyCell` and `LazyLock` types. The answer for the `Lazy*` types is that you would be better off using them if you want to use what is by far the most common pattern: initialize it with a single nullary function that you would call at every `get_or_init` site. For everything else there's the `Once*` types. "For everything else" is a somewhat weak motivation, as it only describes by negation. While contrasting them is inevitable, I feel positive motivations are more understandable. For this, I now offer a distinct example that helps explain why `OnceLock` can be useful, despite `LazyLock` existing: you can do some cool stuff with it that `LazyLock` simply can't support due to its mere definition. The pair of `std::sync::*Lock`s are usable inside a `static`, and can serve roles in async or multithreaded (or asynchronously multithreaded) programs that `*Cell`s cannot. Because of this, they received most of my attention. Fixes #124696 Fixes #125615
2024-06-04Rollup merge of #106186 - rossmacarthur:ft/iter-chain, r=AmanieuGuillaume Gomez-2/+40
Add function `core::iter::chain` The addition of `core::iter::zip` (#82917) set a precedent for adding plain functions for iterator adaptors. Adding `chain` makes it a little easier to `chain` two iterators. ```rust for (x, y) in chain(xs, ys) {} // vs. for (x, y) in xs.into_iter().chain(ys) {} ``` There is prior art for the utility of this in [`itertools::chain`](https://docs.rs/itertools/latest/itertools/fn.chain.html). Approved ACP https://github.com/rust-lang/libs-team/issues/154
2024-06-04Add function `core::iter::chain`Ross MacArthur-2/+40
The addition of `core::iter::zip` (#82917) set a precedent for adding plain functions for iterator adaptors. Adding `chain` makes it a little easier to `chain` two iterators. ``` for (x, y) in chain(xs, ys) {} // vs. for (x, y) in xs.into_iter().chain(ys) {} ```
2024-06-04Rollup merge of #125504 - mqudsi:once_nominal, r=cuviper许杰友 Jieyou Xu (Joe)-2/+2
Change pedantically incorrect OnceCell/OnceLock wording While the semantic intent of a OnceCell/OnceLock is that it can only be written to once (upon init), the fact of the matter is that both these types offer a `take(&mut self) -> Option<T>` mechanism that, when successful, resets the cell to its initial state, thereby [technically allowing it to be written to again](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=415c023a6ae1ef35f371a2d3bb1aa735) Despite the fact that this can only happen with a mutable reference (generally only used during the construction of the OnceCell/OnceLock), it would be incorrect to say that the type itself as a whole *categorically* prevents being initialized or written to more than once (since it is possible to imagine an identical type only without the `take()` method that actually fulfills that contract). To clarify, change "that cannot be.." to "that nominally cannot.." and add a note to OnceCell about what can be done with an `&mut Self` reference. ```@rustbot``` label +A-rustdocs
2024-06-04more explicitly state the basic rules of working with the obtained raw pointersRalf Jung-0/+12
2024-06-03Auto merge of #125912 - nnethercote:rustfmt-tests-mir-opt, r=oli-obkbors-26/+32
rustfmt `tests/mir-opt` Continuing the work started in #125759. Details in individual commit log messages. r? `@oli-obk`
2024-06-02Explain LazyCell in core::cell overviewJubilee Young-0/+15
2024-06-03Reformat `mir!` macro invocations to use braces.Nicholas Nethercote-26/+32
The `mir!` macro has multiple parts: - An optional return type annotation. - A sequence of zero or more local declarations. - A mandatory starting anonymous basic block, which is brace-delimited. - A sequence of zero of more additional named basic blocks. Some `mir!` invocations use braces with a "block" style, like so: ``` mir! { let _unit: (); { let non_copy = S(42); let ptr = std::ptr::addr_of_mut!(non_copy); // Inside `callee`, the first argument and `*ptr` are basically // aliasing places! Call(_unit = callee(Move(*ptr), ptr), ReturnTo(after_call), UnwindContinue()) } after_call = { Return() } } ``` Some invocations use parens with a "block" style, like so: ``` mir!( let x: [i32; 2]; let one: i32; { x = [42, 43]; one = 1; x = [one, 2]; RET = Move(x); Return() } ) ``` And some invocations uses parens with a "tighter" style, like so: ``` mir!({ SetDiscriminant(*b, 0); Return() }) ``` This last style is generally used for cases where just the mandatory starting basic block is present. Its braces are placed next to the parens. This commit changes all `mir!` invocations to use braces with a "block" style. Why? - Consistency is good. - The contents of the invocation is a block of code, so it's odd to use parens. They are more normally used for function-like macros. - Most importantly, the next commit will enable rustfmt for `tests/mir-opt/`. rustfmt is more aggressive about formatting macros that use parens than macros that use braces. Without this commit's changes, rustfmt would break a couple of `mir!` macro invocations that use braces within `tests/mir-opt` by inserting an extraneous comma. E.g.: ``` mir!(type RET = (i32, bool);, { // extraneous comma after ';' RET.0 = 1; RET.1 = true; Return() }) ``` Switching those `mir!` invocations to use braces avoids that problem, resulting in this, which is nicer to read as well as being valid syntax: ``` mir! { type RET = (i32, bool); { RET.0 = 1; RET.1 = true; Return() } } ```
2024-06-02Rollup merge of #125898 - RalfJung:typo, r=NilstriebJubilee-1/+1
typo: depending from -> on
2024-06-02Rollup merge of #125884 - Rua:integer_sign_cast, r=Mark-SimulacrumJubilee-0/+48
Implement feature `integer_sign_cast` Tracking issue: https://github.com/rust-lang/rust/issues/125882 Since this is my first time making a library addition I wasn't sure where to place the new code relative to existing code. I decided to place it near the top where there are already some other basic bitwise manipulation functions. If there is an official guideline for the ordering of functions, please let me know.
2024-06-02Rollup merge of #121062 - RustyYato:f32-midpoint, r=the8472Jubilee-19/+36
Change f32::midpoint to upcast to f64 This has been verified by kani as a correct optimization see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398 The new implementation is branchless and only differs in which NaN values are produced (if any are produced at all), which is fine to change. Aside from NaN handling, this implementation produces bitwise identical results to the original implementation. Question: do we need a codegen test for this? I didn't add one, since the original PR #92048 didn't have any codegen tests.
2024-06-02Wording of the documentationRua-4/+4
2024-06-02typo: depending from -> onRalf Jung-1/+1
2024-06-02from_ref, from_mut: clarify domain of quantificationRalf Jung-4/+4
2024-06-02Implement feature `integer_sign_cast`Rua-0/+48
2024-06-01Change f32::midpoint to upcast to f64RustyYato-19/+36
This has been verified by kani as a correct optimization see: https://github.com/rust-lang/rust/issues/110840#issuecomment-1942587398 The new implementation is branchless, and only differs in which NaN values are produced (if any are produced at all). Which is fine to change. Aside from NaN handling, this implementation produces bitwise identical results to the original implementation. The new implementation is gated on targets that have a fast 64-bit floating point implementation in hardware, and on WASM.
2024-06-02Auto merge of #124294 - tspiteri:ilog-first-iter, r=the8472bors-2/+5
Unroll first iteration of checked_ilog loop This follows the optimization of #115913. As shown in https://github.com/rust-lang/rust/pull/115913#issuecomment-2066788006, the performance was improved in all important cases, but some regressions were introduced for the benchmarks `u32_log_random_small`, `u8_log_random` and `u8_log_random_small`. Basically, #115913 changed the implementation from one division per iteration to one multiplication per iteration plus one division. When there are zero iterations, this is a regression from zero divisions to one division. This PR avoids this by avoiding the division if we need zero iterations by returning `Some(0)` early. It also reduces the number of multiplications by one in all other cases.
2024-05-31Auto merge of #124662 - zetanumbers:needs_async_drop, r=oli-obkbors-0/+13
Implement `needs_async_drop` in rustc and optimize async drop glue This PR expands on #121801 and implements `Ty::needs_async_drop` which works almost exactly the same as `Ty::needs_drop`, which is needed for #123948. Also made compiler's async drop code to look more like compiler's regular drop code, which enabled me to write an optimization where types which do not use `AsyncDrop` can simply forward async drop glue to `drop_in_place`. This made size of the async block from the [async_drop test](https://github.com/zetanumbers/rust/blob/67980dd6fb11917d23d01a19c2cf4cfc3978aac8/tests/ui/async-await/async-drop.rs) to decrease by 12%.
2024-05-30Rollup merge of #125746 - jmillikin:duration-from-weeks-typo, r=lqdMatthias Krüger-1/+1
Fix copy-paste error in `Duration::from_weeks` panic message.
2024-05-30Rollup merge of #125739 - RalfJung:drop-in-place-docs, r=workingjubileeMatthias Krüger-1/+6
drop_in_place: weaken the claim of equivalence with drop(ptr.read()) The two are *not* semantically equivalent in all cases, so let's not be so definite about this. Fixes https://github.com/rust-lang/rust/issues/112015
2024-05-30explain what the open questions are, and add a Miri test for thatRalf Jung-0/+5
2024-05-30Fix copy-paste error in `Duration::from_weeks` panic message.John Millikin-1/+1
2024-05-30Rollup merge of #125733 - compiler-errors:async-fn-assoc-item, r=fmeaseLeón Orell Valerian Liehr-1/+5
Add lang items for `AsyncFn*`, `Future`, `AsyncFnKindHelper`'s associated types Adds lang items for `AsyncFnOnce::Output`, `AsyncFnOnce::CallOnceFuture`, `AsyncFnMut::CallRefFuture`, and uses them in the new solver. I'm mostly interested in doing this to help accelerate uplifting the new trait solver into a separate crate. The old solver is kind of spaghetti, so I haven't moved that to use these lang items (i.e. it still uses `item_name`-based comparisons). update: Also adds lang items for `Future::Output` and `AsyncFnKindHelper::Upvars`. cc ``@lcnr``
2024-05-29drop_in_place: weaken the claim of equivalence with drop(ptr.read())Ralf Jung-1/+1
2024-05-29Add lang item for AsyncFnKindHelper::UpvarsMichael Goulet-0/+1
2024-05-29Add lang item for Future::OutputMichael Goulet-1/+1
2024-05-29Add lang items for AsyncFn's associated typesMichael Goulet-0/+3
2024-05-29[ACP 362] genericize `ptr::from_raw_parts`Scott McMurray-8/+8
2024-05-29Add FRAC_1_SQRT_2PI doc alias to FRAC_1_SQRT_TAUMarkus Mayer-0/+4
This is create symmetry between the already existing TAU constant (2pi) and the newly-introduced FRAC_1_SQRT_2PI, keeping the more common name while increasing visibility.
2024-05-29make `ptr::rotate` smaller when using `optimize_for_size`Folkert-2/+6
code to reproduce https://github.com/folkertdev/optimize_for_size-slice-rotate In the example the size of `.text` goes down from 1624 to 276 bytes.
2024-05-29Add safety comment to fix tidyDaria Sukhonina-0/+2
2024-05-29Optimize async drop glue for some old typesDaria Sukhonina-0/+11
2024-05-29Add FRAC_1_SQRT_2PI constant to f16/f32/f64/f128Markus Mayer-0/+19