use core::result;
use crate::{
error::{Error, Result},
format::{
fst::{WordFst, build_fst_presorted},
header::compute_checksum,
},
plc::feature::MAX_WORD_CHAR,
script::{self, ScriptClass},
};
const DICT_MAGIC: [u8; 4] = *b"MDCT";
const DICT_VERSION: u8 = 1;
const DICT_HEADER_SIZE: usize = 32;
const FLAG_HAS_MIXED_SCRIPT: u8 = 1 << 0;
#[derive(Clone, Copy, Debug)]
pub struct UserDict<'a> {
raw: &'a [u8],
fst: WordFst<'a>,
max_word_char: usize,
mixed_script: bool,
}
#[derive(Clone, Debug)]
pub struct OwnedUserDict {
byte_li: Vec<u8>,
}
impl<'a> UserDict<'a> {
pub const fn empty() -> Self {
Self {
raw: &[],
fst: WordFst::empty(),
max_word_char: 0,
mixed_script: false,
}
}
pub fn from_slice(slice: &'a [u8]) -> Result<Self> {
if slice.len() < DICT_HEADER_SIZE {
return Err(Error::InvalidModel {
reason: "dictionary shorter than 32-byte header",
});
}
if slice[0..4] != DICT_MAGIC {
return Err(Error::InvalidModel {
reason: "bad dictionary magic header",
});
}
if slice[4] != DICT_VERSION {
return Err(Error::InvalidModel {
reason: "unsupported dictionary format version",
});
}
let flag = slice[5];
if (flag & !FLAG_HAS_MIXED_SCRIPT) != 0 || slice[7] != 0 || slice[20..32] != [0u8; 12] {
return Err(Error::InvalidModel {
reason: "unsupported dictionary flags or reserved bytes",
});
}
let max_word_char = slice[6] as usize;
if max_word_char > MAX_WORD_CHAR {
return Err(Error::InvalidModel {
reason: "dictionary max_word_char exceeds limit",
});
}
let word_count = u32::from_le_bytes([slice[8], slice[9], slice[10], slice[11]]);
let fst_len = u32::from_le_bytes([slice[12], slice[13], slice[14], slice[15]]);
let checksum = u32::from_le_bytes([slice[16], slice[17], slice[18], slice[19]]);
let total = (DICT_HEADER_SIZE as u64)
.checked_add(u64::from(fst_len))
.ok_or(Error::InvalidModel {
reason: "dictionary length overflow",
})?;
if total != slice.len() as u64 {
return Err(Error::InvalidModel {
reason: "dictionary byte length mismatch",
});
}
let payload = &slice[DICT_HEADER_SIZE..];
if checksum != compute_checksum(&slice[0..16], payload) {
return Err(Error::InvalidModel {
reason: "dictionary checksum mismatch",
});
}
let fst = WordFst::from_slice(payload)?;
if fst.word_count() != word_count {
return Err(Error::InvalidModel {
reason: "dictionary word count mismatch",
});
}
Ok(Self {
raw: slice,
fst,
max_word_char,
mixed_script: (flag & FLAG_HAS_MIXED_SCRIPT) != 0,
})
}
pub const fn as_slice(&self) -> &'a [u8] {
self.raw
}
pub const fn fst(&self) -> WordFst<'a> {
self.fst
}
pub const fn word_count(&self) -> u32 {
self.fst.word_count()
}
pub const fn is_empty(&self) -> bool {
self.fst.is_empty()
}
pub const fn max_word_char(&self) -> usize {
self.max_word_char
}
pub(crate) const fn has_mixed_script(&self) -> bool {
self.mixed_script
}
pub const fn memory_usage(&self) -> usize {
self.raw.len()
}
}
impl OwnedUserDict {
pub fn from_text(text: &str) -> Result<Self> {
let mut word_li: Vec<&[u8]> = Vec::new();
let mut max_word_char = 0usize;
let mut mixed_script = false;
for (idx, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let word = match line.split_once('\t') {
Some((w, _)) => w.trim(),
None => line,
};
register_word(idx + 1, word, &mut max_word_char, &mut mixed_script)?;
word_li.push(word.as_bytes());
}
Ok(Self {
byte_li: encode_dict(word_li, max_word_char, mixed_script),
})
}
pub fn from_word_li<I, S>(iter: I) -> Result<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let iter = iter.into_iter();
let (lower, _) = iter.size_hint();
let mut item_li: Vec<S> = Vec::with_capacity(lower);
let mut max_word_char = 0usize;
let mut mixed_script = false;
for (idx, item) in iter.enumerate() {
let word = item.as_ref().trim();
register_word(idx + 1, word, &mut max_word_char, &mut mixed_script)?;
item_li.push(item);
}
let word_li: Vec<&[u8]> = item_li
.iter()
.map(|s| s.as_ref().trim().as_bytes())
.collect();
Ok(Self {
byte_li: encode_dict(word_li, max_word_char, mixed_script),
})
}
pub fn from_vec(byte_li: Vec<u8>) -> Result<Self> {
let _ = UserDict::from_slice(&byte_li)?;
Ok(Self { byte_li })
}
pub fn as_dict(&self) -> UserDict<'_> {
UserDict::from_slice(&self.byte_li).expect("owned user dict already validated")
}
pub fn as_slice(&self) -> &[u8] {
&self.byte_li
}
pub fn into_vec(self) -> Vec<u8> {
self.byte_li
}
pub fn word_count(&self) -> u32 {
u32::from_le_bytes([
self.byte_li[8],
self.byte_li[9],
self.byte_li[10],
self.byte_li[11],
])
}
pub fn is_empty(&self) -> bool {
self.word_count() == 0
}
pub fn max_word_char(&self) -> usize {
self.byte_li[6] as usize
}
pub fn memory_usage(&self) -> usize {
self.byte_li.capacity()
}
}
fn encode_dict(mut word_li: Vec<&[u8]>, max_word_char: usize, mixed_script: bool) -> Vec<u8> {
word_li.sort_unstable();
word_li.dedup();
let count = word_li.len();
let fst_buf = build_fst_presorted(word_li, count);
let flag = if mixed_script {
FLAG_HAS_MIXED_SCRIPT
} else {
0
};
let word_count = u32::try_from(count).expect("dict word count fits u32");
let fst_len = u32::try_from(fst_buf.len()).expect("dict fst fits u32");
let mut out = vec![0u8; DICT_HEADER_SIZE + fst_buf.len()];
out[0..4].copy_from_slice(&DICT_MAGIC);
out[4] = DICT_VERSION;
out[5] = flag;
out[6] = max_word_char as u8;
out[7] = 0;
out[8..12].copy_from_slice(&word_count.to_le_bytes());
out[12..16].copy_from_slice(&fst_len.to_le_bytes());
let checksum = compute_checksum(&out[0..16], &fst_buf);
out[16..20].copy_from_slice(&checksum.to_le_bytes());
out[DICT_HEADER_SIZE..].copy_from_slice(&fst_buf);
out
}
fn register_word(
line: usize,
word: &str,
max_word_char: &mut usize,
mixed_script: &mut bool,
) -> Result<()> {
let char_len = validate_word(word).map_err(|reason| Error::InvalidDictionary { line, reason })?;
*max_word_char = (*max_word_char).max(char_len);
*mixed_script |= is_mixed_word(word);
Ok(())
}
pub(crate) fn is_mixed_word(word: &str) -> bool {
let mut first: Option<ScriptClass> = None;
for ch in word.chars() {
if script::is_combining_mark(ch) {
continue;
}
let cls = match script::class(ch) {
ScriptClass::OtherAlpha => ScriptClass::Latin,
other => other,
};
match first {
None => first = Some(cls),
Some(prev) if prev != cls => return true,
_ => {}
}
}
false
}
fn validate_word(word: &str) -> result::Result<usize, &'static str> {
if word.is_empty() {
return Err("empty word");
}
let mut char_len = 0usize;
for ch in word.chars() {
if ch.is_whitespace() {
return Err("word contains whitespace");
}
char_len += 1;
}
if char_len > MAX_WORD_CHAR {
return Err("word exceeds 32 characters");
}
Ok(char_len)
}