watto/
utils.rs

1/// Essentially re-implements nightly-only [`ptr::is_aligned_to`].
2///
3/// See:
4/// https://doc.rust-lang.org/core/primitive.pointer.html#method.is_aligned_to
5pub(crate) fn is_aligned_to(bytes: &[u8], align: usize) -> bool {
6    if !align.is_power_of_two() {
7        panic!("is_aligned_to: align is not a power-of-two");
8    }
9
10    bytes.as_ptr() as usize & (align - 1) == 0
11}
12
13/// Splits the given `bytes` into padding and a slice that is properly aligned
14/// to `align` bytes.
15///
16/// Returns [`None`] when `bytes` is not large enough.
17pub fn align_to(bytes: &[u8], align: usize) -> Option<(&[u8], &[u8])> {
18    let offset = bytes.as_ptr().align_offset(align);
19
20    if bytes.len() < offset {
21        return None;
22    }
23
24    Some(bytes.split_at(offset))
25}
26
27/// Splits the given `bytes` into padding and a slice that is properly aligned
28/// for `T`.
29///
30/// Returns [`None`] when `bytes` is not large enough.
31pub fn align_to_type<T>(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
32    align_to(bytes, core::mem::align_of::<T>())
33}