Skip to content

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

fix(core): avoid allocation in hot path

Elijah Potter99af4a72aa6b
diff --git a/harper-core/benches/parse_demo.rs b/harper-core/benches/parse_demo.rs
index e3b269202..32234f932 100644
--- a/harper-core/benches/parse_demo.rs
+++ b/harper-core/benches/parse_demo.rs
@@ -1,5 +1,5 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
-use harper_core::linting::{LintGroup, LintGroupConfig, Linter};
+use harper_core::linting::{LintGroup, Linter};
use harper_core::{Document, FstDictionary};
static DEMO: &str = include_str!("../../demo.md");
diff --git a/harper-core/src/ignored_lints/mod.rs b/harper-core/src/ignored_lints/mod.rs
index 79e209280..f22dbdb44 100644
--- a/harper-core/src/ignored_lints/mod.rs
+++ b/harper-core/src/ignored_lints/mod.rs
@@ -59,7 +59,7 @@ mod tests {
use super::IgnoredLints;
use crate::{
- linting::{LintGroup, LintGroupConfig, Linter},
+ linting::{LintGroup, Linter},
Document, FstDictionary,
};
diff --git a/harper-core/src/patterns/within_edit_distance.rs b/harper-core/src/patterns/within_edit_distance.rs
index a706a407e..cf2d1abd8 100644
--- a/harper-core/src/patterns/within_edit_distance.rs
+++ b/harper-core/src/patterns/within_edit_distance.rs
@@ -1,7 +1,9 @@
+use std::cell::RefCell;
+
use super::Pattern;
use crate::{CharString, CharStringExt, Token, TokenKind};
-use crate::edit_distance::edit_distance;
+use crate::edit_distance::{edit_distance, edit_distance_min_alloc};
/// A [`Pattern`] that matches single words within a certain edit distance of a given word.
pub struct WithinEditDistance {
@@ -24,6 +26,11 @@ impl WithinEditDistance {
}
}
+thread_local! {
+ // To avoid allocating each call to `matches`.
+ static BUFFERS: RefCell<(Vec<u8>, Vec<u8>)> = const { RefCell::new((Vec::new(), Vec::new())) };
+}
+
impl Pattern for WithinEditDistance {
fn matches(&self, tokens: &[Token], source: &[char]) -> usize {
let Some(first) = tokens.first() else {
@@ -36,10 +43,18 @@ impl Pattern for WithinEditDistance {
let content = first.span.get_content(source);
- if edit_distance(&content.to_lower(), &self.word.to_lower()) <= self.max_edit_dist {
- 1
- } else {
- 0
- }
+ BUFFERS.with_borrow_mut(|(buffer_a, buffer_b)| {
+ if edit_distance_min_alloc(
+ &content.to_lower(),
+ &self.word.to_lower(),
+ buffer_a,
+ buffer_b,
+ ) <= self.max_edit_dist
+ {
+ 1
+ } else {
+ 0
+ }
+ })
}
}