summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2022-10-31Bump version placeholders to releaseMark Rousskov-31/+31
2022-10-29Rollup merge of #102961 - reitermarkus:const-cstr-from-ptr, r=oli-obkMatthias Krüger-11/+37
Make `CStr::from_ptr` `const`. Should be included in https://github.com/rust-lang/rust/issues/101719. cc ``@WaffleLapkin``
2022-10-28Auto merge of #102737 - RalfJung:poll_fn_pin, r=Mark-Simulacrumbors-4/+7
poll_fn and Unpin: fix pinning See [IRLO](https://internals.rust-lang.org/t/surprising-soundness-trouble-around-pollfn/17484) for details: currently `poll_fn` is very subtle to use, since it does not pin the closure, so creating a `Pin::get_unchcked(&mut capture)` inside the closure is unsound. This leads to actual miscompilations with `futures::join!`. IMO the proper fix is to pin the closure when the future is pinned, which is achieved by changing the `Unpin` implementation. This is a breaking change though. 1.64.0 was *just* released, so maybe this is still okay? The alternative would be to add some strong comments to the docs saying that closure captures are *not pinned* and doing `Pin::get_unchecked` on them is unsound.
2022-10-28Remove unneeded attribute.Markus Reiter-1/+0
2022-10-27Rollup merge of #103394 - Pointerbender:unsafecell-docs, r=AmanieuMatthias Krüger-25/+36
Clarify documentation about the memory layout of `UnsafeCell` This PR addresses a [comment](https://github.com/rust-lang/rust/pull/101717#issuecomment-1279908390) by `@RalfJung` in PR #101717 to further clarify the documentation of `UnsafeCell<T>`. The previous PR was merged already before we had a chance to correct this, hence this second PR :) To goal of this PR is: 1. Split the paragraph about the memory layout of `UnsafeCell<T>` and the usage of `UnsafeCell::(raw_)get()` into two paragraphs, so that it is easier to digest for the reader. 2. Slightly simplify the previously added examples in order to reduce redundancy between the new examples and the examples that already [existed](https://github.com/rust-lang/rust/blob/ddd119b2fed57eb6b19c44c18108de95c564a48d/library/core/src/cell.rs#L1858-L1908) before these 2 PRs (which remained untouched by both PRs).
2022-10-27Rollup merge of #103110 - RalfJung:manual-send, r=thomccMatthias Krüger-7/+6
remove redundant Send impl for references Also explain why the other instance is not redundant, move it next to the trait they are implementing, and out of the redundant module. This seems to go back all the way to https://github.com/rust-lang/rust/commit/35ca50bd5676db31a8074a216d1aadad7d434de8, not sure why the module was added. The instance for `&mut` is the default instance we get anyway, and we don't have anything similar for `Sync`, so IMO we should be consistent and not have the redundant instance here, either.
2022-10-27Rollup merge of #103106 - saethlin:from_exposed_docs, r=thomccMatthias Krüger-6/+15
Try to say that memory outside the AM is always exposed cc ``@Gankra`` ``@thomcc`` I want to confidently tell people that they can use `from_exposed_addr` to get a pointer for doing MMIO and/or other hardware interactions done with volatile reads/writes at particular addresses outside the Rust AM. Currently, the docs indicate that would be UB. With this change, now the docs indicate that this is intended to be a valid use of `from_exposed_addr`. r? ``@RalfJung``
2022-10-27Rollup merge of #103035 - saethlin:assert_unsafe_precondition3, r=thomccMatthias Krüger-36/+113
Even nicer errors from assert_unsafe_precondition For example, now running `cargo test` with this patch I get things like: ``` $ cargo +stage1 test Finished test [unoptimized + debuginfo] target(s) in 0.01s Running unittests src/lib.rs (target/debug/deps/malloc_buf-9d105ddf86862995) running 5 tests thread 'tests::test_null_buf' panicked at 'unsafe precondition violated: is_aligned_and_not_null(data) && crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize', /home/ben/rust/library/core/src/slice/raw.rs:93:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace thread panicked while panicking. aborting. error: test failed, to rerun pass `--lib` Caused by: process didn't exit successfully: `/tmp/malloc_buf-1.0.0/target/debug/deps/malloc_buf-9d105ddf86862995` (signal: 6, SIGABRT: process abort signal) ``` This is still not perfect, but these are better for another PR: * `stringify!` is trying to do clever pretty-printing on the `expr` inside `assert_unsafe_precondition` and can even add a newline. * It would be nice to print a bit more information about where the problem is. Perhaps this is `cfg_attr(debug_assertions, track_caller)`, or perhaps it the function name added to `Location`. cc ``@RalfJung`` this is what I was thinking of for https://github.com/rust-lang/rust/pull/102732#discussion_r989068907
2022-10-27add "Memory layout" subsection to documentation of `UnsafeCell` for ↵Pointerbender-0/+2
additional clarity
2022-10-26Print the precondition we violated, and visible through output captureBen Kimock-36/+113
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-27Rollup merge of #103580 - lukas-code:guaranteed_ne, r=GuillaumeGomezYuki Okushi-2/+2
Fix typo in docs for `guaranteed_ne` `==` -> `!=`
2022-10-27Rollup merge of #103567 - RalfJung:ptr-eq-dyn-trait, r=dtolnayYuki Okushi-35/+6
ptr::eq: clarify that comparing dyn Trait is fragile Also remove the dyn trait example from `ptr::eq` since those tests are not actually guaranteed to pass due to how unstable vtable comparison is. Cc ``@rust-lang/libs-api`` Cc discussion following https://github.com/rust-lang/rust/pull/80505
2022-10-26Fix typo in docs for `guaranteed_ne`Lukas Markeffsky-2/+2
2022-10-26Update library/core/src/ptr/mod.rsBen Kimock-0/+1
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-26explicitly mention that both components of wide prts are comparedRalf Jung-0/+1
2022-10-26ptr::eq: clarify that comparing dyn Trait is fragileRalf Jung-35/+5
2022-10-26Rollup merge of #103287 - saethlin:faster-len-check, r=thomccDylan DPC-5/+16
Use a faster allocation size check in slice::from_raw_parts I've been perusing through the codegen changes that result from turning on the standard library debug assertions. The previous check in here uses saturating arithmetic, which in my experience sometimes makes LLVM just fail to optimize things around the saturating operation. Here is a demo of the codegen difference: https://godbolt.org/z/WMEqrjajW Before: ```asm example::len_check_old: mov rax, rdi mov ecx, 3 mul rcx setno cl test rax, rax setns al and al, cl ret example::len_check_old: mov rax, rdi mov ecx, 8 mul rcx setno cl test rax, rax setns al and al, cl ret ``` After: ```asm example::len_check_new: movabs rax, 3074457345618258603 cmp rdi, rax setb al ret example::len_check_new: shr rdi, 60 sete al ret ``` Running rustc-perf locally, this looks like up to a 4.5% improvement when `debug-assertions-std = true`. Thanks ```@LegionMammal978``` (I think that's you?) for turning my idea into a much cleaner implementation. r? ```@thomcc```
2022-10-25Try to say that memory outside the AM is always exposedBen Kimock-6/+14
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-25Rollup merge of #98204 - Kixiron:stable-unzip, r=thomccDylan DPC-4/+7
Stabilize `Option::unzip()` Stabilizes `Option::unzip()`, closes #87800 ```@rustbot``` modify labels: +T-libs-api
2022-10-24Rollup merge of #102271 - ↵Yuki Okushi-22/+19
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-24Auto merge of #100848 - xfix:use-metadata-for-slice-len, r=thomccbors-17/+9
Use ptr::metadata in <[T]>::len implementation This avoids duplication of ptr::metadata code. I believe this is acceptable as the previous approach essentially duplicated `ptr::metadata` because back then `rustc_allow_const_fn_unstable` annotation did not exist. I would like somebody to ping `@rust-lang/wg-const-eval` as the documentation says: > Always ping `@rust-lang/wg-const-eval` if you are adding more rustc_allow_const_fn_unstable attributes to any const fn.
2022-10-24fix typosPointerbender-2/+2
Co-authored-by: Ralf Jung <post@ralfj.de>
2022-10-23Rollup merge of #103447 - ajtribick:maybe_uninit_doc_update, r=scottmcmMichael Howell-2/+1
`MaybeUninit`: use `assume_init_drop()` in the partially initialized array example The `assume_init_drop()` method does the same thing as the pointer conversion, and makes the example more straightforward.
2022-10-23Rollup merge of #100462 - zohnannor:master, r=thomccMichael Howell-0/+4
Clarify `array::from_fn` documentation I've seen quite a few of people on social media confused of where the length of array is coming from in the newly stabilized `array::from_fn` example. This PR tries to clarify the documentation on this.
2022-10-23MaybeUninit: use assume_init_drop() in the partially initialized array exampleAndrew Tribick-2/+1
2022-10-22Rollup merge of #103346 - HeroicKatora:metadata_of_const_pointer_argument, ↵Dylan DPC-1/+5
r=dtolnay Adjust argument type for mutable with_metadata_of (#75091) The method takes two pointer arguments: one `self` supplying the pointer value, and a second pointer supplying the metadata. The new parameter type more clearly reflects the actual requirements. The provenance of the metadata parameter is disregarded completely. Using a mutable pointer in the call site can be coerced to a const pointer while the reverse is not true. In some cases, the current parameter type can thus lead to a very slightly confusing additional cast. [Example](https://github.com/HeroicKatora/static-alloc/commit/cad93775eb9adc62f744651e3abf19513e69e7d0). ```rust // Manually taking an unsized object from a `ManuallyDrop` into another allocation. let val: &core::mem::ManuallyDrop<T> = …; let ptr = val as *const _ as *mut T; let ptr = uninit.as_ptr().with_metadata_of(ptr); ``` This could then instead be simplified to: ```rust // Manually taking an unsized object from a `ManuallyDrop` into another allocation. let val: &core::mem::ManuallyDrop<T> = …; let ptr = uninit.as_ptr().with_metadata_of(&**val); ``` Tracking issue: https://github.com/rust-lang/rust/issues/75091 ``@dtolnay`` you're reviewed #95249, would you mind chiming in?
2022-10-22Rollup merge of #103329 - saethlin:nonnull-precondition, r=thomccDylan DPC-1/+5
Add a forgotten check for NonNull::new_unchecked's precondition Looks like I forgot this function a while ago in https://github.com/rust-lang/rust/pull/92686 r? ```@thomcc```
2022-10-21Auto merge of #101263 - lopopolo:lopopolo/c-unwind-fn-ptr-impls, r=thomccbors-7/+21
Add default trait implementations for "c-unwind" ABI function pointers Following up on #92964, only add default trait implementations for the `c-unwind` family of function pointers. The previous attempt in #92964 added trait implementations for many more ABIs and ran into concerns regarding the increase in size of the libcore rlib. An attempt to abstract away function pointer types behind a unified trait to reduce the duplication of trait impls is being discussed in #99531 but this change looks to be blocked on a lang MCP. Following `@RalfJung's` suggestion in https://github.com/rust-lang/rust/pull/99531#issuecomment-1233440142, this commit is another cut at #92964 but it _only_ adds the impls for `extern "C-unwind" fn` and `unsafe extern "C-unwind" fn`. I am interested in landing this patch to unblock the stabilization of the `c_unwind` feature. RFC: https://github.com/rust-lang/rfcs/pull/2945 Tracking Issue: https://github.com/rust-lang/rust/issues/74990
2022-10-21Argument type for mutable with_metadata_of (#75091)Andreas Molzer-1/+5
The method takes two pointer arguments: one `self` supplying the pointer value, and a second pointer supplying the metadata. The new parameter type more clearly reflects the actual requirements. The provenance of the metadata parameter is disregarded completely. Using a mutable pointer in the call site can be coerced to a const pointer while the reverse is not true. An example of the current use: ```rust // Manually taking an unsized object from a `ManuallyDrop` into another allocation. let val: &core::mem::ManuallyDrop<T> = …; let ptr = val as *const _ as *mut T; let ptr = uninit.as_ptr().with_metadata_of(ptr); ``` This could then instead be simplified to: ```rust // Manually taking an unsized object from a `ManuallyDrop` into another allocation. let val: &core::mem::ManuallyDrop<T> = …; let ptr = uninit.as_ptr().with_metadata_of(&**val); ```
2022-10-20Add a missing precondition checkBen Kimock-1/+5
2022-10-20Rollup merge of #103281 - thomcc:long-overdue, r=jyn514Matthias Krüger-20/+23
Adjust `transmute{,_copy}` to be clearer about which of `T` and `U` is input vs output This is essentially a documentation-only change (although it does touch code in an irrelevant way).
2022-10-20Skip C-unwind fn pointer impls with the bootstrap compilerRyan Lopopolo-0/+1
These need to wait until #103239 makes it into the bootstrap compiler.
2022-10-20clarify documentation about the memory layout of `UnsafeCell`Pointerbender-25/+34
2022-10-19Adjust `transmute{,_copy}` to be clearer about which of `T` and `U` is input ↵Thom Chiovoloni-20/+23
vs output
2022-10-20Use a faster allocation size check in slice::from_raw_partsBen Kimock-5/+16
2022-10-19Update stability annotations on fnptr impls for C-unwind ABIRyan Lopopolo-13/+19
2022-10-19Add default trait implementations for "c-unwind" ABI function pointersRyan Lopopolo-0/+7
Following up on #92964, only add default trait implementations for the `c-unwind` family of function pointers. The previous attempt in #92964 added trait implementations for many more ABIs and ran into concerns regarding the increase in size of the libcore rlib. An attempt to abstract away function pointer types behind a unified trait to reduce the duplication of trait impls is being discussed in #99531 but this change looks to be blocked on a lang MCP. Following @RalfJung's suggestion in https://github.com/rust-lang/rust/pull/99531#issuecomment-1233440142, this commit is another cut at #92964 but it _only_ adds the impls for `extern "C-unwind" fn` and `unsafe extern "C-unwind" fn`. I am interested in landing this patch to unblock the stabilization of the `c_unwind` feature. RFC: https://github.com/rust-lang/rfcs/pull/2945 Tracking Issue: https://github.com/rust-lang/rust/issues/74990
2022-10-19Remove extra spacesclubby789-8/+8
2022-10-19Rollup merge of #103127 - SUPERCILEX:inline-const-uninit, r=scottmcmDylan DPC-2/+5
Make transpose const and inline r? `@scottmcm` - These should have been const from the beginning since we're never going to do more than a transmute. - Inline these always because that's what every other method in MaybeUninit which simply casts does. :) Ok, but a stronger justification is that because we're taking in arrays by `self`, not inlining would defeat the whole purpose of using `MaybeUninit` due to the copying.
2022-10-19Auto merge of #103225 - matthiaskrgr:rollup-1zkv87y, r=matthiaskrgrbors-0/+74
Rollup of 4 pull requests Successful merges: - #103166 (Optimize `slice_iter.copied().next_chunk()`) - #103176 (Fix `TyKind::is_simple_path`) - #103178 (Partially fix `src/test/run-make/coverage-reports` when cross-compiling) - #103198 (Update cargo) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2022-10-19Rollup merge of #103166 - the8472:copied-next-chunk, r=m-ou-seMatthias Krüger-0/+74
Optimize `slice_iter.copied().next_chunk()` ``` OLD: test iter::bench_copied_array_chunks ... bench: 371 ns/iter (+/- 7) NEW: test iter::bench_copied_array_chunks ... bench: 31 ns/iter (+/- 0) ``` The default `next_chunk` implementation suffers from having to assemble the array byte by byte via `next()`, checking the `Option<&T>` and then dereferencing `&T`. The specialization copies the chunk directly from the slice.
2022-10-19specialize slice_iter.copied().next_chunk()The 8472-0/+74
2022-10-18Rollup merge of #102507 - scottmcm:more-binary-search-docs, r=m-ou-seMatthias Krüger-0/+32
More slice::partition_point examples After seeing the discussion of `binary_search` vs `partition_point` in #101999, I thought some more example code could be helpful.
2022-10-18Rollup merge of #101889 - tspiteri:redoc-uint-adc-sbb, r=m-ou-seMatthias Krüger-31/+49
doc: rewrite doc for uint::{carrying_add,borrowing_sub} Reword the documentation for bigint helper methods `uint::{carrying_add,borrowing_sub}` (#85532). The examples were also rewritten to demonstrate how the methods can be used in bignum arithmetic. No loops are used in the examples, but the variable names were chosen to include indices so that it is clear how this can be used in a loop if required. Also, previously `carrying_add` had an example to say that if the input carry is false, the method is equivalent to `overflowing_add`. While the note was kept, the example was removed and an extra note was added to make sure this equivalence is not assumed for signed integers as well.
2022-10-18Rollup merge of #103163 - SUPERCILEX:uninit-array-assume2, r=scottmcmYuki Okushi-4/+3
Remove all uses of array_assume_init See https://github.com/rust-lang/rust/pull/103134#discussion_r997462733 r? `@scottmcm`
2022-10-18Rollup merge of #103159 - cuviper:check_pow-final-try_opt, r=Mark-SimulacrumYuki Okushi-2/+2
Remove the redundant `Some(try_opt!(..))` in `checked_pow` The final return value doesn't need to be tried at all -- we can just return the checked option directly. The optimizer can probably figure this out anyway, but there's no need to make it work here.
2022-10-17Remove all uses of array_assume_initAlex Saveau-4/+3
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-17Remove the redundant `Some(try_opt!(..))` in `checked_pow`Josh Stone-2/+2
The final return value doesn't need to be tried at all -- we can just return the checked option directly. The optimizer can probably figure this out anyway, but there's no need to make it work here.
2022-10-17Fix typo in `ReverseSearcher` docsSky-1/+1
2022-10-16Fix types in documentation for Alignment::as_usize and Alignmnet::as_nonzeroThayne McCombs-2/+2