rustfst/
tr.rs

1use crate::semirings::SerializableSemiring;
2use crate::{Label, StateId};
3
4/// Structure representing a transition from a state to another state in a FST.
5#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
6pub struct Tr<W> {
7    /// Input label.
8    pub ilabel: Label,
9    /// Output label.
10    pub olabel: Label,
11    /// Weight.
12    pub weight: W,
13    /// ID of the next state.
14    pub nextstate: StateId,
15}
16
17impl<W> Tr<W> {
18    /// Creates a new Tr.
19    ///
20    /// # Example
21    ///
22    /// ```
23    /// # use rustfst::Tr;
24    /// # use rustfst::semirings::{TropicalWeight, Semiring};
25    /// let transition = Tr::<TropicalWeight>::new(0, 1, 1.3, 2);
26    ///
27    /// assert_eq!(transition.ilabel, 0);
28    /// assert_eq!(transition.olabel, 1);
29    /// assert_eq!(transition.weight, TropicalWeight::new(1.3));
30    /// assert_eq!(transition.nextstate, 2);
31    ///
32    /// ```
33    pub fn new<S: Into<W>>(ilabel: Label, olabel: Label, weight: S, nextstate: StateId) -> Self {
34        Tr {
35            ilabel,
36            olabel,
37            weight: weight.into(),
38            nextstate,
39        }
40    }
41
42    /// Updates the values of the attributes of the Tr from another Tr.
43    ///
44    /// # Example
45    ///
46    /// ```
47    /// # use rustfst::Tr;
48    /// # use rustfst::semirings::{Semiring, TropicalWeight};
49    /// let mut tr_1 = Tr::<TropicalWeight>::new(0, 1, 1.3, 2);
50    /// let tr_2 = Tr::new(1, 2, 1.2, 3);
51    ///
52    /// tr_1.set_value(&tr_2);
53    ///
54    /// assert_eq!(tr_1, tr_2);
55    /// ```
56    #[inline]
57    pub fn set_value(&mut self, tr: &Tr<W>)
58    where
59        W: std::clone::Clone,
60    {
61        self.ilabel = tr.ilabel;
62        self.olabel = tr.olabel;
63        self.weight = tr.weight.clone();
64        self.nextstate = tr.nextstate;
65    }
66}
67
68impl<W: SerializableSemiring> Tr<W> {
69    pub fn tr_type() -> String {
70        let weight_type = W::weight_type();
71        if weight_type.as_str() == "tropical" {
72            "standard".to_string()
73        } else {
74            weight_type
75        }
76    }
77}