use std::{cmp::Ordering, sync::OnceLock};
use icu_collator::{self, CollatorBorrowed};
use crate::i18n::{DEFAULT_LOCALE, get_collating_locale};
pub use icu_collator::options::{
AlternateHandling, CaseLevel, CollatorOptions, MaxVariable, Strength,
};
static COLLATOR: OnceLock<CollatorBorrowed> = OnceLock::new();
pub fn try_init_collator(opts: CollatorOptions) -> bool {
COLLATOR
.set(CollatorBorrowed::try_new(get_collating_locale().0.clone().into(), opts).unwrap())
.is_ok()
}
pub fn init_collator(opts: CollatorOptions) {
COLLATOR
.set(CollatorBorrowed::try_new(get_collating_locale().0.clone().into(), opts).unwrap())
.expect("Collator already initialized");
}
pub fn should_use_locale_collation() -> bool {
get_collating_locale().0 != DEFAULT_LOCALE
}
pub fn init_locale_collation() -> bool {
use crate::i18n::{UEncoding, get_locale_encoding};
if get_locale_encoding() != UEncoding::Utf8 {
return false;
}
let mut opts = CollatorOptions::default();
opts.alternate_handling = Some(AlternateHandling::Shifted);
try_init_collator(opts)
}
pub fn locale_cmp(left: &[u8], right: &[u8]) -> Ordering {
if get_collating_locale().0 == DEFAULT_LOCALE {
left.cmp(right)
} else {
COLLATOR
.get()
.map_or_else(|| left.cmp(right), |c| c.compare_utf8(left, right))
}
}