I have found a less expensive solution by examining the boundary from the end
to a valid position.
It will only iterate at most three times and remain a &str
fn clip_prompt(s: &str, max_length: usize) -> &str {
if s.len() <= max_length {
return s;
}
let mut end = max_length;
while !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=215b6f1880a6122f4a6dc8cc2b66469b