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

use std::fmt;

use radix_trie::{Trie, TrieCommon};

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

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

    fn insert(&mut self, entry: DictKey, value: DictValue) {
        self.inner.map_with_default(
            entry,
            |dict_value| {
                // TODO: this only merges defns, not notes/syns
                for v in value.defn.iter() {
                    dict_value.defn.push(v);
                }
            },
            value.clone(),
        );
    }

    pub fn search<'dict, 'search>(
        &'dict self,
        search_term: &'search str,
    ) -> SearchResults<'dict, 'search> {
        self.inner
            .subtrie(search_term)
            .map_or(SearchResults::Empty, |subtrie| {
                SearchResults::Hit(subtrie.iter())
            })
    }
}

pub enum SearchResults<'dict, 'search> {
    Empty,
    Hit(radix_trie::iter::Iter<'dict, &'search str, DictValue>),
}

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

                    // if let Some(note) = value.note {
                    //     print!("\t{}", note);
                    // }
                    // if let Some(synonym) = value.synonym {
                    //     print!("\t{}", synonym);
                    // }
                }
            }
            Self::Empty => (),
        }
    }
}

type DictKey = &'static str;

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