about summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2022-10-31Specialize PartialEq for Option<num::NonZero*> and Option<ptr::NonNull>clubby789-1/+67
2022-10-31Rewrite implementation of `#[alloc_error_handler]`Amanieu d'Antras-0/+14
The new implementation doesn't use weak lang items and instead changes `#[alloc_error_handler]` to an attribute macro just like `#[global_allocator]`. The attribute will generate the `__rg_oom` function which is called by the compiler-generated `__rust_alloc_error_handler`. If no `__rg_oom` function is defined in any crate then the compiler shim will call `__rdl_oom` in the alloc crate which will simply panic. This also fixes link errors with `-C link-dead-code` with `default_alloc_error_handler`: `__rg_oom` was previously defined in the alloc crate and would attempt to reference the `oom` lang item, even if it didn't exist. This worked as long as `__rg_oom` was excluded from linking since it was not called. This is a prerequisite for the stabilization of `default_alloc_error_handler` (#102318).
2022-10-31Rollup merge of #103766 - lukas-code:error-in-core, r=Dylan-DPCDylan DPC-1/+1
Add tracking issue to `error_in_core` This was merged in https://github.com/rust-lang/rust/pull/99917 without a tracking issue, so I'm creating one now: https://github.com/rust-lang/rust/issues/103765
2022-10-30Add tracking issue to `error_in_core`Lukas Markeffsky-1/+1
2022-10-30Rollup merge of #103715 - tshepang:consistency, r=Dylan-DPCMatthias Krüger-2/+2
use consistent terminology I did not see other traits using the "interface" word
2022-10-30Rollup merge of #100006 - jyn514:update-copy, r=dtolnayMatthias Krüger-1/+1
Make `core::mem::copy` const cc https://github.com/rust-lang/rust/issues/98262, https://github.com/rust-lang/libs-team/issues/78
2022-10-29More inference-friendly API for lazyAleksey Kladov-3/+1
The signature for new was ``` fn new<F>(f: F) -> Lazy<T, F> ``` Notably, with `F` unconstrained, `T` can be literally anything, and just `let _ = Lazy::new(|| 92)` would not typecheck. This historiacally was a necessity -- `new` is a `const` function, it couldn't have any bounds. Today though, we can move `new` under the `F: FnOnce() -> T` bound, which gives the compiler enough data to infer the type of T from closure.
2022-10-29use consistent terminologyTshepang Mbambo-2/+2
I did not see other traits using the "interface" word
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-28Lift `T: Sized` bounds from some `strict_provenance` pointer methodsMaybe Waffle-36/+12
2022-10-28Simplify implementation of various pointer methodsMaybe Waffle-25/+15
2022-10-28Make `pointer::with_metadata_of` const (+simplify implementation)Maybe Waffle-20/+6
2022-10-28Add examples for `pointer::mask`Maybe Waffle-0/+53
2022-10-28Remove unneeded attribute.Markus Reiter-1/+0
2022-10-28CStr: add some doc linksRalf Jung-2/+5
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-26stabilize `int_log`Lukas Markeffsky-30/+36
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-25stabilise array methodsDylan DPC-7/+2
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-24Make `pointer::byte_offset_from` more genericMaybe Waffle-2/+2
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-23`unchecked_{shl|shr}` should use `u32` as the RHSScott McMurray-12/+22
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-22Pin::new_unchecked: discuss pinning closure capturesRalf Jung-2/+55
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-22Fix mod_inv termination for the last iterationSimonas Kazlauskas-26/+28
On usize=u64 platforms, the 4th iteration would overflow the `mod_gate` back to 0. Similarly for usize=u32 platforms, the 3rd iteration would overflow much the same way. I tested various approaches to resolving this, including approaches with `saturating_mul` and `widening_mul` to a double usize. Turns out LLVM likes `mul_with_overflow` the best. In fact now, that LLVM can see the iteration count is limited, it will happily unroll the loop into a nice linear sequence. You will also notice that the code around the loop got simplified somewhat. Now that LLVM is handling the loop nicely, there isn’t any more reasons to manually unroll the first iteration out of the loop (though looking at the code today I’m not sure all that complexity was necessary in the first place). Fixes #103361
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-20Update tests to match error message changesb4den-1/+1