Skip to content

Commit

Permalink
Add an example for checking from a given dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
the-mikedavis committed Aug 21, 2023
1 parent 37c012f commit 2d83f72
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions .helix/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
editor.workspace-lsp-roots = ["examples"]
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ rust-version = "1.60"
regex = "1"
# TODO: investigate using smartstring to cut down on allocations since
# there are plenty of small strings.

[dev-dependencies]
xdg = "2.5"
64 changes: 64 additions & 0 deletions examples/check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::time::Instant;

use spellbook::Dictionary;
use xdg::BaseDirectories;

fn main() {
let mut args = std::env::args().skip(1);
let arg1 = match args.next() {
Some(arg) => arg,
None => {
eprintln!("Usage: check [LANG] WORD");
std::process::exit(1);
}
};
let (lang, word) = match args.next() {
Some(arg2) => (arg1, arg2),
None => ("en_US".to_string(), arg1),
};

let base = BaseDirectories::new().expect("Could not determine XDG directories");
let (dic_path, aff_path) = match base.get_data_dirs().iter().find_map(|dir| {
let subdir = dir.join("hunspell");
if !subdir.is_dir() {
return None;
}

let dic = subdir.join(format!("{lang}.dic"));
let aff = subdir.join(format!("{lang}.aff"));
if dic.is_file() && aff.is_file() {
Some((dic, aff))
} else {
None
}
}) {
Some((dic, aff)) => (dic, aff),
None => {
eprintln!("Could not find the {lang} dictionary");
std::process::exit(1);
}
};
let dic_text = std::fs::read_to_string(dic_path).unwrap();
let aff_text = std::fs::read_to_string(aff_path).unwrap();

let now = Instant::now();
let dict = Dictionary::compile(&aff_text, &dic_text).unwrap();
println!(
"Compiled the {lang} dictionary in {}ms",
now.elapsed().as_millis()
);

let now = Instant::now();
if dict.check(&word) {
println!(
"\"{word}\" is in the dictionary (checked in {}µs)",
now.elapsed().as_micros()
);
} else {
eprintln!(
"\"{word}\" is NOT in the dictionary (checked in {}µs)",
now.elapsed().as_micros()
);
std::process::exit(1);
}
}

0 comments on commit 2d83f72

Please sign in to comment.