diff options
author | Kartikaya Gupta <kgupta@mozilla.com> | 2016-06-10 10:31:52 -0400 |
---|---|---|
committer | Kartikaya Gupta <kgupta@mozilla.com> | 2016-06-10 10:31:52 -0400 |
commit | 59516ab0654b09d8f0254b9aaa10d985b9fc2e2d (patch) | |
tree | f8f87ca10bb33677c4cd78a5e306dc7494e9dd63 | |
parent | 1ff94b2e0ee4c7cc3406a1e73603aeecd1271c1b (diff) |
Add a helper find_from_u8 function
-rw-r--r-- | src/lib.rs | 33 |
1 files changed, 33 insertions, 0 deletions
@@ -79,6 +79,39 @@ fn find_from(line: &str, ix_start: usize, key: &str) -> Option<usize> { line[ix_start..].find(key).map(|v| ix_start + v) } +fn find_from_u8(line: &[u8], ix_start: usize, key: &[u8]) -> Option<usize> { + assert!(key.len() > 0); + assert!(ix_start < line.len()); + let ix_end = line.len() - key.len(); + if ix_start <= ix_end { + for i in ix_start..ix_end { + if line[i] == key[0] { + let mut success = true; + for j in 1..key.len() { + if line[i + j] != key[j] { + success = false; + break; + } + } + if success { + return Some(i); + } + } + } + } + None +} + +#[test] +fn test_find_from_u8() { + assert_eq!(find_from_u8(b"hello world", 0, b"hell"), Some(0)); + assert_eq!(find_from_u8(b"hello world", 0, b"o"), Some(4)); + assert_eq!(find_from_u8(b"hello world", 4, b"o"), Some(4)); + assert_eq!(find_from_u8(b"hello world", 5, b"o"), Some(7)); + assert_eq!(find_from_u8(b"hello world", 8, b"o"), None); + assert_eq!(find_from_u8(b"hello world", 10, b"d"), None); +} + impl<'a> MailHeader<'a> { pub fn get_key(&self) -> Result<String, MailParseError> { Ok(try!(encoding::all::ISO_8859_1.decode(self.key, encoding::DecoderTrap::Strict)) |