crates/highlight/src/util.rs 1.8 KiB raw
1
//! Small shared helpers for text and lookup normalization.
2
//!
3
//! The highlighter works in byte ranges but must avoid splitting UTF-8 code
4
//! points when regex captures or caller ranges land inside a character. This
5
//! module also centralizes lowercase lookup-key handling for syntax inference.
6
7
use std::path::Path;
8
9
/// Returns the next valid UTF-8 boundary at or after `index`.
10
pub(crate) fn next_char_boundary(text: &str, index: usize) -> usize {
11
    let mut index = index.min(text.len());
12
    while index < text.len() && !text.is_char_boundary(index) {
13
        index += 1;
14
    }
15
    index
16
}
17
18
/// Returns the previous valid UTF-8 boundary at or before `index`.
19
pub(crate) fn previous_char_boundary(text: &str, index: usize) -> usize {
20
    let mut index = index.min(text.len());
21
    while index > 0 && !text.is_char_boundary(index) {
22
        index -= 1;
23
    }
24
    index
25
}
26
27
/// Returns `line` without trailing line terminators.
28
#[inline]
29
pub(crate) fn trim_line_end(line: &str) -> &str {
30
    line.trim_end_matches(['\r', '\n'])
31
}
32
33
/// Returns byte offsets for each source line start.
34
pub(crate) fn line_starts(input: &str) -> Vec<usize> {
35
    if input.is_empty() {
36
        return Vec::new();
37
    }
38
    let mut starts = vec![0];
39
    for (index, byte) in input.bytes().enumerate() {
40
        if byte == b'\n' && index + 1 < input.len() {
41
            starts.push(index + 1);
42
        }
43
    }
44
    starts
45
}
46
47
/// Lowercases a lookup key.
48
#[inline]
49
pub(crate) fn key(input: &str) -> String {
50
    input.to_ascii_lowercase()
51
}
52
53
/// Returns lowercase syntax lookup keys for a path.
54
pub(crate) fn path_keys(path: &Path) -> impl Iterator<Item = String> + '_ {
55
    [
56
        path.file_name().and_then(|name| name.to_str()),
57
        path.extension().and_then(|extension| extension.to_str()),
58
    ]
59
    .into_iter()
60
    .flatten()
61
    .map(key)
62
}