use super::Ruliad;
use crate::types::RuleVec;
use rstm_core::{Head, Rule, Tail};
use rstm_state::{RawState, State};
use alloc::vec::Vec;
impl<Q, S> Ruliad<Q, S>
where
Q: RawState,
{
pub const fn new() -> Self {
Self {
rules: RuleVec::new(),
}
}
pub fn from_rules<I>(iter: I) -> Self
where
I: IntoIterator<Item = Rule<Q, S>>,
{
Self {
rules: RuleVec::from_iter(iter),
}
}
pub const fn rules(&self) -> &RuleVec<Q, S> {
&self.rules
}
pub const fn rules_mut(&mut self) -> &mut RuleVec<Q, S> {
&mut self.rules
}
pub fn with_rules<I>(self, rules: I) -> Self
where
I: IntoIterator<Item = Rule<Q, S>>,
{
Self {
rules: Vec::from_iter(rules),
}
}
pub fn iter(&self) -> core::slice::Iter<'_, Rule<Q, S>> {
self.rules().iter()
}
pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, Rule<Q, S>> {
self.rules_mut().iter_mut()
}
pub fn get(&self, head: &Head<Q, S>) -> Option<&Tail<Q, S>>
where
Q: PartialEq,
S: PartialEq,
{
self.iter().find_map(|i| {
if i.head() == head {
Some(i.tail())
} else {
None
}
})
}
pub fn get_mut(&mut self, head: &Head<Q, S>) -> Option<&mut Tail<Q, S>>
where
Q: PartialEq,
S: PartialEq,
{
self.iter_mut().find_map(|i| {
if i.head() == head {
Some(i.tail_mut())
} else {
None
}
})
}
pub fn find_tail(&self, state: State<&Q>, symbol: &S) -> Option<&Tail<Q, S>>
where
Q: PartialEq,
S: PartialEq,
{
self.iter().find_map(|i| {
if i.head().view() == (Head { state, symbol }) {
Some(i.tail())
} else {
None
}
})
}
pub fn find_mut_tail(&mut self, head: Head<&Q, &S>) -> Option<&mut Tail<Q, S>>
where
Q: PartialEq,
S: PartialEq,
{
self.iter_mut().find_map(|i| {
if i.head().view() == head {
Some(i.tail_mut())
} else {
None
}
})
}
pub fn filter_by_state(&self, state: State<&Q>) -> Vec<&Rule<Q, S>>
where
Q: PartialEq,
S: PartialEq,
{
self.iter().filter(|i| *i.head() == state).collect()
}
}