use crate::core::util::accountable::Accountable;
use crate::core::util::automation::automaton::Automaton;
use crate::core::util::automation::byte_runnable::ByteRunnable;
use crate::core::util::automation::operations::Operations;
use crate::core::util::automation::run_automaton::RunAutomaton;
use crate::core::util::automation::utf32_to_utf8::UTF32ToUTF8;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use std::borrow::Cow;
use std::hash::{Hash, Hasher};
#[derive(Clone)]
pub struct ByteRunAutomaton {
pub base: RunAutomaton,
}
impl ByteRunAutomaton {
pub fn with_bool(a: Automaton, is_binary: bool) -> Result<Self> {
let automaton = if is_binary {
a
} else {
match Self::convert(&a)? {
Cow::Borrowed(_) => a,
Cow::Owned(o) => o,
}
};
Ok(ByteRunAutomaton {
base: RunAutomaton::new(automaton, 256)?,
})
}
pub fn new(a: Automaton) -> Result<Self> {
Self::with_bool(a, false)
}
fn convert(a: &Automaton) -> Result<Cow<'_, Automaton>> {
if !a.is_deterministic() {
return Err(LuceneError::illegal_argument(
"Automaton must be deterministic",
));
}
let converted = UTF32ToUTF8::default().convert(a)?;
match Operations::determinize(&converted, i32::MAX as usize)? {
Cow::Borrowed(_) => Ok(converted),
Cow::Owned(o) => Ok(Cow::Owned(o)),
}
}
}
impl ByteRunnable for ByteRunAutomaton {
fn step(&mut self, state: i32, c: i32) -> Result<i32> {
Ok(self.base.step(state, c))
}
fn is_accept(&self, state: i32) -> Result<bool> {
self.base.is_accept(state)
}
fn get_size(&self) -> usize {
self.base.size()
}
}
impl Accountable for ByteRunAutomaton {
fn ram_bytes_used(&self) -> Result<i64> {
self.base.ram_bytes_used()
}
}
impl PartialEq for ByteRunAutomaton {
fn eq(&self, other: &Self) -> bool {
self.base.eq(&other.base)
}
}
impl Eq for ByteRunAutomaton {}
impl Hash for ByteRunAutomaton {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.base.hash(state)
}
}