Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN

From: Alice Ryhl
Date: Wed Jul 16 2025 - 05:46:32 EST


On Tue, Jul 15, 2025 at 4:19 PM Danilo Krummrich <dakr@xxxxxxxxxx> wrote:
>
> On Tue Jul 15, 2025 at 3:46 PM CEST, Alice Ryhl wrote:
> > diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
> > index bffe72f44cb33a265018e67d92d9f0abe82f8e22..fd3f1e0b9c3b3437fb50d8f1b28c92bc7cefd565 100644
> > --- a/rust/kernel/alloc/kbox.rs
> > +++ b/rust/kernel/alloc/kbox.rs
> > @@ -400,12 +400,19 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
> > }
> >
> > // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
> > -// pointer to `T`.
> > +// pointer to `T` allocated by `A`.
> > unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
> > where
> > A: Allocator,
> > {
> > - const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
> > + const FOREIGN_ALIGN: usize = {
> > + let mut align = core::mem::align_of::<T>();
> > + if align < A::MIN_ALIGN {
> > + align = A::MIN_ALIGN;
> > + }
> > + align
> > + };
>
> Pretty unfortunate that core::cmp::max() can't be used from const context. :(
>
> What do you think about
>
> const FOREIGN_ALIGN: usize =
> if core::mem::align_of::<T>() < A::MIN_ALIGN {
> A::MIN_ALIGN
> } else {
> core::mem::align_of::<T>()
> };
>
> instead? I think that reads a bit better.

I don't mind doing that instead.

Alice