| 1 | /*! |
| 2 | This module defines "naive" implementations of substring search. |
| 3 | |
| 4 | These are sometimes useful to compare with "real" substring implementations. |
| 5 | The idea is that they are so simple that they are unlikely to be incorrect. |
| 6 | */ |
| 7 | |
| 8 | /// Naively search forwards for the given needle in the given haystack. |
| 9 | pub(crate) fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 10 | let end = haystack.len().checked_sub(needle.len()).map_or(0, |i| i + 1); |
| 11 | for i in 0..end { |
| 12 | if needle == &haystack[i..i + needle.len()] { |
| 13 | return Some(i); |
| 14 | } |
| 15 | } |
| 16 | None |
| 17 | } |
| 18 | |
| 19 | /// Naively search in reverse for the given needle in the given haystack. |
| 20 | pub(crate) fn rfind(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 21 | let end = haystack.len().checked_sub(needle.len()).map_or(0, |i| i + 1); |
| 22 | for i in (0..end).rev() { |
| 23 | if needle == &haystack[i..i + needle.len()] { |
| 24 | return Some(i); |
| 25 | } |
| 26 | } |
| 27 | None |
| 28 | } |
| 29 | |
| 30 | #[cfg (test)] |
| 31 | mod tests { |
| 32 | use crate::tests::substring; |
| 33 | |
| 34 | use super::*; |
| 35 | |
| 36 | #[test] |
| 37 | fn forward() { |
| 38 | substring::Runner::new().fwd(|h, n| Some(find(h, n))).run() |
| 39 | } |
| 40 | |
| 41 | #[test] |
| 42 | fn reverse() { |
| 43 | substring::Runner::new().rev(|h, n| Some(rfind(h, n))).run() |
| 44 | } |
| 45 | } |
| 46 | |