79427341

Date: 2025-02-10 14:17:23
Score: 1
Natty:
Report link

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

Reasons:
  • Probably link only (1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: PapEr