aboutsummaryrefslogtreecommitdiff
path: root/helix-core/src/search.rs
blob: 7dd2f4fc3c763fc4b83fde722f674c2c721a49b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::RopeSlice;

pub fn find_nth_next(
    text: RopeSlice,
    ch: char,
    mut pos: usize,
    n: usize,
    inclusive: bool,
) -> Option<usize> {
    if pos >= text.len_chars() {
        return None;
    }

    // start searching right after pos
    let mut chars = text.chars_at(pos + 1);

    for _ in 0..n {
        loop {
            let c = chars.next()?;

            pos += 1;

            if c == ch {
                break;
            }
        }
    }

    if !inclusive {
        pos -= 1;
    }

    Some(pos)
}

pub fn find_nth_prev(
    text: RopeSlice,
    ch: char,
    mut pos: usize,
    n: usize,
    inclusive: bool,
) -> Option<usize> {
    // start searching right before pos
    pos = pos.saturating_sub(1);
    let mut chars = text.chars_at(pos);

    for _ in 0..n {
        loop {
            let c = chars.prev()?;

            pos = pos.saturating_sub(1);

            if c == ch {
                break;
            }
        }
    }

    if !inclusive {
        pos += 1;
    }

    Some(pos)
}