Avoid byte slicing panics in CJK error messages

This commit is contained in:
gloamxun committed 2026-10-19 23:03:24 +08:00
1 parent 6e046575ac
commit 34c8b7d6ec
1 file changed
+13 -2
+13 -2
View File
@@ -251,11 +251,22 @@ fn highlight_substring(line: &str, start: usize, length: usize) -> String {
if line.len() < start + length { if line.len() < start + length {
return line.into(); return line.into();
} }
// Source spans are byte offsets, which may fall inside a multi-byte
// character (CJK templates are a common case). Snap outwards to the
// nearest char boundaries before slicing.
let mut start = start.min(line.len());
while start > 0 && !line.is_char_boundary(start) {
start -= 1;
}
let mut end = (start + length).min(line.len());
while end < line.len() && !line.is_char_boundary(end) {
end += 1;
}
format![ format![
"{}{}{}", "{}{}{}",
&line[..start], &line[..start],
(&line[start..start + length]).bold(), (&line[start..end]).bold(),
line[start + length..].trim_end(), line[end..].trim_end(),
] ]
} }