use std::hash::{Hash, Hasher};
use failure::Fallible;
use crate::semirings::Semiring;
use crate::{Label, EPS_LABEL};
#[derive(PartialEq, Debug, Clone, PartialOrd)]
pub struct FstPath<W: Semiring> {
pub ilabels: Vec<Label>,
pub olabels: Vec<Label>,
pub weight: W,
}
impl<W: Semiring> FstPath<W> {
pub fn new(ilabels: Vec<Label>, olabels: Vec<Label>, weight: W) -> Self {
FstPath {
ilabels,
olabels,
weight,
}
}
pub fn add_to_path(&mut self, ilabel: Label, olabel: Label, weight: W) -> Fallible<()> {
if ilabel != EPS_LABEL {
self.ilabels.push(ilabel);
}
if olabel != EPS_LABEL {
self.olabels.push(olabel);
}
self.weight.times_assign(weight)
}
pub fn add_weight(&mut self, weight: W) -> Fallible<()> {
self.weight.times_assign(weight)
}
pub fn concat(&mut self, other: FstPath<W>) -> Fallible<()> {
self.ilabels.extend(other.ilabels);
self.olabels.extend(other.olabels);
self.weight.times_assign(other.weight)
}
}
impl<W: Semiring> Default for FstPath<W> {
fn default() -> Self {
FstPath {
ilabels: vec![],
olabels: vec![],
weight: W::one(),
}
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl<W: Semiring + Hash + Eq> Hash for FstPath<W> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.ilabels.hash(state);
self.olabels.hash(state);
self.weight.hash(state);
}
}
impl<W: Semiring + Hash + Eq> Eq for FstPath<W> {}
#[macro_export]
macro_rules! fst_path {
( $( $x:expr ),*) => {
{
fn semiring_one<W: Semiring>() -> W {
W::one()
}
FstPath::new(
vec![$($x),*],
vec![$($x),*],
semiring_one()
)
}
};
( $( $x:expr ),* => $( $y:expr ),* ) => {
{
fn semiring_one<W: Semiring>() -> W {
W::one()
}
FstPath::new(
vec![$($x),*],
vec![$($y),*],
semiring_one()
)
}
};
( $( $x:expr ),* ; $weight:expr) => {
{
fn semiring_new<W: Semiring>(v: W::Type) -> W {
W::new(v)
}
FstPath::new(
vec![$($x),*],
vec![$($x),*],
semiring_new($weight)
)
}
};
( $( $x:expr ),* => $( $y:expr ),* ; $weight:expr) => {
{
fn semiring_new<W: Semiring>(v: W::Type) -> W {
W::new(v)
}
FstPath::new(
vec![$($x),*],
vec![$($y),*],
semiring_new($weight)
)
}
};
}