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
#![doc = include_str!("../README.md")]
#![no_std]
extern crate alloc;

use alloc::vec::Vec;

pub type Transition<K, J, OpV> = (K, J, J, OpV);

/// To represent empty trie entry.
/// Provided implementations for integer primitive types as `-1` represents None.
pub trait Optional: Copy {
    type Inner: Copy;

    fn none() -> Self;
    fn some(v: Self::Inner) -> Self;
    fn is_none(&self) -> bool;
    fn is_some(&self) -> bool { !self.is_none() }
    fn inner(&self) -> Option<Self::Inner>;
}

macro_rules! optional_uint {
    ($($ty:ty),+) => {
        $(
            impl Optional for $ty {
                type Inner = $ty;

                fn none() -> Self { !0 }

                fn some(v: Self::Inner) -> Self {
                    assert_ne!(v, Self::none());
                    v
                }

                fn is_none(&self) -> bool {
                    *self == Self::none()
                }

                fn inner(&self) -> Option<Self::Inner> {
                    if self.is_none() {
                        None
                    } else {
                        Some(*self)
                    }
                }
            }
        )+
    };
}

optional_uint! { u8, u16, u32, u64, u128, usize }

impl<T: Copy> Optional for Option<T> {
    type Inner = T;

    fn none() -> Self { None }
    fn some(v: Self::Inner) -> Self { Some(v) }
    fn is_none(&self) -> bool {
        self.is_none()
    }

    fn inner(&self) -> Option<Self::Inner> {
        *self
    }
}

/// Trie generator.
///
/// ```
/// # use transition_table::*;
/// const KEYWORDS: [(&'static str, i8); 3] = [
///     ("A", 1),
///     ("BB", 2),
///     ("BBC", 3),
/// ];
///
/// let tree = Entry::<char, _>::new(KEYWORDS.iter());
/// let tbl: Vec<Transition<_, _, _>> = tree.into();
/// let mut it = tbl.iter();
///
/// assert_eq!(it.next().unwrap(), &('C', 0usize, 0usize, 2usize));
/// assert_eq!(it.next().unwrap(), &('B', 0usize, 1usize, 1usize));
/// assert_eq!(it.next().unwrap(), &('A', 0usize, 0usize, 0usize));
/// assert_eq!(it.next().unwrap(), &('B', 1usize, 2usize, !0usize));
/// assert_eq!(it.next().unwrap(), &('\u{0}', 2usize, 4usize, !0usize));
/// assert!(it.next().is_none());
/// ```
pub struct Entry<K, V> {
    key: K,
    nexts: Vec<Self>,
    value: V,
}

macro_rules! impl_entry_new {
    ($key:ty, $iter:ident) => {
        impl Entry<$key, usize> {
            /// Reading const array, then creating tree structure to generate trie.
            pub fn new<'a, I, S, V>(src: I) -> Self
            where
                I: Iterator<Item = &'a (S, V)>,
                S: 'a + AsRef<str>,
                V: 'a,
            {
                src.enumerate().fold(
                    Self::default(),
                    |mut root, (i, (ref s, _))| {
                        root.push(s.as_ref().$iter(), i);
                        root
                    }
                )
            }
        }
    };
}

impl_entry_new! { char, chars }
impl_entry_new! { u8, bytes }

impl<K, V> Entry<K, V>
where
    K: Copy + Ord,
    V: Optional,
{
    /// Pushing a single entry.
    pub fn push<I>(&mut self, key: I, v: V::Inner)
    where
        I: IntoIterator<Item = K>
    {
        let mut it = key.into_iter();

        match it.next() {
            Some(c) => {
                let i = match self.nexts.binary_search_by_key(&c, |e| e.key) {
                    Ok(i) => i,
                    Err(i) => {
                        self.nexts.insert(i, Self {
                            key: c,
                            nexts: Vec::new(),
                            value: V::none(),
                        });
                        i
                    },
                };

                self.nexts[i].push(it, v)
            },
            None => self.value = V::some(v),
        }
    }

    /// Generating trie.
    pub fn push_to(&self, tbl: &mut Vec<Transition<K, usize, V>>) -> Transition<K, usize, V> {
        let mut v = self.nexts.iter().fold(
            Vec::new(),
            |mut v, child| {
                v.push(child.push_to(tbl));
                v
            }
        );
        let retval = (self.key, tbl.len(), tbl.len() + self.nexts.len(), self.value.clone());

        tbl.append(&mut v);
        retval
    }
}

impl<K, V> Default for Entry<K, V>
where
    K: Default,
    V: Optional,
{
    fn default() -> Self {
        Self {
            key: Default::default(),
            nexts: Vec::new(),
            value: V::none(),
        }
    }
}

impl<K, V> Into<Vec<Transition<K, usize, V>>> for Entry<K, V>
where
    K: Copy + Ord,
    V: Optional,
{
    fn into(self) -> Vec<Transition<K, usize, V>> {
        let mut tbl = Vec::new();
        let root = self.push_to(&mut tbl);

        tbl.push(root);
        tbl
    }
}