mirror of
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
synced 2026-05-16 02:01:18 -04:00
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>
This commit is contained in:
committed by
Miguel Ojeda
parent
7ccef29b5d
commit
0a51b384e0
@@ -225,3 +225,32 @@ fn align_up(self, alignment: Alignment) -> Option<Self> {
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user