Skip to content

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

perf(core): cache `WordSet` in `ModalVerb` (#3017)

Steve Kurch6b752946d82e
diff --git a/harper-core/src/patterns/modal_verb.rs b/harper-core/src/patterns/modal_verb.rs
index 00e2d38ff..9e3fa371e 100644
--- a/harper-core/src/patterns/modal_verb.rs
+++ b/harper-core/src/patterns/modal_verb.rs
@@ -1,43 +1,51 @@
+use std::sync::LazyLock;
+
use super::{Pattern, WordSet};
+static MODALS: [&str; 14] = [
+ "can", "can't", "could", "may", "might", "must", "shall", "shan't", "should", "will", "won't",
+ "would", "ought", "dare",
+];
+
pub struct ModalVerb {
- inner: WordSet,
- include_common_errors: bool,
+ inner: &'static WordSet,
}
impl Default for ModalVerb {
fn default() -> Self {
- let (words, include_common_errors) = Self::init(false);
- Self {
- inner: words,
- include_common_errors,
- }
+ Self::without_common_errors()
}
}
impl ModalVerb {
- fn init(include_common_errors: bool) -> (WordSet, bool) {
- let modals = [
- "can", "can't", "could", "may", "might", "must", "shall", "shan't", "should", "will",
- "won't", "would", "ought", "dare",
- ];
-
- let mut words = WordSet::new(&modals);
- modals.iter().for_each(|word| {
- words.add(&format!("{word}n't"));
- if include_common_errors {
- words.add(&format!("{word}nt"));
- }
+ pub fn without_common_errors() -> Self {
+ static CACHED_WITHOUT_COMMON_ERRORS: LazyLock<WordSet> = LazyLock::new(|| {
+ let mut words = WordSet::new(&MODALS);
+ MODALS.iter().for_each(|word| {
+ words.add(&format!("{word}n't"));
+ });
+ words.add("cannot");
+ words
});
- words.add("cannot");
- (words, include_common_errors)
+
+ Self {
+ inner: &CACHED_WITHOUT_COMMON_ERRORS,
+ }
}
pub fn with_common_errors() -> Self {
- let (words, _) = Self::init(true);
+ static CACHED_WITH_COMMON_ERRORS: LazyLock<WordSet> = LazyLock::new(|| {
+ let mut words = WordSet::new(&MODALS);
+ MODALS.iter().for_each(|word| {
+ words.add(&format!("{word}n't"));
+ words.add(&format!("{word}nt"));
+ });
+ words.add("cannot");
+ words
+ });
+
Self {
- inner: words,
- include_common_errors: true,
+ inner: &CACHED_WITH_COMMON_ERRORS,
}
}
}