use crate::core::util::CoreHelper;
use crate::core::util::bit_util::BitUtil;
pub(crate) struct BKDUtil;
impl BKDUtil {
pub fn common_prefix_length8(a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> i32 {
let a_long = BitUtil::get_i64_le(a, a_offset);
let b_long = BitUtil::get_i64_le(b, b_offset);
let common_prefix_in_bits = (a_long ^ b_long).swap_bytes().leading_zeros();
(common_prefix_in_bits >> 3) as i32
}
pub fn common_prefix_length4(a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> i32 {
let a_int = BitUtil::get_i32_le(a, a_offset);
let b_int = BitUtil::get_i32_le(b, b_offset);
let common_prefix_in_bits = (a_int ^ b_int).swap_bytes().leading_zeros();
(common_prefix_in_bits >> 3) as i32
}
pub fn equals8(a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
let a_long = BitUtil::get_i64_le(a, a_offset);
let b_long = BitUtil::get_i64_le(b, b_offset);
a_long == b_long
}
pub fn equals4(a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
let a_int = BitUtil::get_i32_le(a, a_offset);
let b_int = BitUtil::get_i32_le(b, b_offset);
a_int == b_int
}
pub fn common_prefix_length_n(
a: &[u8],
a_offset: usize,
b: &[u8],
b_offset: usize,
num_bytes: usize,
) -> i32 {
let slice_a = &a[a_offset..a_offset + num_bytes];
let slice_b = &b[b_offset..b_offset + num_bytes];
let cmp = CoreHelper::miss_match_u8(slice_a, slice_b);
debug_assert!(num_bytes <= i32::MAX as usize);
if cmp == -1 { num_bytes as i32 } else { cmp }
}
}
pub trait ByteArrayPredicate {
fn test(&self, a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool;
}
pub struct Equals {
num_bytes: usize,
}
impl ByteArrayPredicate for Equals {
fn test(&self, a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
a[a_offset..a_offset + self.num_bytes] == b[b_offset..b_offset + self.num_bytes]
}
}
pub struct Equals8;
impl ByteArrayPredicate for Equals8 {
fn test(&self, a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
BKDUtil::equals8(a, a_offset, b, b_offset)
}
}
pub struct Equals4;
impl ByteArrayPredicate for Equals4 {
fn test(&self, a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
BKDUtil::equals4(a, a_offset, b, b_offset)
}
}
pub enum ByteArrayPredicateEnum {
Equals8(Equals8),
Equals4(Equals4),
Equals(Equals),
}
impl ByteArrayPredicate for ByteArrayPredicateEnum {
fn test(&self, a: &[u8], a_offset: usize, b: &[u8], b_offset: usize) -> bool {
match self {
ByteArrayPredicateEnum::Equals8(e) => e.test(a, a_offset, b, b_offset),
ByteArrayPredicateEnum::Equals4(e) => e.test(a, a_offset, b, b_offset),
ByteArrayPredicateEnum::Equals(e) => e.test(a, a_offset, b, b_offset),
}
}
}