#[must_use]
pub fn clamp_utf8_boundary(text: &str, byte_index: usize) -> usize {
let mut clamped: usize = byte_index.min(text.len());
while clamped > 0 && !text.is_char_boundary(clamped) {
clamped = clamped.saturating_sub(1);
}
clamped
}
#[must_use]
pub fn prev_char_boundary(text: &str, byte_index: usize) -> usize {
let clamped: usize = clamp_utf8_boundary(text, byte_index);
if clamped == 0 {
return 0;
}
text[..clamped]
.char_indices()
.next_back()
.map(|(offset, _): (usize, char)| offset)
.unwrap_or(0)
}
#[must_use]
pub fn next_char_boundary(text: &str, byte_index: usize) -> usize {
let clamped: usize = clamp_utf8_boundary(text, byte_index);
if clamped >= text.len() {
return text.len();
}
let ch_len: usize = text[clamped..]
.chars()
.next()
.map(|ch: char| ch.len_utf8())
.unwrap_or(0);
clamped.saturating_add(ch_len).min(text.len())
}
#[must_use]
pub fn is_word_char(ch: char) -> bool {
ch.is_alphanumeric() || ch == '_'
}
#[must_use]
pub fn prev_word_boundary(text: &str, byte_index: usize) -> usize {
let clamped: usize = clamp_utf8_boundary(text, byte_index);
if clamped == 0 {
return 0;
}
let mut cursor: usize = clamped;
let prefix: &str = &text[..clamped];
let mut chars_rev: Vec<(usize, char)> = prefix.char_indices().collect();
while let Some(&(offset, ch)) = chars_rev.last() {
if !ch.is_whitespace() {
break;
}
cursor = offset;
let _: Option<(usize, char)> = chars_rev.pop();
}
let Some(&(_, anchor_char)) = chars_rev.last() else {
return cursor;
};
let target_word: bool = is_word_char(anchor_char);
while let Some(&(offset, ch)) = chars_rev.last() {
if ch.is_whitespace() || is_word_char(ch) != target_word {
break;
}
cursor = offset;
let _: Option<(usize, char)> = chars_rev.pop();
}
cursor
}
#[must_use]
pub fn next_word_boundary(text: &str, byte_index: usize) -> usize {
let clamped: usize = clamp_utf8_boundary(text, byte_index);
if clamped >= text.len() {
return text.len();
}
let suffix: &str = &text[clamped..];
let mut iter_chars: Vec<(usize, char)> = suffix.char_indices().collect();
let mut idx: usize = 0;
while idx < iter_chars.len() && iter_chars[idx].1.is_whitespace() {
idx = idx.saturating_add(1);
}
if idx >= iter_chars.len() {
return text.len();
}
let target_word: bool = is_word_char(iter_chars[idx].1);
while idx < iter_chars.len() {
let ch: char = iter_chars[idx].1;
if ch.is_whitespace() || is_word_char(ch) != target_word {
break;
}
idx = idx.saturating_add(1);
}
if idx < iter_chars.len() {
clamped.saturating_add(iter_chars[idx].0)
} else {
let _: usize = iter_chars.len();
iter_chars.clear();
text.len()
}
}