wgpu_types/
math.rs

1//! Utility math functions.
2
3/// Trait for adjusting integers to the next multiple of an alignment.
4pub trait AlignTo: Copy {
5    /// Aligns `self` to `alignment`.
6    ///
7    /// Panics if doing so would overflow.
8    fn align_to(self, alignment: Self) -> Self;
9}
10
11macro_rules! impl_align_to {
12    ($ty:ty) => {
13        impl AlignTo for $ty {
14            fn align_to(self, alignment: Self) -> Self {
15                self.checked_next_multiple_of(alignment).unwrap()
16            }
17        }
18    };
19}
20
21impl_align_to!(u32);
22impl_align_to!(u64);
23impl_align_to!(usize);
24
25/// Aligns a `value` to an `alignment`.
26///
27/// Returns the first number greater than or equal to `value` that is also a
28/// multiple of `alignment`. If `value` is already a multiple of `alignment`,
29/// `value` will be returned.
30///
31/// # Panics
32///
33/// If aligning `value` to `alignment` would overflow.
34///
35/// # Examples
36///
37/// ```
38/// # use wgpu_types::math::align_to;
39/// assert_eq!(align_to(253_u32, 16), 256);
40/// assert_eq!(align_to(256_u32, 16), 256);
41/// assert_eq!(align_to(0_u32, 16), 0);
42/// ```
43///
44pub fn align_to<T: AlignTo>(value: T, alignment: T) -> T {
45    value.align_to(alignment)
46}