use crate::core::index::BytesRef;
use crate::core::util::access::ByteSource;
use crate::core::util::comparator::Comparator;
use crate::core::util::error::lucene_error::Result;
pub trait BytesRefComparator<AV = Vec<u8>>: Comparator<BytesRef<AV>> {
fn byte_at(&self, _bytes_ref: &BytesRef<AV>, _i: usize) -> Result<i32>;
fn compare_with_offset(&self, o1: &BytesRef<AV>, o2: &BytesRef<AV>, k: usize) -> Result<i32> {
for i in k..self.compared_bytes_count() {
let b1 = self.byte_at(o1, i)?;
let b2 = self.byte_at(o2, i)?;
if b1 != b2 {
return Ok(b1 - b2);
} else if b1 == -1 {
break;
}
}
Ok(0)
}
fn compared_bytes_count(&self) -> usize;
}
pub struct Natural {
compared_bytes_count: usize,
}
impl Default for Natural {
fn default() -> Self {
Natural {
compared_bytes_count: i32::MAX as usize,
}
}
}
impl<AV: ByteSource> Comparator<BytesRef<AV>> for Natural {
const TYPE: &'static str = BYTES_REF_COMPARATOR_TYPE;
fn compare(&self, a: &BytesRef<AV>, b: &BytesRef<AV>) -> Result<i32> {
self.compare_with_offset(a, b, 0)
}
}
impl<AV: ByteSource> BytesRefComparator<AV> for Natural {
fn byte_at(&self, bytes_ref: &BytesRef<AV>, i: usize) -> Result<i32> {
if bytes_ref.length <= i {
Ok(-1)
} else {
Ok(bytes_ref.bytes.as_slice()[i + bytes_ref.offset] as i32)
}
}
fn compare_with_offset(&self, o1: &BytesRef<AV>, o2: &BytesRef<AV>, k: usize) -> Result<i32> {
let start1 = o1.offset + k;
let start2 = o2.offset + k;
let slice1 = &o1.bytes.as_slice()[start1..(o1.offset + o1.length)];
let slice2 = &o2.bytes.as_slice()[start2..(o2.offset + o2.length)];
Ok(match slice1.cmp(slice2) {
std::cmp::Ordering::Less => -1,
std::cmp::Ordering::Equal => 0,
std::cmp::Ordering::Greater => 1,
})
}
fn compared_bytes_count(&self) -> usize {
self.compared_bytes_count
}
}
pub const BYTES_REF_COMPARATOR_TYPE: &str = "BytesRefComparator";