use bstr::{ByteSlice, B};
use lru::LruCache;
use std::cmp::Ordering;
use tinyvec::ArrayVec;
use crate::ascii::try_ascii;
use crate::cea_utils::get_cea;
use crate::first_weight::try_initial;
use crate::normalize::make_nfd;
use crate::prefix::trim_prefix;
use crate::sort_key::compare_incremental;
use crate::Tailoring;
#[derive(Debug)]
pub struct Collator {
pub tailoring: Tailoring,
pub shifting: bool,
cache: LruCache<Vec<u32>, Vec<ArrayVec<[u16; 4]>>>,
}
impl Default for Collator {
fn default() -> Self {
Self::new(Tailoring::default(), true)
}
}
impl Collator {
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn new(tailoring: Tailoring, shifting: bool) -> Self {
Self {
tailoring,
shifting,
cache: LruCache::new(std::num::NonZeroUsize::new(128).unwrap()),
}
}
pub fn collate<T: AsRef<[u8]> + Eq + Ord + ?Sized>(&mut self, a: &T, b: &T) -> Ordering {
if a == b {
return Ordering::Equal;
}
let mut a_chars: Vec<u32> = B(a).chars().map(|c| c as u32).collect();
let mut b_chars: Vec<u32> = B(b).chars().map(|c| c as u32).collect();
if let Some(o) = try_ascii(&a_chars, &b_chars) {
return o;
}
make_nfd(&mut a_chars);
make_nfd(&mut b_chars);
if a_chars == b_chars {
return a.cmp(b);
}
trim_prefix(&mut a_chars, &mut b_chars, self.shifting);
if a_chars.is_empty() || b_chars.is_empty() {
return a_chars.cmp(&b_chars);
}
if let Some(o) = try_initial(&a_chars, &b_chars, self) {
return o;
}
let a_cea = get_cea(&mut a_chars, self);
let b_cea = get_cea(&mut b_chars, self);
let comparison = compare_incremental(&a_cea, &b_cea, self.shifting);
if comparison == Ordering::Equal {
return a.cmp(b);
}
comparison
}
pub fn collate_no_tiebreak<T: AsRef<[u8]> + Eq + Ord + ?Sized>(
&mut self,
a: &T,
b: &T,
) -> Ordering {
if a == b {
return Ordering::Equal;
}
let mut a_chars: Vec<u32> = B(a).chars().map(|c| c as u32).collect();
let mut b_chars: Vec<u32> = B(b).chars().map(|c| c as u32).collect();
if let Some(o) = try_ascii(&a_chars, &b_chars) {
return o;
}
make_nfd(&mut a_chars);
make_nfd(&mut b_chars);
if a_chars == b_chars {
return Ordering::Equal;
}
trim_prefix(&mut a_chars, &mut b_chars, self.shifting);
if a_chars.is_empty() || b_chars.is_empty() {
return a_chars.cmp(&b_chars);
}
if let Some(o) = try_initial(&a_chars, &b_chars, self) {
return o;
}
let a_cea = get_cea(&mut a_chars, self);
let b_cea = get_cea(&mut b_chars, self);
compare_incremental(&a_cea, &b_cea, self.shifting)
}
pub(crate) fn get_cache(&mut self, word: &[u32]) -> Option<&Vec<ArrayVec<[u16; 4]>>> {
self.cache.get(word)
}
pub(crate) fn put_cache(&mut self, word: Vec<u32>, cea: Vec<ArrayVec<[u16; 4]>>) {
self.cache.put(word, cea);
}
}