4 ms·
You might be entirely correct. I noticed a small perf issue with the backwards scanning and had it rewrite it not using rfind("_"). First time I prompted it,
by lamontcg 4y ago
You might be entirely correct. I noticed a small perf issue with the backwards scanning and had it rewrite it not using rfind("_"). First time I prompted it, though, it didn't actually manage to fix the problem and gave me some mild gaslighting until I told it to explicitly remove the rfind() call. Now I think the result should be comparable to or beat a regexp, but it is getting quite a bit more complex:
fn strip_suffix(s: &str) -> String {
let mut idx = s.len();
for (i, c) in s.char_indices().rev() {
if c == '_' {
idx = i;
break;
} else if !c.is_ascii_digit() {
return s.to_string();
}
}
if idx == s.len() {
return s.to_string();
}
if s[idx+1..].chars().all(|c| c.is_ascii_digit()) {
return s[..idx].to_string();
}
s.to_string()
}
.char_indexes().rev() there worries me a bit as well now that I look at it... haven't tested that at all.
- lamontcg 4y agoAh, it looks like char_indexes() implements DoubleEndedIterator and you can only call rev() on an iterator that does implement it, so that's fine.
- textninja 4y agoIt took some coaching to get it to use the terse style I prefer, but here’s what 3.5 came up with in a conversation where I first asked about Rust’s support for regular expressions: use regex::Regex; fn strip_suffix_digits(s: &str) -> &str { let re = Regex::new(r"_\d+$").unwrap(); re.replace(s, "").as_ref() } As someone who does not program in Rust I find that quite readable, though I haven’t run it and can’t comment on how it compares outside of LOC. It does depend on the regex crate though.
- lamontcg 4y agoYeah I got basically the same sort of result out of it by asking for a Regexp, much shorter.