Created
July 15, 2021 21:31
-
-
Save k12ish/ba9bdb36fe2011186e08c23a1d137f10 to your computer and use it in GitHub Desktop.
Find the byte index of substrings, unambiguously.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::ops::Range; | |
fn main() { | |
let quote = String::from("I scream, you scream, we all scream for ice cream"); | |
assert_eq!("e[2..8], "scream"); | |
assert_eq!("e[14..20], "scream"); | |
assert_eq!("e[29..35], "scream"); | |
// substring_index("e, "scream") | |
assert_eq!(substring_index("e, "e[2..8]), 2..8); | |
assert_eq!(substring_index("e, "e[14..20]), 14..20); | |
assert_eq!(substring_index("e, "e[29..35]), 29..35); | |
// quote.find( "scream" ) | |
assert_eq!(quote.find("e[2..8]), Some(2)); | |
assert_eq!(quote.find("e[14..20]), Some(2)); | |
assert_eq!(quote.find("e[29..35]), Some(2)); | |
} | |
/// Return the range of bytes where substring is in string | |
fn substring_index(string: &str, substring: &str) -> Range<usize> { | |
let start_ptr: *const u8 = string.as_ptr(); | |
let substring_ptr: *const u8 = substring.as_ptr(); | |
let end_ptr: *const u8; | |
// SAFETY: | |
// | |
// “Boxed types never allocate more than isize::MAX bytes, so | |
// vec.as_ptr().add(vec.len()) is always safe.” | |
// | |
// --- https://doc.rust-lang.org/std/primitive.pointer.html#safety-5 | |
unsafe { | |
end_ptr = start_ptr.add(string.len()); | |
} | |
// Check if we have a 'true' substring, ie start_ptr <= substring_ptr <= end_ptr | |
assert!(start_ptr <= substring_ptr && substring_ptr <= end_ptr); | |
let start; | |
// SAFETY: | |
// The pointers are in bounds, derived from same object and a multiple | |
// of 8 bits apart. | |
// This operation is equivalent to `ptr_into_vec.offset_from(vec.as_ptr())`, | |
// so it will never "wrap around" the address space. | |
unsafe { start = substring_ptr.offset_from(start_ptr) as usize } | |
Range { | |
start, | |
end: start + substring.len(), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is left is to write a few tests:
Then check for undefined behaviour using miri: