dev: improve doc about slice_at (#226)

This commit is contained in:
Myriad-Dreamin 2024-05-04 13:58:51 +08:00 committed by GitHub
parent c544283bbf
commit f87659f2e3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 14 deletions

View file

@ -1,5 +1,6 @@
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::HashSet; use std::collections::HashSet;
use std::ops::Range;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use if_chain::if_chain; use if_chain::if_chain;
@ -995,10 +996,9 @@ impl<'a, 'w> CompletionContext<'a, 'w> {
/// A small window of context before the cursor. /// A small window of context before the cursor.
fn before_window(&self, size: usize) -> &str { fn before_window(&self, size: usize) -> &str {
safe_str_slice( slice_at(
self.before, self.before,
self.cursor.saturating_sub(size), self.cursor.saturating_sub(size)..self.before.len(),
self.before.len(),
) )
} }
@ -1273,17 +1273,18 @@ impl<'a, 'w> CompletionContext<'a, 'w> {
} }
} }
fn safe_str_slice(s: &str, mut start: usize, mut end: usize) -> &str { /// Slices a smaller string at character boundaries safely.
while start < s.len() && !s.is_char_boundary(start) { fn slice_at(s: &str, mut rng: Range<usize>) -> &str {
start += 1; while !rng.is_empty() && !s.is_char_boundary(rng.start) {
rng.start += 1;
} }
while end > 0 && !s.is_char_boundary(end) { while !rng.is_empty() && !s.is_char_boundary(rng.end) {
end -= 1; rng.end -= 1;
} }
if end >= start { if rng.is_empty() {
&s[start..end] return "";
} else {
""
} }
&s[rng]
} }

View file

@ -1063,14 +1063,14 @@ pub fn complete_path(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::upstream::complete::safe_str_slice; use crate::upstream::complete::slice_at;
#[test] #[test]
fn test_before() { fn test_before() {
const TEST_UTF8_STR: &str = "我们"; const TEST_UTF8_STR: &str = "我们";
for i in 0..=TEST_UTF8_STR.len() { for i in 0..=TEST_UTF8_STR.len() {
for j in 0..=TEST_UTF8_STR.len() { for j in 0..=TEST_UTF8_STR.len() {
let _s = std::hint::black_box(safe_str_slice(TEST_UTF8_STR, i, j)); let _s = std::hint::black_box(slice_at(TEST_UTF8_STR, i..j));
} }
} }
} }