pub trait Bitwise {
type Error;
// Required methods
fn get_bit(&self, bit: u16) -> Result<bool, Self::Error>;
fn cmp_bits(
a: &[u8],
b: &[u8],
from: &u16,
to: &u16,
) -> Result<Ordering, Self::Error>;
fn get_first_different_bit(a: &[u8], b: &[u8]) -> usize;
}Expand description
Trait that manages bitwise comparison operations on the implemented type.
§How can I implement Bitwise?
Bitwise requieres the methods get_bit, cmp_bits and get_first_different_bit to be implemented.
use std::cmp;
use std::cmp::Ordering;
pub trait Bitwise {
fn get_bit(&self, bit: u16) -> bool;
fn cmp_bits(a: &[u8], b: &[u8], from: &u16, to: &u16) -> Ordering;
fn get_first_different_bit(a: &[u8], b: &[u8]) -> usize;
}
impl Bitwise for [u8] {
fn get_bit(&self, bit: u16) -> bool {
if (bit / 8) >= self.len() as u16 {
panic!(
"Overflow [get_bit({:?}, {:?})]: Bit must be lower than {:?}.",
self,
bit,
self.len() * 8
);
}
(self[bit as usize / 8] & (1 << (7 - (bit % 8)))) > 0
}
fn cmp_bits(a: &[u8], b: &[u8], from: &u16, to: &u16) -> Ordering {
for depth in *from..*to {
if b.get_bit(depth) && !a.get_bit(depth) {
return Ordering::Less;
} else if !b.get_bit(depth) && a.get_bit(depth) {
return Ordering::Greater;
}
}
return Ordering::Equal;
}
fn get_first_different_bit(a: &[u8], b: &[u8]) -> usize {
let n = cmp::min(a.len(), b.len());
let mut bit: usize = 0;
for i in 0..n {
if a[i] != b[i] {
let xor = a[i] ^ b[i];
let lg_xor = 8 - xor.leading_zeros() - 1; // nbits - leading_zeros - 1 is equivalent to lg
bit += 7 - (lg_xor as usize);
return bit;
}
bit += 8;
}
bit
}
}Required Associated Types§
Required Methods§
Sourcefn cmp_bits(
a: &[u8],
b: &[u8],
from: &u16,
to: &u16,
) -> Result<Ordering, Self::Error>
fn cmp_bits( a: &[u8], b: &[u8], from: &u16, to: &u16, ) -> Result<Ordering, Self::Error>
Returns the and Ordering indicating wether self bits in the interval [from, to) is Higher, Lower or Equal than slice bits in the same interval.
§Arguments
a- The object that’s going to be compared.b- The object that’s going to be compare against.from- The index of the first bit to be compared (inclusive).to- The index of the last bit to be compared (exclusive).
§Panics
- If the
fromvalue is higher than the object length or thanto. - If the
tovalue is higher than the object length or lower thanfrom.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.