about summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2024-01-25fmtYuri Astrakhan-1/+8
2024-01-25Postpone .next() call until iterationYuri Astrakhan-29/+49
2024-01-25Boost intersperse(_with) performanceYuri Astrakhan-52/+74
I did some benchmark digging into the `intersperse` and `intersperse_with` code as part of the https://internals.rust-lang.org/t/add-iterate-with-separators-iterator-function/18781/13 discussion, and as a result I optimized them a bit, without relying on the peekable iterator.
2024-01-25Rollup merge of #120338 - steffahn:provenance_links, r=NilstriebMatthias Krüger-8/+8
Fix links to [strict|exposed] provenance sections of `[std|core]::ptr`
2024-01-25core: add `From<core::ascii::char>` implementationsMichal Nazarewicz-0/+16
Introduce `From<core::ascii::char>` implementations for all unsigned numeric types and `char`. This matches the API of `char` type. Issue: https://github.com/rust-lang/rust/issues/110998
2024-01-25Update primitive_docs.rsJoshua Liebow-Feeser-0/+4
2024-01-25Fix links to [strict|exposed] provenance sections of `[std|core]::ptr`Frank Steffahn-8/+8
2024-01-25Rollup merge of #119305 - compiler-errors:async-fn-traits, r=oli-obkMatthias Krüger-0/+112
Add `AsyncFn` family of traits I'm proposing to add a new family of `async`hronous `Fn`-like traits to the standard library for experimentation purposes. ## Why do we need new traits? On the user side, it is useful to be able to express `AsyncFn` trait bounds natively via the parenthesized sugar syntax, i.e. `x: impl AsyncFn(&str) -> String` when experimenting with async-closure code. This also does not preclude `AsyncFn` becoming something else like a trait alias if a more fundamental desugaring (which can take many[^1] different[^2] forms) comes around. I think we should be able to play around with `AsyncFn` well before that, though. I'm also not proposing stabilization of these trait names any time soon (we may even want to instead express them via new syntax, like `async Fn() -> ..`), but I also don't think we need to introduce an obtuse bikeshedding name, since `AsyncFn` just makes sense. ## The lending problem: why not add a more fundamental primitive of `LendingFn`/`LendingFnMut`? Firstly, for `async` closures to be as flexible as possible, they must be allowed to return futures which borrow from the async closure's captures. This can be done by introducing `LendingFn`/`LendingFnMut` traits, or (equivalently) by adding a new generic associated type to `FnMut` which allows the return type to capture lifetimes from the `&mut self` argument of the trait. This was proposed in one of [Niko's blog posts](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/). Upon further experimentation, for the purposes of closure type- and borrow-checking, I've come to the conclusion that it's significantly harder to teach the compiler how to handle *general* lending closures which may borrow from their captures. This is, because unlike `Fn`/`FnMut`, the `LendingFn`/`LendingFnMut` traits don't form a simple "inheritance" hierarchy whose top trait is `FnOnce`. ```mermaid flowchart LR Fn FnMut FnOnce LendingFn LendingFnMut Fn -- isa --> FnMut FnMut -- isa --> FnOnce LendingFn -- isa --> LendingFnMut Fn -- isa --> LendingFn FnMut -- isa --> LendingFnMut ``` For example: ``` fn main() { let s = String::from("hello, world"); let f = move || &s; let x = f(); // This borrows `f` for some lifetime `'1` and returns `&'1 String`. ``` That trait hierarchy means that in general for "lending" closures, like `f` above, there's not really a meaningful return type for `<typeof(f) as FnOnce>::Output` -- it can't return `&'static str`, for example. ### Special-casing this problem: By splitting out these traits manually, and making sure that each trait has its own associated future type, we side-step the issue of having to answer the questions of a general `LendingFn`/`LendingFnMut` implementation, since the compiler knows how to generate built-in implementations for first-class constructs like async closures, including the required future types for the (by-move) `AsyncFnOnce` and (by-ref) `AsyncFnMut`/`AsyncFn` trait implementations. [^1]: For example, with trait transformers, we may eventually be able to write: `trait AsyncFn = async Fn;` [^2]: For example, via the introduction of a more fundamental "`LendingFn`" trait, plus a [special desugaring with augmented trait aliases](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Lending.20closures.20and.20Fn*.28.29.20-.3E.20impl.20Trait/near/408471480).
2024-01-25Auto merge of #119911 - NCGThompson:is-statically-known, r=oli-obkbors-149/+445
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion. While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests. Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage). Fixes #47234 Resolves #114390 `@Centri3`
2024-01-24Rollup merge of #118326 - WaffleLapkin:nz_count_ones, r=scottmcmLeón Orell Valerian Liehr-0/+37
Add `NonZero*::count_ones` This PR adds the following APIs to the standard library: ```rust impl NonZero* { pub const fn count_ones(self) -> NonZeroU32; } ``` This is potentially interesting, given that `count_ones` can't ever return 0. r? libs-api
2024-01-24core: add Duration constructorsDirkjan Ochtman-0/+120
2024-01-24std/time: avoid divisions in Duration::newUtkarsh Gupta-7/+12
2024-01-24remove StructuralEq traitRalf Jung-5/+23
2024-01-24Add `NonZero*::count_ones`Maybe Waffle-0/+37
2024-01-23Auto merge of #120283 - fmease:rollup-rk0f6r5, r=fmeasebors-10/+105
Rollup of 9 pull requests Successful merges: - #112806 (Small code improvements in `collect_intra_doc_links.rs`) - #119766 (Split tait and impl trait in assoc items logic) - #120139 (Do not normalize closure signature when building `FnOnce` shim) - #120160 (Manually implement derived `NonZero` traits.) - #120171 (Fix assume and assert in jump threading) - #120183 (Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]`) - #120195 (add several resolution test cases) - #120259 (Split Diagnostics for Uncommon Codepoints: Add List to Display Characters Involved) - #120261 (Provide structured suggestion to use trait objects in some cases of `if` arm type divergence) r? `@ghost` `@rustbot` modify labels: rollup
2024-01-23Rollup merge of #120183 - Zalathar:test-closure, r=compiler-errorsLeón Orell Valerian Liehr-2/+2
Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]` These closures are an internal implementation detail of the `#[test]` and `#[bench]` attribute macros, so from a user perspective there is no reason to instrument them for coverage. Skipping them makes coverage reports slightly cleaner, and will also allow other changes to span processing during coverage instrumentation, without having to worry about how they affect the `#[test]` macro. The `#[coverage(off)]` attribute has no effect when `-Cinstrument-coverage` is not used. Fixes #120046. --- Note that this PR has no effect on the user-written function that has the `#[test]` attribute attached to it. That function will still be instrumented as normal.
2024-01-23Rollup merge of #120171 - cjgillot:jump-threading-assume-assert, r=tmiaskoLeón Orell Valerian Liehr-0/+2
Fix assume and assert in jump threading r? ``@tmiasko``
2024-01-23Rollup merge of #120160 - reitermarkus:nonzero-traits, r=dtolnayLeón Orell Valerian Liehr-8/+101
Manually implement derived `NonZero` traits. Step 3 as mentioned in https://github.com/rust-lang/rust/pull/100428#pullrequestreview-1767139731. Manually implement the traits that would cause “borrow of layout constrained field with interior mutability” errors when switching to `NonZero<T>`. r? ```@dtolnay```
2024-01-23Rollup merge of #120244 - reitermarkus:nonzero-self, r=dtolnayLeón Orell Valerian Liehr-43/+48
Use `Self` in `NonZero*` implementations. This slightly reduces the size of the eventual diff when making these generic, since this can be merged independently.
2024-01-23Further Implement Power of Two OptimizationNicholas Thompson-146/+324
2024-01-23Further Implement `is_val_statically_known`Nicholas Thompson-8/+22
2024-01-23Auto merge of #119892 - joboet:libs_use_assert_unchecked, r=Nilstrieb,cuviperbors-9/+12
Use `assert_unchecked` instead of `assume` intrinsic in the standard library Now that a public wrapper for the `assume` intrinsic exists, we can use it in the standard library. CC #119131
2024-01-22Add Assume custom MIR.Camille GILLOT-0/+2
2024-01-22Rollup merge of #120143 - ↵Matthias Krüger-0/+1
compiler-errors:consolidate-instance-resolve-for-coroutines, r=oli-obk Consolidate logic around resolving built-in coroutine trait impls Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best. r? oli-obk
2024-01-22Use `Self` in `NonZero*` implementations.Markus Reiter-43/+48
2024-01-22Rollup merge of #118578 - mina86:c, r=dtolnayMatthias Krüger-28/+217
core: introduce split_at{,_mut}_checked Introduce split_at_checked and split_at_mut_checked methods to slices types (including str) which are non-panicking versions of split_at and split_at_mut respectively. This is analogous to get method being non-panicking version of indexing. - https://github.com/rust-lang/libs-team/issues/308 - https://github.com/rust-lang/rust/issues/119128
2024-01-22Auto merge of #120226 - matthiaskrgr:rollup-9xwx0si, r=matthiaskrgrbors-39/+39
Rollup of 9 pull requests Successful merges: - #118714 ( Explanation that fields are being used when deriving `(Partial)Ord` on enums) - #119710 (Improve `let_underscore_lock`) - #119726 (Tweak Library Integer Division Docs) - #119746 (rustdoc: hide modals when resizing the sidebar) - #119986 (Fix error counting) - #120194 (Shorten `#[must_use]` Diagnostic Message for `Option::is_none`) - #120200 (Correct the anchor of an URL in an error message) - #120203 (Replace `#!/bin/bash` with `#!/usr/bin/env bash` in rust-installer tests) - #120212 (Give nnethercote more reviews) r? `@ghost` `@rustbot` modify labels: rollup
2024-01-22Auto merge of #120196 - matthiaskrgr:rollup-id2zocf, r=matthiaskrgrbors-2/+0
Rollup of 8 pull requests Successful merges: - #120005 (Update Readme) - #120045 (Un-hide `iter::repeat_n`) - #120128 (Make stable_mir::with_tables sound) - #120145 (fix: Drop guard was deallocating with the incorrect size) - #120158 (`rustc_mir_dataflow`: Restore removed exports) - #120167 (Capture the rationale for `-Zallow-features=` in bootstrap.py) - #120174 (Warn users about limited review for tier 2 and 3 code) - #120180 (Document some alternatives to `Vec::split_off`) Failed merges: - #120171 (Fix assume and assert in jump threading) r? `@ghost` `@rustbot` modify labels: rollup
2024-01-22Rollup merge of #120194 - ↵Matthias Krüger-1/+1
HTGAzureX1212:HTGAzureX1212shorten-option-must-use, r=Nilstrieb Shorten `#[must_use]` Diagnostic Message for `Option::is_none` This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
2024-01-22Rollup merge of #119726 - NCGThompson:div-overflow-doc, r=NilstriebMatthias Krüger-36/+34
Tweak Library Integer Division Docs Improved the documentation and diagnostics related to panicking in the division-like methods in std: * For signed methods that can overflow, clarified "results in overflow" to "self is -1 and rhs is Self::MIN." This is more concise than saying "results in overflow" and then explaining how it could overflow. * For floor/ceil_div, corrected the documentation and made it more like the documentation in other methods. * For signed methods that can overflow, explicitly mention that they are not affected by compiler flags. * Removed all unused rustc_inherit_overflow_checks attributes. The non-division-like operations will never overflow. * Added track_caller attributes to all methods that can panic. The panic messages will always be correct. For example, division methods all have / before %. * Edited the saturating_div documentation to be consistent with similar methods.
2024-01-22Rollup merge of #118714 - The-Ludwig:explain_ord_derive_enum_field, r=NilstriebMatthias Krüger-2/+4
Explanation that fields are being used when deriving `(Partial)Ord` on enums When deriving `std::cmp::Ord` or `std::cmp::PartialOrd` on enums, their fields are compared if the variants are equal. This means that the last assertion in the following snipped panics. ```rust use std::cmp::{PartialEq, Eq, PartialOrd, Ord}; #[derive(PartialEq, Eq, PartialOrd, Ord)] enum Sizes { Small(usize), Big(usize), } fn main() { let a = Sizes::Big(3); let b = Sizes::Big(5); let c = Sizes::Small(10); assert!( c < a); assert_eq!(a, c); } ``` This is more often expected behavior than not, and can be easily circumvented, as discussed in [this thread](https://users.rust-lang.org/t/how-to-sort-enum-variants/52291/4). But it is addressed nowhere in the documentation, yet. So I stumbled across this, as I personally did not expect fields being used in `PartialOrd`. I added the explanation to the documentation.
2024-01-21reviewMichal Nazarewicz-178/+20
2024-01-21Manually implement derived `NonZero` traits.Markus Reiter-8/+101
2024-01-21Auto merge of #119807 - Emilgardis:track_caller_from_impl_into, r=Nilstriebbors-0/+1
Add `#[track_caller]` to the "From implies Into" impl This pr implements what was mentioned in https://github.com/rust-lang/rust/issues/77474#issuecomment-1074480790 This follows from my URLO https://users.rust-lang.org/t/104497 ```rust #![allow(warnings)] fn main() { // Gives a good location let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(|e| e.into())); // still doesn't work, gives location of `FnOnce::call_once()` let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(Into::into)); } #[derive(Debug)] pub struct Loc { pub l: &'static std::panic::Location<'static>, } impl From<()> for Loc { #[track_caller] fn from(_: ()) -> Self { Loc { l: std::panic::Location::caller(), } } } ```
2024-01-21Fix `clippy::correctness` in the libraryNilstrieb-0/+12
2024-01-21Add `#[coverage(off)]` to closures introduced by `#[test]`/`#[bench]`Zalathar-2/+2
2024-01-21Rollup merge of #120045 - scottmcm:unhide-repeat-n, r=Mark-SimulacrumMatthias Krüger-2/+0
Un-hide `iter::repeat_n` ACP accepted in https://github.com/rust-lang/libs-team/issues/120#issuecomment-1894144403
2024-01-21Auto merge of #85528 - the8472:iter-markers, r=dtolnaybors-12/+105
Implement iterator specialization traits on more adapters This adds * `TrustedLen` to `Skip` and `StepBy` * `TrustedRandomAccess` to `Skip` * `InPlaceIterable` and `SourceIter` to `Copied` and `Cloned` The first two might improve performance in the compiler itself since `skip` is used in several places. Constellations that would exercise the last point are probably rare since it would require an owning iterator that has references as Items somewhere in its iterator pipeline. Improvements for `Skip`: ``` # old test iter::bench_skip_trusted_random_access ... bench: 8,335 ns/iter (+/- 90) # new test iter::bench_skip_trusted_random_access ... bench: 2,753 ns/iter (+/- 27) ```
2024-01-21chore: suggest wrapping in an `assert!()` insteadHTGAzureX1212-1/+1
This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
2024-01-21Rollup merge of #119081 - jstasiak:is-ipv4-mapped, r=dtolnayNadrieril-0/+25
Add Ipv6Addr::is_ipv4_mapped This change consists of cherry-picking the content from the original PR[1], which got closed due to inactivity, and applying the following changes: * Resolving merge conflicts (obviously) * Linked to to_ipv4_mapped instead of to_ipv4 in the documentation (seems more appropriate) * Added the must_use and rustc_const_unstable attributes the original didn't have I think it's a reasonably useful method to have. [1] https://github.com/rust-lang/rust/pull/86490
2024-01-21Rollup merge of #118811 - EbbDrop:is-sorted-by-bool, r=Mark-SimulacrumNadrieril-21/+33
Use `bool` instead of `PartiolOrd` as return value of the comparison closure in `{slice,Iteraotr}::is_sorted_by` Changes the function signature of the closure given to `{slice,Iteraotr}::is_sorted_by` to return a `bool` instead of a `PartiolOrd` as suggested by the libs-api team here: https://github.com/rust-lang/rust/issues/53485#issuecomment-1766411980. This means these functions now return true if the closure returns true for all the pairs of values.
2024-01-21Rollup merge of #116090 - rmehri01:strict_integer_ops, r=m-ou-seNadrieril-15/+996
Implement strict integer operations that panic on overflow This PR implements the first part of the ACP for adding panic on overflow style arithmetic operations (https://github.com/rust-lang/libs-team/issues/270), mentioned in #116064. It adds the following operations on both signed and unsigned integers: - `strict_add` - `strict_sub` - `strict_mul` - `strict_div` - `strict_div_euclid` - `strict_rem` - `strict_rem_euclid` - `strict_neg` - `strict_shl` - `strict_shr` - `strict_pow` Additionally, signed integers have: - `strict_add_unsigned` - `strict_sub_unsigned` - `strict_abs` And unsigned integers have: - `strict_add_signed` The `div` and `rem` operations are the same as normal division and remainder but are added for completeness similar to the corresponding `wrapping_*` operations. I'm not sure if I missed any operations, I basically found them from the `wrapping_*` and `checked_*` operations on both integer types.
2024-01-20Auto merge of #111803 - scottmcm:simple-swap-alternative, r=Mark-Simulacrumbors-1/+1
Tweak the threshold for chunked swapping Thanks to `@AngelicosPhosphoros` for the tests here, which I copied from #98892. This is an experiment as a simple alternative to that PR that just tweaks the existing threshold, since that PR showed that 3×Align (like `String`) currently doesn't work as well as it could.
2024-01-20Use bool instead of PartiolOrd in is_sorted_byEbbDrop-21/+33
2024-01-20Spelling fixsunrosa-1/+1
"It's" expands to "it is". "Its" is the possessive form.
2024-01-20core: introduce split_at{,_mut}_checkedMichal Nazarewicz-28/+375
Introduce split_at_checked and split_at_mut_checked methods to slices types (including str) which are non-panicking versions of split_at and split_at_mut respectively. This is analogous to get method being non-panicking version of indexing.
2024-01-20doc: fix some doctests after rebaseTomás Vallotton-3/+3
2024-01-20refactor: make waker mandatory.Tomás Vallotton-81/+18
This also removes * impl From<&Context> for ContextBuilder * Context::try_waker() The from implementation is removed because now that wakers are always supported, there are less incentives to override the current context. Before, the incentive was to add Waker support to a reactor that didn't have any.
2024-01-20chore: make method order consistent with wakerTomás Vallotton-13/+13
2024-01-20docs: remove recommendations to use LocalWaker in stable API documentationTomás Vallotton-57/+46