Timur Tabi
2025-May-01 15:19 UTC
[PATCH v2 17/21] rust: num: Add an upward alignment helper for usize
On Thu, 2025-05-01 at 21:58 +0900, Alexandre Courbot wrote:> +impl UsizeAlign for usize { > +??? fn align_up(mut self, align: usize) -> usize { > +??????? self = (self + align - 1) & !(align - 1); > +??????? self > +??? } > +} > + > +/// Aligns `val` upwards to the nearest multiple of `align`. > +pub const fn usize_align_up(val: usize, align: usize) -> usize { > +??? (val + align - 1) & !(align - 1) > +}Why not have usize_align_up() just return "val.align_up(align)"? But why why two versions at all? Is there any context where you could use one and not the other?
Joel Fernandes
2025-May-01 15:22 UTC
[PATCH v2 17/21] rust: num: Add an upward alignment helper for usize
On 5/1/2025 11:19 AM, Timur Tabi wrote:> On Thu, 2025-05-01 at 21:58 +0900, Alexandre Courbot wrote: > > >> +impl UsizeAlign for usize { >> +??? fn align_up(mut self, align: usize) -> usize { >> +??????? self = (self + align - 1) & !(align - 1); >> +??????? self >> +??? } >> +} >> + >> +/// Aligns `val` upwards to the nearest multiple of `align`. >> +pub const fn usize_align_up(val: usize, align: usize) -> usize { >> +??? (val + align - 1) & !(align - 1) >> +} > > Why not have usize_align_up() just return "val.align_up(align)"? > > But why why two versions at all? Is there any context where you could use one > and not the other? >I can't remember now but when I tried that, I got compiler errors (because val is immutable?). Also not mutating it like that matches the pattern in the rest of this file so I'd leave it as-is. Thanks.
Timur Tabi
2025-May-01 15:31 UTC
[PATCH v2 17/21] rust: num: Add an upward alignment helper for usize
On Thu, 2025-05-01 at 11:22 -0400, Joel Fernandes wrote:> Also not mutating it like that matches the pattern in the rest of this file > so > I'd leave it as-is.Oh I see now. One version changes a variable, and the other returns a new value.
Alexandre Courbot
2025-May-01 21:02 UTC
[PATCH v2 17/21] rust: num: Add an upward alignment helper for usize
On Fri May 2, 2025 at 12:19 AM JST, Timur Tabi wrote:> On Thu, 2025-05-01 at 21:58 +0900, Alexandre Courbot wrote: > > >> +impl UsizeAlign for usize { >> +??? fn align_up(mut self, align: usize) -> usize { >> +??????? self = (self + align - 1) & !(align - 1); >> +??????? self >> +??? } >> +} >> + >> +/// Aligns `val` upwards to the nearest multiple of `align`. >> +pub const fn usize_align_up(val: usize, align: usize) -> usize { >> +??? (val + align - 1) & !(align - 1) >> +} > > Why not have usize_align_up() just return "val.align_up(align)"? > > But why why two versions at all? Is there any context where you could use one > and not the other?The second version can be used in const context to create values at compile-time, something the first one cannot do. If we want to factorize things out we can probably make the first version call the second one though.