Skip to main content

khive_text/
tokenizer.rs

1//! Tokenizer implementations: whitespace, CJK-character, keyword, identifier, unicode-word.
2
3use crate::identifier::{is_identifier, split_identifier};
4use crate::lang::is_cjk_char;
5use crate::Tokenizer;
6
7/// Splits on Unicode whitespace, trims leading/trailing ASCII punctuation from
8/// each token, and drops empty results.
9///
10/// See `crates/khive-text/docs/api/tokenizers.md`.
11#[derive(Debug, Default, Clone)]
12pub struct WhitespaceTokenizer;
13
14impl Tokenizer for WhitespaceTokenizer {
15    fn tokenize(&self, text: &str) -> Vec<String> {
16        text.split_whitespace()
17            .map(|w| {
18                w.trim_matches(|c: char| c.is_ascii_punctuation())
19                    .to_string()
20            })
21            .filter(|t| !t.is_empty())
22            .collect()
23    }
24}
25
26/// Emits each CJK character as its own token; non-CJK runs split on whitespace with ASCII punctuation stripped.
27///
28/// See `crates/khive-text/docs/api/tokenizers.md`.
29#[derive(Debug, Default, Clone)]
30pub struct CjkCharTokenizer;
31
32impl Tokenizer for CjkCharTokenizer {
33    fn tokenize(&self, text: &str) -> Vec<String> {
34        let mut tokens = Vec::new();
35        let mut non_cjk_start = 0;
36
37        let flush = |span: &str, out: &mut Vec<String>| {
38            for part in span.split_whitespace() {
39                let p = part.trim_matches(|c: char| c.is_ascii_punctuation());
40                if !p.is_empty() {
41                    out.push(p.to_string());
42                }
43            }
44        };
45
46        for (index, ch) in text.char_indices() {
47            if is_cjk_char(ch) {
48                flush(&text[non_cjk_start..index], &mut tokens);
49                tokens.push(ch.to_string());
50                non_cjk_start = index + ch.len_utf8();
51            }
52        }
53        flush(&text[non_cjk_start..], &mut tokens);
54        tokens
55    }
56}
57
58/// Returns the entire (whitespace-trimmed) input as a single token.
59/// Empty input → empty vec.
60#[derive(Debug, Default, Clone)]
61pub struct KeywordTokenizer;
62
63impl Tokenizer for KeywordTokenizer {
64    fn tokenize(&self, text: &str) -> Vec<String> {
65        let t = text.trim();
66        if t.is_empty() {
67            vec![]
68        } else {
69            vec![t.to_string()]
70        }
71    }
72}
73
74/// Identifier-aware tokenizer: emits lowercased original + split parts for identifiers,
75/// falls back to `WhitespaceTokenizer` for plain words.
76///
77/// See `crates/khive-text/docs/api/tokenizers.md`.
78#[derive(Debug, Clone)]
79pub struct IdentifierTokenizer {
80    pub min_part_len: usize,
81}
82
83impl Default for IdentifierTokenizer {
84    fn default() -> Self {
85        Self { min_part_len: 1 }
86    }
87}
88
89impl Tokenizer for IdentifierTokenizer {
90    fn tokenize(&self, text: &str) -> Vec<String> {
91        let ws = WhitespaceTokenizer;
92        let mut result: Vec<String> = Vec::new();
93
94        for raw_word in text.split_whitespace() {
95            let word = raw_word.trim_matches(|c: char| c.is_ascii_punctuation());
96            if word.is_empty() {
97                continue;
98            }
99            if is_identifier(word) {
100                let lower = word.to_lowercase();
101                let parts = split_identifier(word, self.min_part_len);
102                result.push(lower.clone());
103                for part in parts {
104                    if part != lower {
105                        result.push(part);
106                    }
107                }
108            } else {
109                result.extend(ws.tokenize(word));
110            }
111        }
112        result
113    }
114}
115
116/// Splits on Unicode word boundaries using `unicode_segmentation`.
117///
118/// Enable with `features = ["unicode"]`.
119#[cfg(feature = "unicode")]
120#[derive(Debug, Default, Clone)]
121pub struct UnicodeWordTokenizer;
122
123#[cfg(feature = "unicode")]
124impl Tokenizer for UnicodeWordTokenizer {
125    fn tokenize(&self, text: &str) -> Vec<String> {
126        use unicode_segmentation::UnicodeSegmentation;
127        UnicodeSegmentation::unicode_words(text)
128            .map(|w| w.to_string())
129            .collect()
130    }
131}
132
133#[cfg(test)]
134#[path = "tokenizer/tests.rs"]
135mod tests;