MCPcopy Create free account
hub / github.com/ScriptedAlchemy/tracedecay / utf8_prefix_at_or_before

Function utf8_prefix_at_or_before

src/text.rs:9–19  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.
9pub 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)]
22mod tests {

Callers 2

insert_atMethod · 0.85
extract_code_blocksMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected