From 1d48f16815f74379a71bf4f70075e60e2ed15ae6 Mon Sep 17 00:00:00 2001 From: Michael Davis Date: Mon, 21 Aug 2023 16:36:53 -0500 Subject: [PATCH] Add an example for checking from a given dictionary --- .helix/config.toml | 1 + Cargo.toml | 3 +++ examples/check.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 .helix/config.toml create mode 100644 examples/check.rs diff --git a/.helix/config.toml b/.helix/config.toml new file mode 100644 index 0000000..ef7f507 --- /dev/null +++ b/.helix/config.toml @@ -0,0 +1 @@ +editor.workspace-lsp-roots = ["examples"] diff --git a/Cargo.toml b/Cargo.toml index 516a511..ec1d728 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/examples/check.rs b/examples/check.rs new file mode 100644 index 0000000..b92a77b --- /dev/null +++ b/examples/check.rs @@ -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); + } +}