bit-length helper for integers and byte slices
This commit is contained in:
parent
6ba146f565
commit
d9e6d99286
36
src/lib.rs
36
src/lib.rs
|
@ -37,3 +37,39 @@ pub fn tokenize<'a>(
|
||||||
> {
|
> {
|
||||||
lexer::Tokenizer::new_with_errors(bytes)
|
lexer::Tokenizer::new_with_errors(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
trait BitSize {
|
||||||
|
fn bits(&self) -> u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! impl_bitsize_int {
|
||||||
|
($($ty:ty)*) => {
|
||||||
|
|
||||||
|
$(
|
||||||
|
impl BitSize for $ty {
|
||||||
|
fn bits(&self) -> u32 {
|
||||||
|
Self::BITS as u32 - self.trailing_zeros() as u32
|
||||||
|
}
|
||||||
|
})*
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl_bitsize_int!(u8 u16 u32 u64 u128);
|
||||||
|
|
||||||
|
impl BitSize for &[u8] {
|
||||||
|
fn bits(&self) -> u32 {
|
||||||
|
let bytes = self.as_ref();
|
||||||
|
let mut bits = bytes.len() * u8::BITS as usize;
|
||||||
|
|
||||||
|
for &d in bytes.iter().rev() {
|
||||||
|
if d == 0 {
|
||||||
|
bits -= u8::BITS as usize;
|
||||||
|
} else {
|
||||||
|
bits -= d.leading_zeros() as usize;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bits as u32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue