Skip to main content

ncp_matcher/
utf32_str.rs

1#[cfg(test)]
2mod tests;
3
4use std::borrow::Cow;
5use std::ops::{Bound, RangeBounds};
6use std::{fmt, slice};
7
8use memchr::memmem;
9
10use crate::chars;
11
12/// Check if a given string can be represented internally as the `Ascii` variant in a
13/// [`Utf32String`] or a [`Utf32Str`].
14///
15/// This returns true if the string is ASCII and does not contain a windows-style newline
16/// `'\r'`.
17/// The additional carriage return check is required since even for strings consisting only
18/// of ASCII, the windows-style newline `\r\n` is treated as a single grapheme.
19#[inline]
20fn has_ascii_graphemes(string: &str) -> bool {
21    string.is_ascii() && memmem::find(string.as_bytes(), b"\r\n").is_none()
22}
23
24/// A UTF-32 encoded (char array) string that is used as an input to (fuzzy) matching.
25///
26/// This is mostly intended as an internal string type, but some methods are exposed for
27/// convenience. We make the following API guarantees for `Utf32Str(ing)`s produced from a string
28/// using one of its `From<T>` constructors for string types `T` or from the
29/// [`Utf32Str::new`] method.
30///
31/// 1. The `Ascii` variant contains a byte buffer which is guaranteed to be a valid string
32///    slice.
33/// 2. It is guaranteed that the string slice internal to the `Ascii` variant is identical
34///    to the original string.
35/// 3. The length of a `Utf32Str(ing)` is exactly the number of graphemes in the original string.
36///
37/// Since `Utf32Str(ing)`s variants may be constructed directly, you **must not** make these
38/// assumptions when handling `Utf32Str(ing)`s of unknown origin.
39///
40/// ## Caveats
41/// Despite the name, this type is quite far from being a true string type. Here are some
42/// examples demonstrating this.
43///
44/// ### String conversions are not round-trip
45/// Graphemes with a canonical Unicode composition are represented by the first character of their
46/// NFC-normalized form. If normalization leaves multiple characters, the trailing characters are
47/// truncated.
48/// ```
49/// # use ncp_matcher::Utf32String;
50/// assert_eq!(Utf32String::from("u\u{0308}").to_string(), "ü");
51/// assert_eq!(Utf32String::from("a\u{0302}\u{0301}").to_string(), "ấ");
52/// assert_eq!(Utf32String::from("q\u{0308}").to_string(), "q");
53/// ```
54///
55/// ### Indexing is done by grapheme
56/// Indexing into a string is done by grapheme rather than by codepoint.
57/// ```
58/// # use ncp_matcher::Utf32String;
59/// assert!(Utf32String::from("au\u{0308}").len() == 2);
60/// ```
61///
62/// ### A `Unicode` variant may be produced by all-ASCII characters.
63/// Since the windows-style newline `\r\n` is ASCII only but considered to be a single grapheme,
64/// strings containing `\r\n` will still result in a `Unicode` variant.
65/// ```
66/// # use ncp_matcher::Utf32String;
67/// let s = Utf32String::from("\r\n");
68/// assert!(!s.slice(..).is_ascii());
69/// assert!(s.len() == 1);
70/// assert!(s.slice(..).get(0) == '\n');
71/// ```
72///
73/// ## Design rationale
74/// Usually Rust's UTF-8 encoded strings are great. However, since fuzzy matching
75/// operates on codepoints (ideally, it should operate on graphemes but that's too
76/// much hassle to deal with), we want to quickly iterate over codepoints (up to 5
77/// times) during matching.
78///
79/// Doing codepoint segmentation on the fly not only blows trough the cache
80/// (lookup tables and I-cache) but also has nontrivial runtime compared to the
81/// matching itself. Furthermore there are many extra optimizations available
82/// for ASCII only text, but checking each match has too much overhead.
83///
84/// Of course, this comes at extra memory cost as we usually still need the UTF-8
85/// encoded variant for rendering. In the (dominant) case of ASCII-only text
86/// we don't require a copy. Furthermore fuzzy matching usually is applied while
87/// the user is typing on the fly so the same item is potentially matched many
88/// times (making the the up-front cost more worth it). That means that its
89/// basically always worth it to pre-segment the string.
90///
91/// For usecases that only match (a lot of) strings once its possible to keep
92/// char buffer around that is filled with the presegmented chars.
93///
94/// Another advantage of this approach is that the matcher will naturally
95/// produce grapheme indices (instead of utf8 offsets) anyway. With a
96/// codepoint basic representation like this the indices can be used
97/// directly
98#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
99pub enum Utf32Str<'a> {
100    /// A string represented as ASCII encoded bytes.
101    ///
102    /// Correctness invariant: must only contain valid ASCII (`<= 127`)
103    Ascii(&'a [u8]),
104    /// A string represented as an array of unicode codepoints (basically UTF-32).
105    Unicode(&'a [char]),
106}
107
108impl<'a> Utf32Str<'a> {
109    /// Convenience method to construct a `Utf32Str` from a normal UTF-8 str
110    pub fn new(str: &'a str, buf: &'a mut Vec<char>) -> Self {
111        if has_ascii_graphemes(str) {
112            Utf32Str::Ascii(str.as_bytes())
113        } else {
114            buf.clear();
115            buf.extend(crate::chars::graphemes(str));
116            Utf32Str::Unicode(buf)
117        }
118    }
119
120    /// Returns the number of characters in this string.
121    #[inline]
122    pub fn len(self) -> usize {
123        match self {
124            Utf32Str::Unicode(codepoints) => codepoints.len(),
125            Utf32Str::Ascii(ascii_bytes) => ascii_bytes.len(),
126        }
127    }
128
129    /// Returns whether this string is empty.
130    #[inline]
131    pub fn is_empty(self) -> bool {
132        match self {
133            Utf32Str::Unicode(codepoints) => codepoints.is_empty(),
134            Utf32Str::Ascii(ascii_bytes) => ascii_bytes.is_empty(),
135        }
136    }
137
138    /// Creates a slice with a string that contains the characters in
139    /// the specified **character range**.
140    #[inline]
141    pub fn slice(self, range: impl RangeBounds<usize>) -> Utf32Str<'a> {
142        let start = match range.start_bound() {
143            Bound::Included(&start) => start,
144            Bound::Excluded(&start) => start + 1,
145            Bound::Unbounded => 0,
146        };
147        let end = match range.end_bound() {
148            Bound::Included(&end) => end + 1,
149            Bound::Excluded(&end) => end,
150            Bound::Unbounded => self.len(),
151        };
152        match self {
153            Utf32Str::Ascii(bytes) => Utf32Str::Ascii(&bytes[start..end]),
154            Utf32Str::Unicode(codepoints) => Utf32Str::Unicode(&codepoints[start..end]),
155        }
156    }
157
158    /// Returns the number of leading whitespaces in this string
159    #[inline]
160    pub(crate) fn leading_white_space(self) -> usize {
161        match self {
162            Utf32Str::Ascii(bytes) => bytes
163                .iter()
164                .position(|b| !b.is_ascii_whitespace())
165                .unwrap_or(0),
166            Utf32Str::Unicode(codepoints) => codepoints
167                .iter()
168                .position(|c| !c.is_whitespace())
169                .unwrap_or(0),
170        }
171    }
172
173    /// Returns the number of trailing whitespaces in this string
174    #[inline]
175    pub(crate) fn trailing_white_space(self) -> usize {
176        match self {
177            Utf32Str::Ascii(bytes) => bytes
178                .iter()
179                .rev()
180                .position(|b| !b.is_ascii_whitespace())
181                .unwrap_or(0),
182            Utf32Str::Unicode(codepoints) => codepoints
183                .iter()
184                .rev()
185                .position(|c| !c.is_whitespace())
186                .unwrap_or(0),
187        }
188    }
189
190    /// Same as `slice` but accepts a u32 range for convenience since
191    /// those are the indices returned by the matcher.
192    #[inline]
193    pub fn slice_u32(self, range: impl RangeBounds<u32>) -> Utf32Str<'a> {
194        let start = match range.start_bound() {
195            Bound::Included(&start) => start as usize,
196            Bound::Excluded(&start) => start as usize + 1,
197            Bound::Unbounded => 0,
198        };
199        let end = match range.end_bound() {
200            Bound::Included(&end) => end as usize + 1,
201            Bound::Excluded(&end) => end as usize,
202            Bound::Unbounded => self.len(),
203        };
204        match self {
205            Utf32Str::Ascii(bytes) => Utf32Str::Ascii(&bytes[start..end]),
206            Utf32Str::Unicode(codepoints) => Utf32Str::Unicode(&codepoints[start..end]),
207        }
208    }
209
210    /// Returns whether this string only contains graphemes which are single ASCII chars.
211    ///
212    /// This is almost equivalent to the string being ASCII, except with the additional requirement
213    /// that the string cannot contain a windows-style newline `\r\n` which is treated as a single
214    /// grapheme.
215    pub fn is_ascii(self) -> bool {
216        matches!(self, Utf32Str::Ascii(_))
217    }
218
219    /// Returns the `n`th character in this string, zero-indexed
220    pub fn get(self, n: u32) -> char {
221        match self {
222            Utf32Str::Ascii(bytes) => bytes[n as usize] as char,
223            Utf32Str::Unicode(codepoints) => codepoints[n as usize],
224        }
225    }
226
227    /// Returns the last character in this string.
228    ///
229    /// Panics if the string is empty.
230    pub(crate) fn last(self) -> char {
231        match self {
232            Utf32Str::Ascii(bytes) => bytes[bytes.len() - 1] as char,
233            Utf32Str::Unicode(codepoints) => codepoints[codepoints.len() - 1],
234        }
235    }
236
237    /// Returns the first character in this string.
238    ///
239    /// Panics if the string is empty.
240    pub(crate) fn first(self) -> char {
241        match self {
242            Utf32Str::Ascii(bytes) => bytes[0] as char,
243            Utf32Str::Unicode(codepoints) => codepoints[0],
244        }
245    }
246
247    /// Returns an iterator over the characters in this string
248    pub fn chars(self) -> Chars<'a> {
249        match self {
250            Utf32Str::Ascii(bytes) => Chars::Ascii(bytes.iter()),
251            Utf32Str::Unicode(codepoints) => Chars::Unicode(codepoints.iter()),
252        }
253    }
254}
255
256impl fmt::Debug for Utf32Str<'_> {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        use std::fmt::Write;
259        f.write_char('"')?;
260        for c in self.chars() {
261            for c in c.escape_debug() {
262                f.write_char(c)?;
263            }
264        }
265        f.write_char('"')
266    }
267}
268
269impl fmt::Display for Utf32Str<'_> {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        use std::fmt::Write;
272        for c in self.chars() {
273            f.write_char(c)?;
274        }
275        Ok(())
276    }
277}
278
279pub enum Chars<'a> {
280    Ascii(slice::Iter<'a, u8>),
281    Unicode(slice::Iter<'a, char>),
282}
283
284impl Iterator for Chars<'_> {
285    type Item = char;
286
287    fn next(&mut self) -> Option<Self::Item> {
288        match self {
289            Chars::Ascii(iter) => iter.next().map(|&c| c as char),
290            Chars::Unicode(iter) => iter.next().copied(),
291        }
292    }
293}
294
295impl DoubleEndedIterator for Chars<'_> {
296    fn next_back(&mut self) -> Option<Self::Item> {
297        match self {
298            Chars::Ascii(iter) => iter.next_back().map(|&c| c as char),
299            Chars::Unicode(iter) => iter.next_back().copied(),
300        }
301    }
302}
303
304/// An owned version of [`Utf32Str`].
305///
306/// See the API documentation for [`Utf32Str`] for more detail.
307#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
308pub enum Utf32String {
309    /// A string represented as ASCII encoded bytes.
310    ///
311    /// Correctness invariant: must only contain valid ASCII (`<= 127`)
312    Ascii(Box<str>),
313    /// A string represented as an array of unicode codepoints (basically UTF-32).
314    Unicode(Box<[char]>),
315}
316
317impl Default for Utf32String {
318    fn default() -> Self {
319        Self::Ascii(String::new().into_boxed_str())
320    }
321}
322
323impl Utf32String {
324    /// Returns the number of characters in this string.
325    #[inline]
326    pub fn len(&self) -> usize {
327        match self {
328            Utf32String::Unicode(codepoints) => codepoints.len(),
329            Utf32String::Ascii(ascii_bytes) => ascii_bytes.len(),
330        }
331    }
332
333    /// Returns whether this string is empty.
334    #[inline]
335    pub fn is_empty(&self) -> bool {
336        match self {
337            Utf32String::Unicode(codepoints) => codepoints.is_empty(),
338            Utf32String::Ascii(ascii_bytes) => ascii_bytes.is_empty(),
339        }
340    }
341
342    /// Creates a slice with a string that contains the characters in
343    /// the specified **character range**.
344    #[inline]
345    pub fn slice(&self, range: impl RangeBounds<usize>) -> Utf32Str<'_> {
346        let start = match range.start_bound() {
347            Bound::Included(&start) => start,
348            Bound::Excluded(&start) => start + 1,
349            Bound::Unbounded => 0,
350        };
351        let end = match range.end_bound() {
352            Bound::Included(&end) => end + 1,
353            Bound::Excluded(&end) => end,
354            Bound::Unbounded => self.len(),
355        };
356        match self {
357            Utf32String::Ascii(bytes) => Utf32Str::Ascii(&bytes.as_bytes()[start..end]),
358            Utf32String::Unicode(codepoints) => Utf32Str::Unicode(&codepoints[start..end]),
359        }
360    }
361
362    /// Same as `slice` but accepts a u32 range for convenience since
363    /// those are the indices returned by the matcher.
364    #[inline]
365    pub fn slice_u32(&self, range: impl RangeBounds<u32>) -> Utf32Str<'_> {
366        let start = match range.start_bound() {
367            Bound::Included(&start) => start,
368            Bound::Excluded(&start) => start + 1,
369            Bound::Unbounded => 0,
370        };
371        let end = match range.end_bound() {
372            Bound::Included(&end) => end + 1,
373            Bound::Excluded(&end) => end,
374            Bound::Unbounded => self.len() as u32,
375        };
376        match self {
377            Utf32String::Ascii(bytes) => {
378                Utf32Str::Ascii(&bytes.as_bytes()[start as usize..end as usize])
379            }
380            Utf32String::Unicode(codepoints) => {
381                Utf32Str::Unicode(&codepoints[start as usize..end as usize])
382            }
383        }
384    }
385}
386
387impl From<&str> for Utf32String {
388    #[inline]
389    fn from(value: &str) -> Self {
390        if has_ascii_graphemes(value) {
391            Self::Ascii(value.to_owned().into_boxed_str())
392        } else {
393            Self::Unicode(chars::graphemes(value).collect())
394        }
395    }
396}
397
398impl From<Box<str>> for Utf32String {
399    fn from(value: Box<str>) -> Self {
400        if has_ascii_graphemes(&value) {
401            Self::Ascii(value)
402        } else {
403            Self::Unicode(chars::graphemes(&value).collect())
404        }
405    }
406}
407
408impl From<String> for Utf32String {
409    #[inline]
410    fn from(value: String) -> Self {
411        value.into_boxed_str().into()
412    }
413}
414
415impl From<Cow<'_, str>> for Utf32String {
416    #[inline]
417    fn from(value: Cow<'_, str>) -> Self {
418        match value {
419            Cow::Borrowed(value) => value.into(),
420            Cow::Owned(value) => value.into(),
421        }
422    }
423}
424
425impl From<Utf32Str<'_>> for Utf32String {
426    fn from(value: Utf32Str<'_>) -> Self {
427        match value {
428            Utf32Str::Ascii(items) => unsafe {
429                Utf32String::Ascii(std::str::from_utf8_unchecked(items).into())
430            },
431            Utf32Str::Unicode(items) => Utf32String::Unicode(items.into()),
432        }
433    }
434}
435
436impl fmt::Debug for Utf32String {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        fmt::Debug::fmt(&self.slice(..), f)
439    }
440}
441
442impl fmt::Display for Utf32String {
443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444        fmt::Display::fmt(&self.slice(..), f)
445    }
446}