1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
pub mod builder;
pub mod error;
pub mod intermediate;
pub mod output;

pub use self::builder::Builder;
pub use self::error::Error;
pub use self::output::Output;


use fnv::FnvHashMap;
use std::slice;

use fst::error::Result;
use fst::intermediate::Intermediary;
use index::Index;


#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Stipe {
    pub check : u8,
    pub terminal : Terminal
}

/// Finality of a transition's destination state.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Terminal {
    /// The transition is not final.
    Not,
    /// The transition is final and leads to a state with no inner output.
    Empty,
    /// The transition is final and leads to a state with inner output.
    Inner
}

impl Terminal {
    #[inline] pub fn is(self) -> bool { self != Terminal::Not }
    #[inline] pub fn is_inner(self) -> bool { self == Terminal::Inner }
}

impl Default for Terminal {
    fn default() -> Terminal { Terminal::Not }
}


/// Hybrid Dart representation for a finite subsequential transducer.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct FST<I, O> where I : Index, O : Output {
    pub da : Dart<I, O>,
    pub state_output : FnvHashMap<I, O>
}

/// The double-array trie, holding the core state machine for the FST.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Dart<I, O> {
    pub stipe : Vec<Stipe>,
    pub next : Vec<I>,
    pub output : Vec<O>,
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct State<I> { pub index : I, pub terminal : Terminal }

impl<I, O> FST<I, O> where I : Index, O : Output {
    pub fn from_builder(builder : &builder::Builder<I, O>) -> Result<Self> {
        let mut repr = Intermediary::default();
        repr.from_builder(builder) ?;
        Ok(repr.into_dart())
    }

    /// Given a starting state and an input, returns the destination state, if any.
    pub fn transition(&self, state : I, input : u8) -> Option<State<I>> {
        let e = state.as_usize() + (1 + input as usize);
        match self.da.stipe.get(e) {
            Some(&Stipe { check, terminal })
                if check == input => Some(State { index: self.da.next[e], terminal: terminal }),
            _ => None
        }
    }

    /// Returns whether the key is present in the FST.
    pub fn contains<K>(&self, key : K) -> bool
        where K : AsRef<[u8]>
    {
        let mut state = State::default();
        for &label in key.as_ref() {
            let to = self.transition(state.index, label);
            match to {
                Some(s) => state = s,
                _ => return false
            }
        }

        state.terminal.is()
    }

    /// Get the value associated to the key, if any.
    pub fn get<K>(&self, key : K) -> Option<O>
        where K : AsRef<[u8]>
    {
        let mut out = O::zero();
        let mut state = I::zero();
        let mut terminal = self.da.stipe[0].terminal;
        for &label in key.as_ref() {
            let e = state.as_usize() + (1 + label as usize);
            let stipe = self.da.stipe.get(e);
            match stipe {
                Some(stipe) if stipe.check == label => {
                    terminal = stipe.terminal;
                    out.mappend_assign(self.da.output[e]);
                    state = self.da.next[e];
                },
                _ => return None
            }
        }

        match terminal {
            Terminal::Not   => None,
            Terminal::Empty => Some(out),
            Terminal::Inner => Some(out.mappend(self.state_output[&state]))
        }
    }

    /// Returns an iterator producing the values associated to all prefixes
    /// of the query, including the empty string and the query itself.
    pub fn reap<'a, 'q>(&'a self, query : &'q [u8]) -> Reaper<'a, 'q, I, O> {
        let root_output = match self.da.stipe[0].terminal {
            Terminal::Not   => None,
            Terminal::Empty => Some((0, O::zero())),
            Terminal::Inner => Some((0, self.state_output[&I::zero()]))
        };

        Reaper {
            query : query.into_iter(),
            position : 0,
            fst : &self,
            root_output : root_output,
            output : O::zero(),
            state : I::zero()
        }
    }

    /// Returns an iterator producing the values associated to all prefixes
    /// of the query, including the query itself but excluding the empty string.
    pub fn reap_past_root<'a, 'q>(&'a self, query : &'q [u8]) -> RootlessReaper<'a, 'q, I, O> {
        RootlessReaper {
            query : query.into_iter(),
            position : 0,
            fst : &self,
            output : O::zero(),
            state : I::zero()
        }
    }

    /// The number of nodes in the internal double array, including surplus.
    pub fn len(&self) -> usize {
        assert!(self.da.next.len() == self.da.stipe.len());
        assert!(self.da.next.len() == self.da.output.len());
        self.da.stipe.len()
    }

    fn resize(&mut self, length : usize) {
        self.da.stipe.resize(length, Stipe::default());
        self.da.next.resize(length, I::zero());
        self.da.output.resize(length, O::zero());
    }

    fn reserve(&mut self, n : usize) {
        self.da.stipe.reserve(n);
        self.da.next.reserve(n);
        self.da.output.reserve(n);
    }
}


#[derive(Clone, Debug)]
pub struct Reaper<'a, 'q, I, O>
    where I : Index + 'a
        , O : Output + 'a
{
    query : slice::Iter<'q, u8>,
    position : usize,
    fst : &'a FST<I, O>,
    root_output : Option<(usize, O)>,
    state : I,
    output : O
}


// FIXME: the root-skipping doppelgänger of `Reaper` exists solely because
// downstream users of `atlatl` appear to suffer an inscrutable performance
// penalty if they do not avail themselves to both.
//
// Surely something is amiss.
#[derive(Clone, Debug)]
pub struct RootlessReaper<'a, 'q, I, O>
    where I : Index + 'a
        , O : Output + 'a
{
    query : slice::Iter<'q, u8>,
    position : usize,
    fst : &'a FST<I, O>,
    state : I,
    output : O
}

impl<'a, 'q, I, O> Iterator for RootlessReaper<'a, 'q, I, O>
    where I : Index, O : Output
{
    type Item = (usize, O);

    fn next(&mut self) -> Option<Self::Item> {
        let mut terminal = Terminal::Not;
        let da = &self.fst.da;
        for &label in self.query.by_ref() {
            let e = self.state.as_usize() + (1 + label as usize);
            let stipe = da.stipe.get(e);
            match stipe {
                Some(stipe) if stipe.check == label => {
                    self.output.mappend_assign(da.output[e]);
                    self.state = da.next[e];
                    self.position += 1;
                    terminal = stipe.terminal;
                    if terminal.is() { break }
                },
                _ => return None
            }
        }

        match terminal {
            Terminal::Not   => None,
            Terminal::Empty => Some((self.position, self.output)),
            Terminal::Inner =>
                Some((self.position,
                      self.output.mappend(self.fst.state_output[&self.state])))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.query.len()))
    }
}

impl<'a, 'q, I, O> Iterator for Reaper<'a, 'q, I, O>
    where I : Index, O : Output
{
    type Item = (usize, O);

    fn next(&mut self) -> Option<Self::Item> {
        // The root output representing the empty prefix, if present, is always
        // the first match of any query.
        self.root_output.take()
            .or_else(|| {
                let mut terminal = Terminal::Not;
                let da = &self.fst.da;
                for &label in self.query.by_ref() {
                    let e = self.state.as_usize() + (1 + label as usize);
                    let stipe = da.stipe.get(e);
                    match stipe {
                        Some(stipe) if stipe.check == label => {
                            self.output.mappend_assign(da.output[e]);
                            self.state = da.next[e];
                            self.position += 1;
                            terminal = stipe.terminal;
                            if terminal.is() { break }
                        },
                        _ => return None
                    }
                }

                match terminal {
                    Terminal::Not   => None,
                    Terminal::Empty => Some((self.position, self.output)),
                    Terminal::Inner =>
                        Some((self.position,
                              self.output.mappend(self.fst.state_output[&self.state])))
                }
            })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let from_root = if self.root_output.is_some() { 1 } else { 0 };
        (from_root, Some(self.query.len() + from_root))
    }
}