diff options
| author | John Hubbard <jhubbard@nvidia.com> | 2026-03-25 18:38:47 -0700 |
|---|---|---|
| committer | Miguel Ojeda <ojeda@kernel.org> | 2026-04-03 11:57:35 +0200 |
| commit | 0a51b384e0decfe9dfe65d721a5e9cd39cabc152 (patch) | |
| tree | 305cc707719ddca5307408ddd6cfbfca16ce5c0a /rust/kernel | |
| parent | 7ccef29b5d93d6e235dc8ace27cfbbfbbede9908 (diff) | |
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>
Diffstat (limited to 'rust/kernel')
| -rw-r--r-- | rust/kernel/ptr.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs index 512e2eabe3ad..c7788656a162 100644 --- a/rust/kernel/ptr.rs +++ b/rust/kernel/ptr.rs @@ -225,3 +225,32 @@ macro_rules! impl_alignable_uint { } impl_alignable_uint!(u8, u16, u32, u64, usize); + +/// Aligns `value` up to `align`. +/// +/// This is the const-compatible equivalent of [`Alignable::align_up`]. +/// +/// Returns [`None`] on overflow. +/// +/// # Examples +/// +/// ``` +/// use kernel::{ +/// ptr::{ +/// const_align_up, +/// Alignment, // +/// }, +/// sizes::SZ_4K, // +/// }; +/// +/// assert_eq!(const_align_up(0x4f, Alignment::new::<16>()), Some(0x50)); +/// assert_eq!(const_align_up(0x40, Alignment::new::<16>()), Some(0x40)); +/// assert_eq!(const_align_up(1, Alignment::new::<SZ_4K>()), Some(SZ_4K)); +/// ``` +#[inline(always)] +pub const fn const_align_up(value: usize, align: Alignment) -> Option<usize> { + match value.checked_add(align.as_usize() - 1) { + Some(v) => Some(v & align.mask()), + None => None, + } +} |
