1
0
mirror of https://github.com/BurntSushi/ripgrep.git synced 2025-03-17 20:28:03 +02:00

searcher: simplify 'replace_bytes' routine

I did this in the course of trying to optimize it. I don't believe I
made it any faster, but the refactoring led to code that I think is
more readable.
This commit is contained in:
Andrew Gallant 2023-10-08 14:49:18 -04:00
parent b9de003f81
commit f7ff34fdf9

View File

@ -524,24 +524,26 @@ impl LineBuffer {
/// Replaces `src` with `replacement` in bytes, and return the offset of the /// Replaces `src` with `replacement` in bytes, and return the offset of the
/// first replacement, if one exists. /// first replacement, if one exists.
fn replace_bytes(bytes: &mut [u8], src: u8, replacement: u8) -> Option<usize> { fn replace_bytes(
mut bytes: &mut [u8],
src: u8,
replacement: u8,
) -> Option<usize> {
if src == replacement { if src == replacement {
return None; return None;
} }
let mut first_pos = None; let first_pos = bytes.find_byte(src)?;
let mut pos = 0; bytes[first_pos] = replacement;
while let Some(i) = bytes[pos..].find_byte(src).map(|i| pos + i) { bytes = &mut bytes[first_pos + 1..];
if first_pos.is_none() { while let Some(i) = bytes.find_byte(src) {
first_pos = Some(i);
}
bytes[i] = replacement; bytes[i] = replacement;
pos = i + 1; bytes = &mut bytes[i + 1..];
while bytes.get(pos) == Some(&src) { while bytes.get(0) == Some(&src) {
bytes[pos] = replacement; bytes[0] = replacement;
pos += 1; bytes = &mut bytes[1..];
} }
} }
first_pos Some(first_pos)
} }
#[cfg(test)] #[cfg(test)]