Skip to content

Commit

Permalink
Optimize replace/replacen() to avoid unnecessary extra find
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonas Berlin committed Nov 28, 2022
1 parent f871a8e commit f7fd66e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
12 changes: 6 additions & 6 deletions src/re_bytes.rs
Expand Up @@ -496,12 +496,12 @@ impl Regex {
let mut new = Vec::with_capacity(text.len());
let mut last_match = 0;
for (i, m) in it {
if limit > 0 && i >= limit {
break;
}
new.extend_from_slice(&text[last_match..m.start()]);
new.extend_from_slice(&rep);
last_match = m.end();
if limit > 0 && i >= limit - 1 {
break;
}
}
new.extend_from_slice(&text[last_match..]);
return Cow::Owned(new);
Expand All @@ -516,14 +516,14 @@ impl Regex {
let mut new = Vec::with_capacity(text.len());
let mut last_match = 0;
for (i, cap) in it {
if limit > 0 && i >= limit {
break;
}
// unwrap on 0 is OK because captures only reports matches
let m = cap.get(0).unwrap();
new.extend_from_slice(&text[last_match..m.start()]);
rep.replace_append(&cap, &mut new);
last_match = m.end();
if limit > 0 && i >= limit - 1 {
break;
}
}
new.extend_from_slice(&text[last_match..]);
Cow::Owned(new)
Expand Down
12 changes: 6 additions & 6 deletions src/re_unicode.rs
Expand Up @@ -554,12 +554,12 @@ impl Regex {
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, m) in it {
if limit > 0 && i >= limit {
break;
}
new.push_str(&text[last_match..m.start()]);
new.push_str(&rep);
last_match = m.end();
if limit > 0 && i >= limit - 1 {
break;
}
}
new.push_str(&text[last_match..]);
return Cow::Owned(new);
Expand All @@ -574,14 +574,14 @@ impl Regex {
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, cap) in it {
if limit > 0 && i >= limit {
break;
}
// unwrap on 0 is OK because captures only reports matches
let m = cap.get(0).unwrap();
new.push_str(&text[last_match..m.start()]);
rep.replace_append(&cap, &mut new);
last_match = m.end();
if limit > 0 && i >= limit - 1 {
break;
}
}
new.push_str(&text[last_match..]);
Cow::Owned(new)
Expand Down

0 comments on commit f7fd66e

Please sign in to comment.