Debian Codegraph @

helix-core/src/search.rs

raw symbols SCIP
1 use crate::movement::Direction;
2 use crate::RopeSlice;
3
4 // TODO: switch to std::str::Pattern when it is stable.
5 pub trait CharMatcher {
6 fn char_match(&self, ch: char) -> bool;
7 }
8
9 impl CharMatcher for char {
10 fn char_match(&self, ch: char) -> bool {
11 *self == ch
12 }
13 }
14
15 impl<F: Fn(&char) -> bool> CharMatcher for F {
16 fn char_match(&self, ch: char) -> bool {
17 (*self)(&ch)
18 }
19 }
20
21 // Finds the positions of the nth matching character in given direction
22 // starting from the pos gap-index (see Range struct for explanation)
23 pub fn find_nth_char<M: CharMatcher>(
24 mut n: usize,
25 text: RopeSlice,
26 char_matcher: M,
27 mut pos: usize,
28 direction: Direction,
29 ) -> Option<usize> {
30 if n == 0 {
31 return None;
32 }
33
34 let mut chars = text.get_chars_at(pos)?;
35
36 match direction {
37 Direction::Forward => loop {
38 let c = chars.next()?;
39 if char_matcher.char_match(c) {
40 n -= 1;
41 if n == 0 {
42 return Some(pos);
43 }
44 }
45 pos += 1;
46 },
47 Direction::Backward => loop {
48 let c = chars.prev()?;
49 pos -= 1;
50 if char_matcher.char_match(c) {
51 n -= 1;
52 if n == 0 {
53 return Some(pos);
54 }
55 }
56 },
57 };
58 }
59
60 #[cfg(test)]
61 mod test {
62 use super::*;
63 use crate::movement::Direction;
64
65 #[test]
66 fn test_find_nth_char() {
67 let text = RopeSlice::from("aa ⌚aa \r\n aa");
68
69 // Forward direction
70 assert_eq!(find_nth_char(1, text, 'a', 5, Direction::Forward), Some(5));
71 assert_eq!(find_nth_char(2, text, 'a', 5, Direction::Forward), Some(10));
72 assert_eq!(find_nth_char(3, text, 'a', 5, Direction::Forward), Some(11));
73 assert_eq!(find_nth_char(4, text, 'a', 5, Direction::Forward), None);
74
75 // Backward direction
76 assert_eq!(find_nth_char(1, text, 'a', 5, Direction::Backward), Some(4));
77 assert_eq!(find_nth_char(2, text, 'a', 5, Direction::Backward), Some(1));
78 assert_eq!(find_nth_char(3, text, 'a', 5, Direction::Backward), Some(0));
79 assert_eq!(find_nth_char(4, text, 'a', 5, Direction::Backward), None);
80
81 // Edge cases
82 assert_eq!(find_nth_char(0, text, 'a', 5, Direction::Forward), None); // n = 0
83 assert_eq!(find_nth_char(1, text, 'x', 5, Direction::Forward), None); // Not found
84 assert_eq!(find_nth_char(1, text, 'a', 20, Direction::Forward), None); // Beyond text
85 assert_eq!(find_nth_char(1, text, 'a', 0, Direction::Backward), None); // At start going backward
86 }
87 }