Skip to content

Commit 0a51b38

Browse files
johnhubbardojeda
authored andcommitted
rust: ptr: add const_align_up()
Add const_align_up() to kernel::ptr as the const-compatible equivalent of Alignable::align_up(). Suggested-by: Danilo Krummrich <dakr@kernel.org> Suggested-by: Gary Guo <gary@garyguo.net> Suggested-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Signed-off-by: John Hubbard <jhubbard@nvidia.com> Reviewed-by: Alexandre Courbot <acourbot@nvidia.com> Link: https://patch.msgid.link/20260326013902.588242-17-jhubbard@nvidia.com [ Adjusted imports style. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 7ccef29 commit 0a51b38

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

rust/kernel/ptr.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,32 @@ macro_rules! impl_alignable_uint {
225225
}
226226

227227
impl_alignable_uint!(u8, u16, u32, u64, usize);
228+
229+
/// Aligns `value` up to `align`.
230+
///
231+
/// This is the const-compatible equivalent of [`Alignable::align_up`].
232+
///
233+
/// Returns [`None`] on overflow.
234+
///
235+
/// # Examples
236+
///
237+
/// ```
238+
/// use kernel::{
239+
/// ptr::{
240+
/// const_align_up,
241+
/// Alignment, //
242+
/// },
243+
/// sizes::SZ_4K, //
244+
/// };
245+
///
246+
/// assert_eq!(const_align_up(0x4f, Alignment::new::<16>()), Some(0x50));
247+
/// assert_eq!(const_align_up(0x40, Alignment::new::<16>()), Some(0x40));
248+
/// assert_eq!(const_align_up(1, Alignment::new::<SZ_4K>()), Some(SZ_4K));
249+
/// ```
250+
#[inline(always)]
251+
pub const fn const_align_up(value: usize, align: Alignment) -> Option<usize> {
252+
match value.checked_add(align.as_usize() - 1) {
253+
Some(v) => Some(v & align.mask()),
254+
None => None,
255+
}
256+
}

0 commit comments

Comments
 (0)