use crate::BitError;
#[inline] pub const fn is_power_of_two(v: usize) -> bool { v != 0 && (v & v.wrapping_sub(1)) == 0 }
#[inline]
const fn check(a: usize) -> Result<(), BitError> {
if a == 0 { Err(BitError::AlignmentZero) }
else if !is_power_of_two(a) { Err(BitError::AlignmentNotPowerOfTwo) }
else { Ok(()) }
}
#[inline]
pub const fn is_aligned(v: usize, a: usize) -> Result<bool, BitError> {
match check(a) { Ok(()) => Ok((v & (a - 1)) == 0), Err(e) => Err(e) }
}
#[inline]
pub const fn down(v: usize, a: usize) -> Result<usize, BitError> {
match check(a) { Ok(()) => Ok(v & !(a - 1)), Err(e) => Err(e) }
}
#[inline]
pub const fn up(v: usize, a: usize) -> Result<usize, BitError> {
match check(a) {
Ok(()) => match v.checked_add(a - 1) {
Some(s) => Ok(s & !(a - 1)),
None => Err(BitError::Overflow),
},
Err(e) => Err(e),
}
}
#[inline]
pub const fn padding(v: usize, a: usize) -> Result<usize, BitError> {
match check(a) { Ok(()) => Ok(v.wrapping_neg() & (a - 1)), Err(e) => Err(e) }
}