use core::{
any::TypeId,
ops::{
Bound,
Range,
RangeBounds,
},
};
use crate::{
order::BitOrder,
store::BitStore,
};
#[inline]
pub fn normalize_range<R>(bounds: R, end: usize) -> Range<usize>
where R: RangeBounds<usize> {
let min = match bounds.start_bound() {
Bound::Included(&n) => n,
Bound::Excluded(&n) => n + 1,
Bound::Unbounded => 0,
};
let max = match bounds.end_bound() {
Bound::Included(&n) => n + 1,
Bound::Excluded(&n) => n,
Bound::Unbounded => end,
};
min .. max
}
#[inline]
pub fn assert_range(range: Range<usize>, end: impl Into<Option<usize>>) {
if range.start > range.end {
panic!(
"Malformed range: `{} .. {}` must run from lower to higher",
range.start, range.end
);
}
if let Some(end) = end.into() {
if range.end > end {
panic!(
"Range out of bounds: `{} .. {}` must not exceed `{}`",
range.start, range.end, end
);
}
}
}
#[inline(always)]
pub fn match_order<O1, O2>() -> bool
where
O1: BitOrder,
O2: BitOrder,
{
TypeId::of::<O1>() == TypeId::of::<O2>()
}
#[inline(always)]
pub fn match_types<O1, T1, O2, T2>() -> bool
where
O1: BitOrder,
T1: BitStore,
O2: BitOrder,
T2: BitStore,
{
match_order::<O1, O2>() && TypeId::of::<T1>() == TypeId::of::<T2>()
}
#[cfg(all(test, feature = "std"))]
mod tests {
use std::panic::catch_unwind;
use super::*;
#[test]
fn check_range_asserts() {
assert!(catch_unwind(|| assert_range(7 .. 2, None)).is_err());
assert!(catch_unwind(|| assert_range(0 .. 8, 4)).is_err());
}
}