about summary refs log tree commit diff
path: root/library/core/src/num
AgeCommit message (Collapse)AuthorLines
2025-09-29Rollup merge of #146979 - npmccallum:nanosecs, r=Mark-SimulacrumStuart Cook-1/+2
constify Default on Nanoseconds
2025-09-27Rollup merge of #147076 - joshuarayton:more-float-constants-issue, r=tgross35Matthias Krüger-24/+24
update issue number for more_float_constants Update issue number from https://github.com/rust-lang/rust/issues/103883 to https://github.com/rust-lang/rust/issues/146939 r? ``@tgross35``
2025-09-26Update CURRENT_RUSTC_VERSION post-bumpMark Rousskov-60/+60
2025-09-26update issue number for more_float_constantsJoshua Rayton-24/+24
2025-09-25Auto merge of #147037 - matthiaskrgr:rollup-xtgqzuu, r=matthiaskrgrbors-0/+12
Rollup of 8 pull requests Successful merges: - rust-lang/rust#116882 (rustdoc: hide `#[repr]` if it isn't part of the public ABI) - rust-lang/rust#135771 ([rustdoc] Add support for associated items in "jump to def" feature) - rust-lang/rust#141032 (avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`) - rust-lang/rust#142401 (Add proper name mangling for pattern types) - rust-lang/rust#146293 (feat: non-panicking `Vec::try_remove`) - rust-lang/rust#146859 (BTreeMap: Don't leak allocators when initializing nodes) - rust-lang/rust#146924 (Add doc for `NonZero*` const creation) - rust-lang/rust#146933 (Make `render_example_with_highlighting` return an `impl fmt::Display`) r? `@ghost` `@rustbot` modify labels: rollup
2025-09-25Rollup merge of #146924 - cptpiepmatz:doc-nonzero-const-creation, r=joboetMatthias Krüger-0/+12
Add doc for `NonZero*` const creation I ran into trouble using `NonZero*` values because I didn’t see any clear way to create them at compile time. At first I ended up using `NonZero*::new_unchecked` a lot, until I realized that `Option::unwrap` and `Option::expect` are `const` and can be used in a `const` context. With that, you can create non-zero values at compile time safely, without touching `unsafe`. This wasn’t obvious to me and my peers who’ve been using Rust for a while, so I thought adding a note to the docs would make it easier for others to discover. If this should be worded differently or placed in another location, we can do that. I just want to make this more obvious.
2025-09-25add doc for `NonZero*` const creationTim 'Piepmatz' Hesse-0/+12
2025-09-25Rollup merge of #146735 - Qelxiros:const_mul_add, r=tgross35,RalfJungStuart Cook-4/+8
unstably constify float mul_add methods Tracking issue: rust-lang/rust#146724 r? `@tgross35`
2025-09-24unstably constify float mul_add methodsJeremy Smart-4/+8
Co-authored-by: Ralf Jung <post@ralfj.de>
2025-09-24Rollup merge of #146915 - clarfonthey:safe-intrinsics-2, r=RalfJungMatthias Krüger-12/+6
Make missed precondition-free float intrinsics safe So, in my defence, these were both separated out from the other intrinsics in the file *and* had a different safety comment in the stable versions, so, I didn't notice them before. But, in my offence, the entire reason I did the previous PR was because I was using them for SIMD intrinsic fallbacks, and `fabs` is needed for those too, so, I don't really have an excuse. Extra follow-up to rust-lang/rust#146683. r? ```@RalfJung``` who reviewed the previous one These don't appear to be used anywhere outside of the standard locations, at least.
2025-09-24constify Default on NanosecondsNathaniel McCallum-1/+2
2025-09-23Make missed precondition-free float intrinsics safeltdk-12/+6
2025-09-23Rollup merge of #146818 - npmccallum:total_cmp, r=fee1-deadMatthias Krüger-4/+8
constify {float}::total_cmp()
2025-09-23Auto merge of #146317 - saethlin:panic=immediate-abort, r=nnethercotebors-2/+2
Add panic=immediate-abort MCP: https://github.com/rust-lang/compiler-team/issues/909 This adds a new panic strategy, `-Cpanic=immediate-abort`. This panic strategy essentially just codifies use of `-Zbuild-std-features=panic_immediate_abort`. This PR is intended to just set up infrastructure, and while it will change how the compiler is invoked for users of the feature, there should be no other impacts. In many parts of the compiler, `PanicStrategy::ImmediateAbort` behaves just like `PanicStrategy::Abort`, because actually most parts of the compiler just mean to ask "can this unwind?" so I've added a helper function so we can say `sess.panic_strategy().unwinds()`. The panic and unwind strategies have some level of compatibility, which mostly means that we can pre-compile the sysroot with unwinding panics then the sysroot can be linked with aborting panics later. The immediate-abort strategy is all-or-nothing, enforced by `compiler/rustc_metadata/src/dependency_format.rs` and this is tested for in `tests/ui/panic-runtime/`. We could _technically_ be more compatible with the other panic strategies, but immediately-aborting panics primarily exist for users who want to eliminate all the code size responsible for the panic runtime. I'm open to other use cases if people want to present them, but not right now. This PR is already large. `-Cpanic=immediate-abort` sets both `cfg(panic = "immediate-abort")` _and_ `cfg(panic = "abort")`. bjorn3 pointed out that people may be checking for the abort cfg to ask if panics will unwind, and also the sysroot feature this is replacing used to require `-Cpanic=abort` so this seems like a good back-compat step. At least for the moment. Unclear if this is a good idea indefinitely. I can imagine this being confusing. The changes to the standard library attributes are purely mechanical. Apart from that, I removed an `unsafe` we haven't needed for a while since the `abort` intrinsic became safe, and I've added a helpful diagnostic for people trying to use the old feature. To test that `-Cpanic=immediate-abort` conflicts with other panic strategies, I've beefed up the core-stubs infrastructure a bit. There is now a separate attribute to set flags on it. I've added a test that this produces the desired codegen, called `tests/run-make-cargo/panic-immediate-abort-codegen/` and also a separate run-make-cargo test that checks that we can build a binary.
2025-09-22Auto merge of #146683 - clarfonthey:safe-intrinsics, r=RalfJung,Amanieubors-56/+28
Mark float intrinsics with no preconditions as safe Note: for ease of reviewing, the list of safe intrinsics is sorted in the first commit, and then safe intrinsics are added in the second commit. All *recently added* float intrinsics have been correctly marked as safe to call due to the fact that they have no preconditions. This adds the remaining float intrinsics which are safe to call to the safe intrinsic list, and removes the unsafe blocks around their calls. --- Side note: this may want a try run before being added to the queue, since I'm not sure if there's any tier-2 code that uses these intrinsics that might not be tested on the usual PR flow. We've already uncovered a few places in subtrees that do this, and it's worth double-checking before clogging up the queue.
2025-09-22constify {float}::total_cmp()Nathaniel McCallum-4/+8
2025-09-22assert_unsafe_precondition: fix some incorrect check_language_ubRalf Jung-5/+5
2025-09-21Mark float intrinsics with no preconditions as safeltdk-56/+28
2025-09-21Change the cfg to a dashBen Kimock-2/+2
2025-09-21Add panic=immediate-abortBen Kimock-2/+2
2025-09-15Rollup merge of #146284 - Kivooeo:blazing-fast-division-bignum, ↵Matthias Krüger-37/+0
r=Mark-Simulacrum Remove `div_rem` from `core::num::bignum` This fixes very old fixme that sounds like this ``` Stupid slow base-2 long division taken from https://en.wikipedia.org/wiki/Division_algorithm FIXME use a greater base ($ty) for the long division. ``` By deleting this method since it was never used
2025-09-12Constify Eq, Ord, PartialOrdEvgenii Zheltonozhskii-6/+11
2025-09-08simplify the declaration of the legacy integer modules (`std::u32` etc.)cyrgani-178/+71
2025-09-07remove unsused div_rem method from bignumKivooeo-37/+0
2025-09-07Auto merge of #146216 - ↵bors-3/+3
LorrensP-2158466:miri-float-nondet-foreign-items-take2, r=RalfJung Miri: non-deterministic floating point operations in foreign_items Take 2 of rust-lang/rust#143906. The last 2 commits are what changed compared to the original pr. Verified the tests using (fish shell): ```fish env MIRIFLAGS="-Zmiri-max-extra-rounding-error -Zmiri-many-seeds" ./x miri --no-fail-fast std core coretests -- f32 f64 ``` r? `@RalfJung`
2025-09-06Change stdlib float tests to account for miri nondet floats.LorrensP-2158466-3/+3
2025-09-05Rollup merge of #146225 - Jules-Bertholet:simplify-float-midpoint, r=tgross35León Orell Valerian Liehr-32/+0
Simplify `{f16, f32, f64, f128}::midpoint()` `(float_ty::MAX / 2) - (float_ty::MIN_POSITIVE * 2)` equals `(float_ty::MAX / 2) + (float_ty::MIN_POSITIVE * 2)` equals `(float_ty::MAX / 2)`. So these branches are pointless. CC `@Urgau` who wrote the original implementation in https://github.com/rust-lang/rust/pull/92048; does this seem right? `@rustbot` label A-floating-point
2025-09-05Simplify `{f16, f32, f54, f128}::midpoint()`Jules Bertholet-32/+0
`(float_ty::MAX / 2) - (float_ty::MIN_POSITIVE * 2)` equals `(float_ty::MAX / 2) + (float_ty::MIN_POSITIVE * 2)` equals `(float_ty::MAX / 2)`. So these branches are pointless
2025-09-05Rollup merge of #144342 - Qelxiros:exact-bitshifts, r=tgross35Trevor Gross-0/+231
add exact bitshifts Tracking issue: rust-lang/rust#144336 cc ```@lolbinarycat```
2025-09-04Rollup merge of #145690 - sayantn:integer-funnel-shift, r=tgross35Jacob Pratt-0/+97
Implement Integer funnel shifts Tracking issue: rust-lang/rust#145686 ACP: https://github.com/rust-lang/libs-team/issues/642 This implements funnel shifts on primitive integer types. Implements this for cg_llvm, with a fallback impl for everything else Thanks `@folkertdev` for the fixes and tests cc `@rust-lang/libs-api`
2025-09-04Rollup merge of #146136 - ↵Stuart Cook-2/+2
AudaciousAxiom:docs/missing-closing-code-block-fences, r=tgross35 docs(std): add missing closing code block fences in doc comments This PR adds a few closing code block fences which I believe are missing in some doc comments. It seems that rustdoc just autocloses code blocks at the end of doc comments and thus these were easily overlooked: I do not think these code blocks are special in any way. I found these when working on a Clippy lint that checks the last sentence of doc comments for terminal punctuation, and these were failing cases when testing against the std. Therefore I am not entirely sure these are all such cases, but still have high hopes that they are (or at least a well-defined subset of them).
2025-09-03Rollup merge of #145279 - clarfonthey:const-convert-initial, r=tgross35Stuart Cook-4/+4
Constify conversion traits (part 1) This is the first part of rust-lang/rust#144289 being split into smaller pieces. It adds/moves constness of several traits under the `const_convert` feature: * `From` * `Into` * `TryFrom` * `TryInto` * `FromStr` * `AsRef` * `AsMut` * `Borrow` * `BorrowMut` * `Deref` * `DerefMut` There are a few methods that are intrinsically tied to these traits which I've included in the feature. Particularly, those which are wrappers over `AsRef`: * `ByteStr::new` (unstable under `bstr` feature) * `OsStr::new` * `Path::new` Those which directly use `Into`: * `Result::into_ok` * `Result::into_err` And those which use `Deref` and `DerefMut`: * `Pin::as_ref` * `Pin::as_mut` * `Pin::as_deref_mut` * `Option::as_deref` * `Option::as_deref_mut` * `Result::as_deref` * `Result::as_deref_mut` (note: the `Option` and `Result` methods were suggested by ``@npmccallum`` initially as rust-lang/rust#146101) The parts which are missing from this PR are: * Anything that involves heap-allocated types * Making any method const than the ones listed above * Anything that could rely on the above, *or* could rely on system-specific code for `OsStr` or `Path` (note: this mostly makes these methods useless since `str` doesn't implement `AsRef<OsStr>` yet, but it's better to track the method for now and add impls later, IMHO) r? ``@tgross35`` (who mostly already reviewed this)
2025-09-03Add `funnel_sh{l,r}` functions and intrinsicssayantn-0/+97
- Add a fallback implementation for the intrinsics - Add LLVM backend support for funnel shifts Co-Authored-By: folkertdev <folkert@folkertdev.nl>
2025-09-02add exact bitshiftsJeremy Smart-0/+231
2025-09-02docs(std): add missing closing code block fences in doc commentsAudaciousAxiom-2/+2
2025-09-01Constify conversion traitsltdk-4/+4
2025-08-30Rollup merge of #145776 - ChaiTRex:ilog_specialization, r=joboetStuart Cook-0/+14
Optimize `.ilog({2,10})` to `.ilog{2,10}()` Optimize `.ilog({2,10})` to `.ilog{2,10}()` Inform compiler of optimizations when the base is known at compile time and there's a cheaper method available: * `{integer}.checked_ilog(2)` -> `{integer}.checked_ilog2()` * `{integer}.checked_ilog(10)` -> `{integer}.checked_ilog10()` * `{integer}.ilog(2)` -> `{integer}.ilog2()` * `{integer}.ilog(10)` -> `{integer}.ilog10()`
2025-08-30Auto merge of #144494 - scottmcm:min_bigint_helpers, r=Mark-Simulacrumbors-24/+42
Partial-stabilize the basics from `bigint_helper_methods` Direct link to p-FCP comment: https://github.com/rust-lang/rust/pull/144494#issuecomment-3133172161 After libs-api discussion, this is now the following methods: - [`uN::carrying_add`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.carrying_add): uN + uN + bool -> (uN, bool) - [`uN::borrowing_sub`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.borrowing_sub): uN + uN + bool -> (uN, bool) - [`uN::carrying_mul`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.carrying_mul): uN * uN + uN -> (uN, uN) - [`uN::carrying_mul_add`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.carrying_mul_add): uN * uN + uN + uN -> (uN, uN) Specifically, these are the ones that are specifically about working with `uN` as a "digit" (or "limb") where the output, despite being larger than can fit in a single digit, wants to be phrased in terms of those *digits*, not in terms of a wider type. (This leaves open the possibility of things like `widening_mul: u32 * u32 -> u64` for places where one wants to only think in terms of the *number*s, rather than as carries between multiple digits. Though of course discussions about how best to phrase such a thing are best for the tracking issue, not for this PR.) --- **Original PR description**: A [conversation on IRLO](https://internals.rust-lang.org/t/methods-for-splitting-integers-into-their-halves/23210/7?u=scottmcm) the other day pushed me to write this up 🙂 This PR proposes a partial stabilization of `bigint_helper_methods` (rust-lang/rust#85532), focusing on a basic set that hopefully can be non-controversial. Specifically: - [`uN::carrying_add`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.carrying_add): uN + uN + bool -> (uN, bool) - [`uN::widening_mul`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.widening_mul): uN * uN -> (uN, uN) - [`uN::carrying_mul_add`](https://doc.rust-lang.org/nightly/std/primitive.u64.html#method.carrying_mul_add): uN * uN + uN + uN -> (uN, uN) Why these? - We should let people write Rust without needing to be backend experts to know what the magic incantation is to do this. Even `carrying_add`, which doesn't seem that complicated, actually broke in 1.82 (see rust-lang/rust#133674) so we should just offer something fit-for-purpose rather than making people keep up with whatever the secret sauce is today. We also get to do things that users cannot, like have the LLVM version emit operations on `i256` in the implementation of `u128::carrying_mul_add` (https://rust.godbolt.org/z/cjG7eKcxd). - Unsigned only because the behaviour is much clearer than when signed is involved, as everything is just unsigned (vs questions like whether `iN * iN` should give `(uN, iN)`) and carries can only happen in one direction (vs questions about whether the carry from `-128_u8 + -128_u8` should be considered `-1`). - `carrying_add` is the core [full adder](https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder) primitive for implementing addition. - `carrying_mul_add` is the core primitive for [grade school](https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication) multiplication (see the example in its docs for why both carries are needed). - `widening_mul` even though it's not strictly needed (its implementation is just `carrying_mul_add(a, b, 0, 0)` right now) as the simplest way for users to get to [cranelift's `umulhi`](https://docs.rs/cranelift/latest/cranelift/prelude/trait.InstBuilder.html#method.umulhi), RISC-V's `MULHU`, Arm's `UMULL`, etc. (For example, I added an ISLE pattern https://github.com/bytecodealliance/wasmtime/commit/d12e4237de867d58d8c3451d77ee7547e9492550#diff-2041f67049d5ac3d8f62ea91d3cb45cdb8608d5f5cdab988731ae2addf90ef01 so Cranelift can notice what's happening from the fallback, even if the intrinsics aren't overridden specifically. And on x86 this is one of the simplest possible non-trivial functions <https://rust.godbolt.org/z/4oadWKTc1> because `MUL` puts the results in exactly the registers that the scalar pair result happens to want.) (I did not const-stabilize them in this PR because [the fallbacks](https://github.com/rust-lang/rust/blob/master/library/core/src/intrinsics/fallback.rs) are using `#[const_trait]` plus there's two [new intrinsic](https://doc.rust-lang.org/nightly/std/intrinsics/fn.disjoint_bitor.html)s involved, so I didn't want to *also* open those cans of worms here. Given that both intrinsics *have* fallbacks, and thus don't do anything that can't already be expressed in existing Rust, const-stabilizing these should be straight-forward once the underlying machinery is allowed on stable. But that doesn't need to keep these from being usable at runtime in the mean time.)
2025-08-29Optimize `.ilog({2,10})` to `.ilog{2,10}()`Chai T. Rex-0/+14
Inform compiler of optimizations when the base is known at compile time and there's a cheaper method available: * `{integer}.checked_ilog(2)` -> `{integer}.checked_ilog2()` * `{integer}.checked_ilog(10)` -> `{integer}.checked_ilog10()` * `{integer}.ilog(2)` -> `{integer}.ilog2()` * `{integer}.ilog(10)` -> `{integer}.ilog10()`
2025-08-27Rollup merge of #145625 - karolzwolak:f16-use-expr-instead-literal, ↵Matthias Krüger-10/+79
r=beetrees,tgross35 improve float to_degrees/to_radians rounding comments and impl This PR makes `to_degrees()` and `to_radians()` float functions more consistent between each other and improves comments around their precision and rounding. * revise comments explaining why we are using literal or expression * add unspecified precision comments as we don't guarantee precision * use expression in `f128::to_degrees()` * make `f64::to_degrees()` impl consistent with other functions r? `@tgross35`
2025-08-27Rollup merge of #145335 - clarfonthey:wtf8-core-alloc, r=Mark-SimulacrumMatthias Krüger-0/+15
Move WTF-8 code from std into core and alloc This is basically a small portion of rust-lang/rust#129411 with a smaller scope. It *does not*\* affect any public APIs; this code is still internal to the standard library. It just moves the WTF-8 code into `core` and `alloc` so it can be accessed by `no_std` crates like `backtrace`. > \* The only public API this affects is by adding a `Debug` implementation to `std::os::windows::ffi::EncodeWide`, which was not present before. This is due to the fact that `core` requires `Debug` implementations for all types, but `std` does not (yet) require this. Even though this was ultimately changed to be a wrapper over the original type, not a re-export, I decided to keep the `Debug` implementation so it remains useful. Like we do with ordinary strings, the tests are still located entirely in `alloc`, rather than splitting them into `core` and `alloc`. ---- Reviewer note: for ease of review, this is split into three commits: 1. Moving the original files into their new "locations" 2. Actually modifying the code to compile. 3. Removing aesthetic changes that were made so that the diff for commit 2 was readable. You can review commits 1 and 3 to verify these claims, but commit 2 contains the majority of the changes you should care about. ---- API changes: `impl Debug for std::os::windows::ffi::EncodeWide`
2025-08-26remove deprecated Error::description in implsMarijn Schouten-29/+13
2025-08-22improve float to_degrees/to_radians rounding comments and implKarol Zwolak-10/+79
* revise comments explaining why we are using literal or expression * add unspecified precision comments as we don't guarantee precision * use expression in `f128::to_degrees()` * make `f64::to_degrees()` impl consistent with other functions
2025-08-20Move WTF-8 code from std to core/allocltdk-0/+15
2025-08-20Partial-stabilize the basics from `bigint_helper_methods`Scott McMurray-24/+42
2025-08-20Rollup merge of #145381 - Gnurou:int_lowest_highest_one, r=jhprattJacob Pratt-0/+138
Implement feature `int_lowest_highest_one` for integer and NonZero types Tracking issue: rust-lang/rust#145203 Implement the accepted ACP rust-lang/rust#145203 for methods that find the index of the least significant (lowest) and most significant (highest) set bit in an integer for signed, unsigned, and NonZero types. Also add unit tests for all these types.
2025-08-19Rollup merge of #145255 - lune-climate:dec2flt-doc, r=ibraheemdev许杰友 Jieyou Xu (Joe)-0/+2
dec2flt: Provide more valid inputs examples I was just looking at the specifics of how the parsing is handled here and I wasn't sure if the examples were incomplete or the grammar below was misleading. The grammar was correct so I figured I'd add these examples to clarify.
2025-08-19Rollup merge of #144767 - tgross35:doc-grammar, r=ibraheemdev许杰友 Jieyou Xu (Joe)-18/+12
Correct some grammar in integer documentation Update "between" to "among" (more than two items), connect the "which" dependent clause to the independent part, and remove the redundant "here".
2025-08-18Implement feature `int_lowest_highest_one` for integer and NonZero typesAlexandre Courbot-0/+138
Implement the accepted ACP for methods that find the index of the least significant (lowest) and most significant (highest) set bit in an integer for signed, unsigned, and NonZero types. Also add unit tests for all these types.
2025-08-15Rollup merge of #144947 - tautschnig:remove-stray-checked_div-comment, ↵Stuart Cook-12/+6
r=Mark-Simulacrum Fix description of unsigned `checked_exact_div` Like its signed counterpart, this function does not panic. Also, fix the examples to document how it returns Some/None.