Small text-handling utilities shared across crates. Returns the longest prefix of `s` whose byte length does not exceed `max_bytes`, snapping back to the nearest preceding UTF-8 char boundary when the budget lands inside a multi-byte character. This is the safe replacement for `&s[..max_bytes]` when `s` may contain non-ASCII text and the caller has a byte budget rather than a char budget.
(s: &str, max_bytes: usize)
| 7 | /// This is the safe replacement for `&s[..max_bytes]` when `s` may contain |
| 8 | /// non-ASCII text and the caller has a byte budget rather than a char budget. |
| 9 | pub fn utf8_prefix_at_or_before(s: &str, max_bytes: usize) -> &str { |
| 10 | if s.len() <= max_bytes { |
| 11 | return s; |
| 12 | } |
| 13 | |
| 14 | let mut end = max_bytes; |
| 15 | while !s.is_char_boundary(end) && end > 0 { |
| 16 | end -= 1; |
| 17 | } |
| 18 | &s[..end] |
| 19 | } |
| 20 | |
| 21 | #[cfg(test)] |
| 22 | mod tests { |
no outgoing calls
no test coverage detected