aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: b286cb533c2dd3c2f02fc0fa49abef7a95da722c (plain)
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
pub mod consts;
pub mod lex;
pub mod parse;
mod utils;

use qp_trie::{
    wrapper::{BStr, BString},
    Iter, Trie,
};

pub struct Dict {
    inner: Trie<DictKey, DictValue>,
}

impl Dict {
    fn new() -> Self {
        Self { inner: Trie::new() }
    }

    fn insert(&mut self, entry: &'static str, value: DictValue) {
        let key = BString::from(entry);
        let dict_value = self.inner.entry(key).or_insert(Default::default());
        for v in value.defn.into_iter() {
            dict_value.defn.push(v);
        }
    }

    pub fn search<'a, 's>(&'a self, search_term: &'s str) -> SearchResults<'a> {
        SearchResults(self.inner.iter_prefix_str(search_term))
    }
}

pub struct SearchResults<'a>(Iter<'a, DictKey, DictValue>);

impl<'a> SearchResults<'a> {
    // mutable ref here to advance the iterator present in Self::Hit
    pub fn print(&mut self) {
        while let Some((key, value)) = self.0.next() {
            if value.defn.len() > 1 {
                for (def, idx) in value.defn.iter().zip(1..) {
                    println!("{}({}) {}", key.as_str(), idx, def.replace('\n', " "));
                }
            } else {
                println!("{} {}", key.as_str(), value.defn[0].replace('\n', " "));
            }
        }
    }
}

type DictKey = BString;

#[derive(Clone, Debug, Default)]
pub struct DictValue {
    defn: Vec<&'static str>,
    note: Option<&'static str>,
    synonym: Option<&'static str>,
}