char to_digit: avoid unnecessary casts to u64
Hello,
in the `char::to_digit` method there are a few `as u64` casts that are not strictly necessary.
I assume that the reason behind these casts is to avoid possible overflows in the `+ 10` add.
This PR removes the aforementioned casts, avoiding the overflow issue by slightly modifying the ASCII letter to int mapping.
Thanks,
Happy new year.
Tidy up bigint multiplication methods
This tidies up the library version of the bigint multiplication methods after the addition of the intrinsics in #133663. It follows [this summary](https://github.com/rust-lang/rust/issues/85532#issuecomment-2403442775) of what's desired for these methods.
Note that, if `2H = N`, then `uH::MAX * uH::MAX + uH::MAX + uH::MAX` is `uN::MAX`, and that we can effectively add two "carry" values without overflowing.
For ease of terminology, the "low-order" or "least significant" or "wrapping" half of multiplication will be called the low part, and the "high-order" or "most significant" or "overflowing" half of multiplication will be called the high part. In all cases, the return convention is `(low, high)` and left unchanged by this PR, to be litigated later.
## API Changes
The original API:
```rust
impl uN {
// computes self * rhs
pub const fn widening_mul(self, rhs: uN) -> (uN, uN);
// computes self * rhs + carry
pub const fn carrying_mul(self, rhs: uN, carry: uN) -> (uN, uN);
}
```
The added API:
```rust
impl uN {
// computes self * rhs + carry1 + carry2
pub const fn carrying2_mul(self, rhs: uN, carry: uN, add: uN) -> (uN, uN);
}
impl iN {
// note that the low part is unsigned
pub const fn widening_mul(self, rhs: iN) -> (uN, iN);
pub const fn carrying_mul(self, rhs: iN, carry: iN) -> (uN, iN);
pub const fn carrying_mul_add(self, rhs: iN, carry: iN, add: iN) -> (uN, iN);
}
```
Additionally, a naive implementation has been added for `u128` and `i128` since there are no double-wide types for those. Eventually, an intrinsic will be added to make these more efficient, but rather than doing this all at once, the library changes are added first.
## Justifications for API
The unsigned parts are done to ensure consistency with overflowing addition: for a two's complement integer, you want to have unsigned overflow semantics for all parts of the integer except the highest one. This is because overflow for unsigned integers happens on the highest bit (from `MAX` to zero), whereas overflow for signed integers happens on the second highest bit (from `MAX` to `MIN`). Since the sign information only matters in the highest part, we use unsigned overflow for everything but that part.
There is still discussion on the merits of signed bigint *addition* methods, since getting the behaviour right is very subtle, but at least for signed bigint *multiplication*, the sign of the operands does make a difference. So, it feels appropriate that at least until we've nailed down the final API, there should be an option to do signed versions of these methods.
Additionally, while it's unclear whether we need all three versions of bigint multiplication (widening, carrying-1, and carrying-2), since it's possible to have up to two carries without overflow, there should at least be a method to allow that. We could potentially only offer the carry-2 method and expect that adding zero carries afterword will optimise correctly, but again, this can be litigated before stabilisation.
## Note on documentation
While a lot of care was put into the documentation for the `widening_mul` and `carrying_mul` methods on unsigned integers, I have not taken this same care for `carrying_mul_add` or the signed versions. While I have updated the doc tests to be more appropriate, there will likely be many documentation changes done before stabilisation.
## Note on tests
Alongside this change, I've added several tests to ensure that these methods work as expected. These are alongside the codegen tests for the intrinsics.
Fix doc for read&write unaligned in zst operation
### PR Description
This PR addresses an inconsistency in the Rust documentation regarding `read_unaligned ` and `write_unaligned` on zero-sized types (ZSTs). The current documentation for [pointer validity](https://doc.rust-lang.org/nightly/std/ptr/index.html#safety) states that for zero-sized types (ZSTs), null pointers are valid:
> For zero-sized types (ZSTs), every pointer is valid, including the null pointer.
However, there is an inconsistency in the documentation for the unaligned read operation in the function [ptr::read_unaligned](https://doc.rust-lang.org/nightly/std/ptr/fn.read_unaligned.html)(as well as `write_unaligned`), which states:
> Note that even if T has size 0, the pointer must be non-null.
This change is also supported by [PR #134912](https://github.com/rust-lang/rust/pull/134912)
> the _unaligned method docs should be fixed.
ptr docs: make it clear that we are talking only about memory accesses
This should make it harder to take this sentence out of context and misunderstand it.
stabilize const_swap
libs-api FCP passed in https://github.com/rust-lang/rust/issues/83163.
However, I only just realized that this actually involves an intrinsic. The intrinsic could be implemented entirely with existing stable const functionality, but we choose to make it a primitive to be able to detect more UB. So nominating for `@rust-lang/lang` to make sure they are aware; I leave it up to them whether they want to FCP this.
While at it I also renamed the intrinsic to make the "nonoverlapping" constraint more clear.
Fixes#83163
Add a compiler intrinsic to back `bigint_helper_methods`
cc https://github.com/rust-lang/rust/issues/85532
This adds a new `carrying_mul_add` intrinsic, to implement `wide_mul` and `carrying_mul`.
It has fallback MIR for all types -- including `u128`, which isn't currently supported on nightly -- so that it'll continue to work on all backends, including CTFE.
Then it's overridden in `cg_llvm` to use wider intermediate types, including `i256` for `u128::carrying_mul`.
ptr::copy: fix docs for the overlapping case
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/549
As discussed in that issue, it doesn't make any sense for `copy` to read a byte via `src` after it was already written via `dst`. The entire point of this method is that is copies correctly even if they overlap, and that requires always reading any given location before writing it.
Cc `@rust-lang/opsem`
docs: inline `std::ffi::c_str` types to `std::ffi`
Rustdoc has no way to show that an item is stable, but only at a different path. `std::ffi::c_str::NulError` is not stable, but `std::ffi::NulError` is.
To avoid marking these types as unstable when someone just wants to follow a link from `CString`, inline them into their stable paths.
Fixes#134702
r? `@tgross35`
Update Code Example for `Iterator::rposition`
Added an additional assertion to the example to show the behavior of `iter.next_back` after using `iter.rposition`.
core: fix const ptr::swap_nonoverlapping when there are pointers at odd offsets
Ensure that the pointer gets swapped correctly even if it is not stored at an aligned offset. This rules out implementations that copy things in a `usize` loop -- so our implementation needs to be adjusted to avoid such a loop when running in const context.
Part of https://github.com/rust-lang/rust/issues/133668
Fix safety docs for `dyn Any + Send {+ Sync}`
Fixes the `# Safety` docs for `dyn Any + Send`'s `downcast_{mut/ref}_unchecked` to show the direct instructions , where previously the would tell the user to find the docs on `dyn Any` themselves.
This also adds them for `downcast_{mut/ref}_unchecked` on `dyn Any + Send + Sync`
Use `#[derive(Default)]` instead of manual `impl` when possible
While working on #134175 I noticed a few manual `Default` `impl`s that could be `derive`d instead. These likely predate the existence of the `#[default]` attribute for `enum`s.
Revert stabilization of the `#[coverage(..)]` attribute
Due to a process mixup, the PR to stabilize the `#[coverage(..)]` attribute (#130766) was merged while there are still outstanding concerns. The default action in that situation is to revert, and the feature is not sufficiently urgent or uncontroversial to justify special treatment, so this PR reverts that stabilization.
---
- A key point that came up in offline discussions is that unlike most user-facing features, this one never had a proper RFC, so parts of the normal stabilization process that implicitly rely on an RFC break down in this case.
- As the implementor and de-facto owner of the feature in its current form, I would like to think that I made good choices in designing and implementing it, but I don't feel comfortable proceeding to stabilization without further scrutiny.
- There hasn't been a clear opportunity for T-compiler to weigh in or express concerns prior to stabilization.
- The stabilization PR cites a T-lang FCP that occurred in the tracking issue, but due to the messy design and implementation history (and lack of a clear RFC), it's unclear what that FCP approval actually represents in this case.
- At the very least, we should not proceed without a clear statement from T-lang or the relevant members about the team's stance on this feature, especially in light of the other concerns listed here.
- The existing user-facing documentation doesn't clearly reflect which parts of the feature are stable commitments, and which parts are subject to change. And there doesn't appear to be a clear consensus anywhere about where that line is actually drawn, or whether the chosen boundary is acceptable to the relevant teams and individuals.
- For example, the [stabilization report comment](https://github.com/rust-lang/rust/issues/84605#issuecomment-2166514660) mentions that some aspects are subject to change, but that text isn't consistent with my earlier comments, and there doesn't appear to have been any explicit discussion or approval process.
- [The current reference text](https://github.com/rust-lang/reference/blob/4dfaa4f/src/attributes/coverage-instrumentation.md) doesn't mention this distinction at all, and instead simply describes the current implementation behaviour.
- When the implementation was changed to its current form, the associated user-facing error messages were not updated, so they still refer to the attribute only being allowed on functions and closures.
- On its own, this might have been reasonable to fix-forward in the absence of other concerns, but the fact that it never came up earlier highlights the breakdown in process that has occurred here.
---
Apologies to everyone who was excited for this stabilization to land, but unfortunately it simply isn't ready yet.
Rollup of 6 pull requests
Successful merges:
- #130289 (docs: Permissions.readonly() also ignores root user special permissions)
- #134583 (docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code)
- #134611 (Align `{i686,x86_64}-win7-windows-msvc` to their parent targets)
- #134629 (compiletest: Allow using a specific debugger when running debuginfo tests)
- #134642 (Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.)
- #134660 (Fix spacing of markdown code block fences in compiler rustdoc)
r? `@ghost`
`@rustbot` modify labels: rollup
Implement `PointerLike` for `isize`, `NonNull`, `Cell`, `UnsafeCell`, and `SyncUnsafeCell`.
* Implementing `PointerLike` for `UnsafeCell` enables the possibility of interior mutable `dyn*` values. Since this means potentially exercising new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`. Please let me know if there are further sorts of tests that should be written, or other care that should be taken with this change.
It is unfortunately not possible without compiler changes to implement `PointerLike` for `Atomic*` types, since they are not `repr(transparent)` (and, in theory if not in practice, `AtomicUsize`'s alignment may be greater than that of an ordinary pointer or `usize`).
* Implementing `PointerLike` for `NonNull` is useful for pointer types which wrap `NonNull`.
* Implementing `PointerLike` for `isize` is just for completeness; I have no use cases in mind, but I cannot think of any reason not to do this.
* Tracking issue: #102425
`@rustbot` label +F-dyn_star
(there is no label or tracking issue for F-pointer_like_trait)
docs: `transmute<&mut T, &mut MaybeUninit<T>>` is unsound when exposed to safe code
Closes#66699
On my system (Edit: And also in the [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=90529e2a9900599cb759e4bfaa5b5efe)) the example program terminates with an unpredictable exit code:
```console
$ cargo +nightly build && target/debug/bin ; echo $?
255
$ cargo +nightly build && target/debug/bin ; echo $?
253
```
And miri considers the code to have undefined behavior:
```console
$ cargo +nightly miri run
error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory
--> src/main.rs:12:24
|
12 | std::process::exit(*code); // UB! Accessing uninitialized memory
| ^^^^^ using uninitialized data, but this operation requires initialized memory
|
error: aborting due to 1 previous error
```
Implementing `PointerLike` for `UnsafeCell` enables the possibility of
interior mutable `dyn*` values. Since this means potentially exercising
new codegen behavior, I added a test for it in `tests/ui/dyn-star/cell.rs`.
Also updated UI tests to account for the `isize` implementation changing
error messages.
Delete `Rvalue::Len` 🎉
Everything's moved to `PtrMetadata`, so we can get rid of the `Len` variant now.
~~Depends on #134326, so draft until that lands~~ Ready!
r? mir
Asserts the maximum value that can be returned from `Vec::len`
Currently, casting `Vec<i32>` to `Vec<u32>` takes O(1) time:
```rust
// See <https://godbolt.org/z/hxq3hnYKG> for assembly output.
pub fn cast(vec: Vec<i32>) -> Vec<u32> {
vec.into_iter().map(|e| e as _).collect()
}
```
But the generated assembly is not the same as the identity function, which prevents us from casting `Vec<Vec<i32>>` to `Vec<Vec<u32>>` within O(1) time:
```rust
// See <https://godbolt.org/z/7n48bxd9f> for assembly output.
pub fn cast(vec: Vec<Vec<i32>>) -> Vec<Vec<u32>> {
vec.into_iter()
.map(|e| e.into_iter().map(|e| e as _).collect())
.collect()
}
```
This change tries to fix the problem. You can see the comparison here: <https://godbolt.org/z/jdManrKvx>.
In the playground the example program terminates with an unpredictable exit
code. The undefined behavior is also detected by miri:
error: Undefined Behavior: using uninitialized data
Document `PointerLike` implementation restrictions.
Since <https://github.com/rust-lang/rust/pull/133226>, it is no longer automatically implemented, but must be manually implemented, with special restrictions. The documentation now (roughly) explains those special restrictions.
cc `@compiler-errors` (author of the previous PR)
Rollup of 6 pull requests
Successful merges:
- #134364 (Use E0665 for missing `#[default]` on enum and update doc)
- #134601 (Support pretty-printing `dyn*` trait objects)
- #134603 (Explain why a type is not eligible for `impl PointerLike`.)
- #134618 (coroutine_clone: add comments)
- #134630 (Use `&raw` for `ptr` primitive docs)
- #134637 (Flatten effects directory now that it doesn't really test anything specific)
r? `@ghost`
`@rustbot` modify labels: rollup