Re: [PATCH v7 16/31] rust: ptr: add const_align_up()

From: Alice Ryhl

Date: Fri Mar 20 2026 - 05:47:25 EST


On Fri, Mar 20, 2026 at 10:27 AM David Rheinsberg <david@xxxxxxxxxxxx> wrote:
>
> Hi!
>
> On Fri, Mar 20, 2026, at 10:03 AM, Alice Ryhl wrote:
> > The Alignment type can only hold values that are a power of two.
>
> That solves my concern!
>
> Kinda off-topic: why doesn't `Alignment` store a u8 that represents the exponent, rather than the power? The left-shift when needing the power should be effectively free, shouldn't it? It would avoid all the unsafety in the impl.

For one, it mirrors the design of the unstable stdlib Alignment type.
For another, it'd make Alignment::of and similar a pain to implement.

> >> >> FYI, `core` provides `usize::checked_next_multiple_of()` ((const-)stable since 1.73). So an alternative would be:
> >> >>
> >> >> pub const fn const_align_up(value: usize, align: Alignment) -> Option<usize> {
> >> >> value.checked_next_multiple_of(align.as_usize())
> >> >> }
> >> >
> >> > That would return value+align when value is already aligned, which is wrong.
> >>
> >> You sure? (emphasis mine:)
> >>
> >> "Calculates the smallest value greater than or **EQUAL TO** self that is a multiple of rhs."
> >>
> >> assert_eq!(16_u64.next_multiple_of(8), 16);
> >
> > Okay, well, weird naming then.
>
> Do you need this helper then at all? I assume it is added because `Alignable` cannot be used in const. But it hard-codes `usize` as type, yet does not reflect that in the name. It comes down to which one is more readable, I guess:
>
> const_align_up(value, align)
> vs
> value.checked_next_multiple_of(align.as_usize())
>
> Meh, I don't mind too much. Just wanted to point out that the standard library provides this exactly.

The stdlib implementation probably invokes an expensive division
operation in place of our bitwise-and operation when the argument is
not a compile-time constant value.

Alice