From 1e7cd48cfab6a2f78667f07909640a28f5dc176f Mon Sep 17 00:00:00 2001 From: PSeitz Date: Thu, 13 Jul 2023 08:43:02 +0800 Subject: [PATCH] remove allocations in split compound words (#2080) * remove allocations in split compound words * clear reused data --- src/tokenizer/split_compound_words.rs | 46 +++++++++++++++------------ 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/tokenizer/split_compound_words.rs b/src/tokenizer/split_compound_words.rs index bcde161cc..5ee244f01 100644 --- a/src/tokenizer/split_compound_words.rs +++ b/src/tokenizer/split_compound_words.rs @@ -86,6 +86,8 @@ impl TokenFilter for SplitCompoundWords { SplitCompoundWordsFilter { dict: self.dict, inner: tokenizer, + cuts: Vec::new(), + parts: Vec::new(), } } } @@ -94,29 +96,33 @@ impl TokenFilter for SplitCompoundWords { pub struct SplitCompoundWordsFilter { dict: AhoCorasick, inner: T, -} - -impl Tokenizer for SplitCompoundWordsFilter { - type TokenStream<'a> = SplitCompoundWordsTokenStream>; - - fn token_stream<'a>(&'a mut self, text: &'a str) -> Self::TokenStream<'a> { - SplitCompoundWordsTokenStream { - dict: self.dict.clone(), - tail: self.inner.token_stream(text), - cuts: Vec::new(), - parts: Vec::new(), - } - } -} - -pub struct SplitCompoundWordsTokenStream { - dict: AhoCorasick, - tail: T, cuts: Vec, parts: Vec, } -impl SplitCompoundWordsTokenStream { +impl Tokenizer for SplitCompoundWordsFilter { + type TokenStream<'a> = SplitCompoundWordsTokenStream<'a, T::TokenStream<'a>>; + + fn token_stream<'a>(&'a mut self, text: &'a str) -> Self::TokenStream<'a> { + self.cuts.clear(); + self.parts.clear(); + SplitCompoundWordsTokenStream { + dict: self.dict.clone(), + tail: self.inner.token_stream(text), + cuts: &mut self.cuts, + parts: &mut self.parts, + } + } +} + +pub struct SplitCompoundWordsTokenStream<'a, T> { + dict: AhoCorasick, + tail: T, + cuts: &'a mut Vec, + parts: &'a mut Vec, +} + +impl<'a, T: TokenStream> SplitCompoundWordsTokenStream<'a, T> { // Will use `self.cuts` to fill `self.parts` if `self.tail.token()` // can fully be split into consecutive matches against `self.dict`. fn split(&mut self) { @@ -152,7 +158,7 @@ impl SplitCompoundWordsTokenStream { } } -impl TokenStream for SplitCompoundWordsTokenStream { +impl<'a, T: TokenStream> TokenStream for SplitCompoundWordsTokenStream<'a, T> { fn advance(&mut self) -> bool { self.parts.pop();