From 57e90533a00951b00075fbc698d07bb47dfa24d8 Mon Sep 17 00:00:00 2001 From: Riccardo Attilio Galli Date: Sun, 4 Feb 2024 09:53:39 -0800 Subject: [PATCH] searcher: add more tests for `replace_bytes` ... and add a comment explaining an optimization. Closes #2729 --- crates/searcher/src/line_buffer.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/searcher/src/line_buffer.rs b/crates/searcher/src/line_buffer.rs index e73c6504..2a7ff09f 100644 --- a/crates/searcher/src/line_buffer.rs +++ b/crates/searcher/src/line_buffer.rs @@ -538,6 +538,11 @@ fn replace_bytes( while let Some(i) = bytes.find_byte(src) { bytes[i] = replacement; bytes = &mut bytes[i + 1..]; + + // To search for adjacent `src` bytes we use a different strategy. + // Since binary data tends to have long runs of NUL terminators, + // it is faster to compare one-byte-at-a-time than to stop and start + // memchr (through `find_byte`) for every byte in a sequence. while bytes.get(0) == Some(&src) { bytes[0] = replacement; bytes = &mut bytes[1..]; @@ -577,6 +582,9 @@ and exhibited clearly, with a label attached.\ #[test] fn replace() { + assert_eq!(replace_str("", b'b', b'z'), (s(""), None)); + assert_eq!(replace_str("a", b'a', b'a'), (s("a"), None)); + assert_eq!(replace_str("a", b'b', b'z'), (s("a"), None)); assert_eq!(replace_str("abc", b'b', b'z'), (s("azc"), Some(1))); assert_eq!(replace_str("abb", b'b', b'z'), (s("azz"), Some(1))); assert_eq!(replace_str("aba", b'a', b'z'), (s("zbz"), Some(0)));