pub fn is_combining_mark(ch: char) -> bool {
let c = ch as u32;
matches!(c,
0x0300..=0x036F | 0x0483..=0x0489 | 0x0591..=0x05BD | 0x0610..=0x061A | 0x064B..=0x065F | 0x0670
| 0x06D6..=0x06DC
| 0x06DF..=0x06E4
| 0x06E7..=0x06E8
| 0x06EA..=0x06ED
| 0x0900..=0x0903 | 0x093A..=0x094F | 0x0951..=0x0957
| 0x0962..=0x0963
| 0x0E31 | 0x0E34..=0x0E3A | 0x0E47..=0x0E4E
| 0x1AB0..=0x1AFF | 0x20D0..=0x20F0 | 0xFE00..=0xFE0F | 0xFE20..=0xFE2F ) || ch == '\u{200D}' || ch == '\u{200C}' }
fn joins_after_zwj(ch: char) -> bool {
!ch.is_control() && !ch.is_whitespace() && !ch.is_ascii()
}
pub fn cluster_boundaries(text: &str) -> Vec<usize> {
let mut out = vec![0usize];
let mut prev_was_zwj = false;
for (i, ch) in text.char_indices() {
if i > 0 {
let joins = is_combining_mark(ch) || (prev_was_zwj && joins_after_zwj(ch));
if !joins {
out.push(i);
}
}
prev_was_zwj = ch == '\u{200D}';
}
out.push(text.len());
out.dedup();
out
}
#[inline]
fn is_boundary_at(text: &str, i: usize) -> bool {
debug_assert!(text.is_char_boundary(i));
if i == 0 || i >= text.len() {
return false; }
let ch = text[i..].chars().next().unwrap_or('\0');
if is_combining_mark(ch) {
return false;
}
if text[..i].ends_with('\u{200D}') {
return !joins_after_zwj(ch);
}
true
}
fn boundary_at_or_before(text: &str, byte: usize) -> usize {
let mut end = byte;
while end > 0 {
let Some((start, _)) = text[..end].char_indices().next_back() else {
return 0;
};
if start == 0 {
return 0; }
if is_boundary_at(text, start) {
return start;
}
end = start;
}
0
}
pub fn snap(text: &str, byte: usize) -> usize {
let byte = byte.min(text.len());
if byte == 0 {
return 0;
}
if byte >= text.len() {
return text.len();
}
let mut at = byte;
while at > 0 && !text.is_char_boundary(at) {
at -= 1;
}
if text.is_char_boundary(at) && (is_boundary_at(text, at) || at == 0) {
return at;
}
boundary_at_or_before(text, at)
}
pub fn prev_boundary(text: &str, byte: usize) -> Option<usize> {
let byte = snap(text, byte);
if byte == 0 {
return None;
}
let mut end = byte;
while end > 0 {
let (start, _) = text[..end].char_indices().next_back()?;
if start == 0 {
return Some(0); }
if is_boundary_at(text, start) {
return Some(start);
}
end = start;
}
Some(0)
}
pub fn next_boundary(text: &str, byte: usize) -> Option<usize> {
let byte = snap(text, byte);
if byte >= text.len() {
return None;
}
let mut it = text[byte..].char_indices();
it.next();
for (offset, ch) in it {
let i = byte + offset;
let _ = ch;
if is_boundary_at(text, i) {
return Some(i);
}
}
Some(text.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_has_one_boundary_per_char_plus_ends() {
assert_eq!(cluster_boundaries("abc"), vec![0, 1, 2, 3]);
}
#[test]
fn arabic_letters_are_individual_clusters() {
let text = "مرحبا";
let b = cluster_boundaries(text);
assert_eq!(b.len(), 6, "5 个字母 → 6 个边界,实得 {b:?}");
}
#[test]
fn devanagari_vowel_sign_stays_with_its_consonant() {
let text = "कि";
let b = cluster_boundaries(text);
assert_eq!(b, vec![0, text.len()], "实得 {b:?}");
}
#[test]
fn combining_accent_attaches_to_the_letter() {
let text = "e\u{0301}x";
let b = cluster_boundaries(text);
assert_eq!(b, vec![0, 3, 4], "e+重音应同群,x 单群;实得 {b:?}");
}
#[test]
fn snap_never_lands_inside_a_cluster() {
let text = "कि";
for i in 0..=text.len() {
let s = snap(text, i);
assert!(s == 0 || s == text.len(), "snap({i}) = {s}");
}
}
#[test]
fn snap_clamps_out_of_range_input() {
assert_eq!(snap("abc", 99), 3);
assert_eq!(snap("abc", 0), 0);
assert_eq!(snap("", 5), 0);
}
#[test]
fn prev_and_next_boundary_walk_over_whole_clusters() {
let text = "e\u{0301}x";
assert_eq!(
prev_boundary(text, 3),
Some(0),
"从 x 往左应跨过整个 e+重音"
);
assert_eq!(
next_boundary(text, 0),
Some(3),
"从 0 往右应跨过整个 e+重音"
);
assert_eq!(prev_boundary(text, 0), None);
assert_eq!(next_boundary(text, text.len()), None);
}
fn reference_snap_prev_next(text: &str, byte: usize) -> (usize, Option<usize>, Option<usize>) {
fn bounds(text: &str) -> Vec<usize> {
let mut out = vec![0usize];
let mut prev_was_zwj = false;
for (i, ch) in text.char_indices() {
if i > 0 {
let joins = is_combining_mark(ch) || (prev_was_zwj && joins_after_zwj(ch));
if !joins {
out.push(i);
}
}
prev_was_zwj = ch == '\u{200D}';
}
out.push(text.len());
out.dedup();
out
}
let byte = byte.min(text.len());
let b = bounds(text);
let snapped = if byte == 0 || byte >= text.len() {
byte
} else {
match b.binary_search(&byte) {
Ok(_) => byte,
Err(idx) => b.get(idx.saturating_sub(1)).copied().unwrap_or(0),
}
};
let prev = b.iter().rev().copied().find(|x| *x < snapped);
let next = b.iter().copied().find(|x| *x > snapped);
(snapped, prev, next)
}
#[test]
fn allocation_free_walk_matches_the_materialised_reference() {
let corpus = [
"",
"abc",
"ab cd",
"e\u{301}",
"e\u{301}x\u{308}",
"\u{915}\u{93F}\u{930}\u{94D}\u{92F}",
"\u{645}\u{631}\u{62D}\u{628}\u{627}",
"\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}",
"a\u{200D}b\u{200C}c",
" \u{301} ",
];
for text in corpus {
for byte in 0..=text.len() {
let (want_snap, want_prev, want_next) = reference_snap_prev_next(text, byte);
assert_eq!(snap(text, byte), want_snap, "snap({text:?}, {byte})");
assert_eq!(
prev_boundary(text, byte),
want_prev,
"prev_boundary({text:?}, {byte})"
);
assert_eq!(
next_boundary(text, byte),
want_next,
"next_boundary({text:?}, {byte})"
);
}
}
}
#[test]
fn walk_stays_correct_on_a_long_combining_run() {
let mut text = String::from("a");
for _ in 0..500 {
text.push('\u{301}');
}
text.push('b');
assert_eq!(snap(&text, 250), 0, "簇中间必须吸附到簇首");
assert_eq!(next_boundary(&text, 0), Some(1001), "下一步应一次跨到 'b'");
assert_eq!(prev_boundary(&text, text.len()), Some(1001));
let huge = "x".repeat(200_000);
let mut pos = huge.len();
for _ in 0..1000 {
pos = prev_boundary(&huge, pos).unwrap_or(0);
}
assert_eq!(pos, huge.len() - 1000, "1000 次 ← 应正好后退 1000 个字符");
}
#[test]
fn zwj_does_not_glue_control_or_space_into_the_same_cluster() {
let text = "\u{1F468}\u{200D}\t";
let b = cluster_boundaries(text);
assert!(
b.contains(&(text.len() - 1)),
"制表符之前必须成界(否则它和前一个 emoji 粘成一簇):{b:?}"
);
assert_eq!(
prev_boundary(text, text.len()),
Some(text.len() - 1),
"Backspace 只能删掉制表符,不能连 emoji 一起删"
);
for tail in ["\n", " "] {
let t = format!("\u{1F468}\u{200D}{tail}");
let b = cluster_boundaries(&t);
assert!(
b.contains(&(t.len() - tail.len())),
"ZWJ 后的 {tail:?} 必须成界:{b:?}"
);
}
}
#[test]
fn emoji_zwj_sequence_stays_one_cluster() {
let text = "\u{1F468}\u{200D}\u{1F469}";
let b = cluster_boundaries(text);
assert_eq!(b, vec![0, text.len()], "emoji ZWJ 序列必须是一簇:{b:?}");
assert_eq!(prev_boundary(text, text.len()), Some(0));
}
#[test]
fn empty_text_has_one_boundary_and_no_movement() {
assert_eq!(cluster_boundaries(""), vec![0]);
assert_eq!(prev_boundary("", 0), None);
assert_eq!(next_boundary("", 0), None);
}
#[test]
fn orbiting_spaces_create_boundaries() {
let b = cluster_boundaries("ab cd");
assert!(b.contains(&3), "空格处应成界:{b:?}");
}
}