Skip to content

Commit

Permalink
Fix Regex::replacen when replacing an empty match.
Browse files Browse the repository at this point in the history
  • Loading branch information
Lapin0t authored and Ethan Pailes committed Nov 28, 2017
1 parent cd4ebd3 commit 86394bf
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
9 changes: 5 additions & 4 deletions src/re_bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,19 +494,20 @@ impl Regex {
mut rep: R,
) -> Cow<'t, [u8]> {
if let Some(rep) = rep.no_expansion() {
let mut it = self.find_iter(text).enumerate().peekable();
if it.peek().is_none() {
return Cow::Borrowed(text);
}
let mut new = Vec::with_capacity(text.len());
let mut last_match = 0;
for (i, m) in self.find_iter(text).enumerate() {
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 last_match == 0 {
return Cow::Borrowed(text);
}
new.extend_from_slice(&text[last_match..]);
return Cow::Owned(new);
}
Expand Down
9 changes: 5 additions & 4 deletions src/re_unicode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,19 +583,20 @@ impl Regex {
// replacements inside the replacement string. We just push it
// at each match and be done with it.
if let Some(rep) = rep.no_expansion() {
let mut it = self.find_iter(text).enumerate().peekable();
if it.peek().is_none() {
return Cow::Borrowed(text);
}
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, m) in self.find_iter(text).enumerate() {
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 last_match == 0 {
return Cow::Borrowed(text);
}
new.push_str(&text[last_match..]);
return Cow::Owned(new);
}
Expand Down
3 changes: 3 additions & 0 deletions tests/replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ replace!(no_expand2, replace,

// See https://github.com/rust-lang/regex/issues/314
replace!(match_at_start_replace_with_empty, replace_all, r"foo", "foobar", t!(""), "bar");

// See https://github.com/rust-lang/regex/issues/393
replace!(single_empty_match, replace, r"^", "bar", t!("foo"), "foobar");

0 comments on commit 86394bf

Please sign in to comment.