Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(fst-dict): start implementing dictionary based around fst map

Grant Lemonsd9a159d8a8ec
diff --git a/harper-core/src/spell/fst_dictionary.rs b/harper-core/src/spell/fst_dictionary.rs
new file mode 100644
index 000000000..e3c749f94
--- /dev/null
+++ b/harper-core/src/spell/fst_dictionary.rs
@@ -0,0 +1,70 @@
+use std::fs::File;
+
+use fst::Map as FstMap;
+use memmap::Mmap;
+
+use super::hunspell::{parse_default_attribute_list, parse_default_word_list};
+use crate::{CharString, Lrc, WordMetadata};
+
+use super::Dictionary;
+
+#[derive(Debug, Clone)]
+pub struct FstDictionary {
+ /// Copied from [`super::FullDictionary`], not sure if rationale there holds here yet.
+ /// All English words
+ words: Vec<CharString>,
+ metadata: Vec<WordMetadata>,
+ /// Used for fuzzy-finding the index of words or metadata
+ word_map: FstMap<String>,
+}
+///
+/// The uncached function that is used to produce the original copy of the
+/// curated dictionary.
+fn uncached_inner_new() -> Lrc<FstDictionary> {
+ let word_list = parse_default_word_list().unwrap();
+ let attr_list = parse_default_attribute_list();
+
+ // There will be at _least_ this number of words
+ // This creates a memory map, which enables searching the map without loading
+ // all of it into memory.
+ let mmap = unsafe { Mmap::map(&File::open("../../dictionary.fst").unwrap()).unwrap() };
+ let word_map = FstMap::new(mmap).unwrap();
+
+ let mut words: Vec<CharString> = word_list.iter().map(|mw| mw.letters).collect();
+ words.sort();
+ words.dedup();
+
+ Lrc::new(FstDictionary {
+ words,
+ metadata,
+ word_map,
+ })
+}
+
+thread_local! {
+ static DICT: Lrc<FstDictionary> = uncached_inner_new();
+}
+
+impl Dictionary for FstDictionary {
+ fn contains_word(&self, word: &[char]) -> bool {
+ self.word_map.contains_key(word.iter().collect::<String>())
+ }
+
+ fn contains_word_str(&self, word: &str) -> bool {
+ self.word_map.contains_key(word)
+ }
+
+ fn words_iter(&self) -> impl Iterator<Item = &'_ [char]> {
+ self.words.iter().map(|v| v.as_slice())
+ }
+
+ fn get_word_metadata(&self, word: &[char]) -> WordMetadata {
+ let index: usize = self.word_map.get(word.iter().collect::<String>()).unwrap() as usize;
+ self.metadata[index]
+ }
+
+ fn get_word_metadata_str(&self, word: &str) -> WordMetadata {
+ let index: usize = self.word_map.get(word).unwrap() as usize;
+ self.metadata[index]
+ }
+}
diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rs
index 98161e8e7..2868eb082 100644
--- a/harper-core/src/spell/mod.rs
+++ b/harper-core/src/spell/mod.rs
@@ -7,6 +7,7 @@ pub use self::full_dictionary::FullDictionary;
pub use self::merged_dictionary::MergedDictionary;
mod dictionary;
+mod fst_dictionary;
mod full_dictionary;
mod hunspell;
mod merged_dictionary;