Description
Proposal
Problem statement
The align_to
slice method is only useful for optimizations that want to process all elements of the original slice, but has an optimized path for larger or more-aligned elements. The function may fall back to not producing a middle (aligned) slice and instead just return the original slice in the head or tail slice (for which, according to align_to
's docs, an implementation must exist).
There are many users in the ecosystem that use it for guaranteed alignment, which, while working most of the time, is not guaranteed by the API.
Related discussion: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/align_to.20and.20other.20APIs.20with.20surprising.20const.20behavior
Motivation, use-cases
When you have a slice to primitives (like integers), it is sometimes convenient to convert said slice to a smaller or larger primitive. Especially common are conversions to and from [u8]
.
Solution sketches
Add two new slice methods (plus their mut
counterparts):
aligned_subslice
: Get a subslice where the first element is aligned to a given alignment and the size of the slice is a multiple of the alignment.transmute_elements
:- Transmute the slice elements to another type.
- If the target element type is smaller than the source element type, the returned slice will have multiple elements per element of the original slice.
- Cannot be used to go to an element type with higher alignment requirements. Use
aligned_subslice
for that instead.
Alternatives:
We can also remove the fuzziness of the align_to
method, but that would mean it could never be used in const eval.
Links and related work
- Add stronger alternatives to
align_to
rust#105296 implements this change
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.