kernel/records/text_budget.rs
1//! Clipping text to a byte budget without splitting a UTF-8 character.
2
3/// The result of clipping text to a byte cap.
4#[derive(Debug, PartialEq, Eq)]
5pub struct Clip<'a> {
6 /// The kept prefix, never longer than the cap and always char-aligned.
7 pub kept: &'a str,
8 /// Whether the text was longer than the cap and had to be trimmed.
9 pub overflowed: bool,
10 /// The full UTF-8 byte length of the original text.
11 pub total: usize,
12}
13
14/// Clip `text` so its UTF-8 length does not exceed `cap` bytes, trimming back to
15/// the nearest character boundary rather than splitting a multi-byte character.
16pub fn clip(text: &str, cap: usize) -> Clip<'_> {
17 let total = text.len();
18 if total <= cap {
19 return Clip {
20 kept: text,
21 overflowed: false,
22 total,
23 };
24 }
25 let mut end = cap;
26 while end > 0 && !text.is_char_boundary(end) {
27 end -= 1;
28 }
29 Clip {
30 kept: &text[..end],
31 overflowed: true,
32 total,
33 }
34}