pub(crate) fn str_offset(haystack: &str, needle: &str) -> Option<usize> {
let needle_start_u = needle.as_ptr() as usize;
let needle_end_u = needle_start_u + needle.len();
let haystack_start_u = haystack.as_ptr() as usize;
let haystack_end_u = haystack_start_u + haystack.len();
if haystack_start_u <= needle_start_u && needle_end_u <= haystack_end_u {
Some(needle_start_u - haystack_start_u)
} else {
None
}
}
#[derive(Clone, Debug)]
pub(crate) struct Extent {
offset: usize,
length: usize,
sliceptr: *const u8,
slicelen: usize,
}
impl Extent {
pub(crate) fn new(haystack: &str, needle: &str) -> Option<Extent> {
str_offset(haystack, needle).map(|offset| Extent {
offset,
length: needle.len(),
sliceptr: haystack.as_ptr(),
slicelen: haystack.len(),
})
}
pub(crate) fn reconstruct<'a>(&self, haystack: &'a str) -> Option<&'a str> {
if self.sliceptr != haystack.as_ptr() || self.slicelen != haystack.len() {
None
} else {
haystack.get(self.offset..self.offset + self.length)
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#[test]
fn test_str_offset() {
use super::str_offset;
let quote = "A rose is a rose is a rose."; assert_eq!("e[2..6], "rose");
assert_eq!(str_offset(quote, "e[2..6]).unwrap(), 2);
assert_eq!("e[12..16], "rose");
assert_eq!(str_offset(quote, "e[12..16]).unwrap(), 12);
assert_eq!("e[22..26], "rose");
assert_eq!(str_offset(quote, "e[22..26]).unwrap(), 22);
assert_eq!(str_offset(quote, "rose"), None);
assert_eq!(str_offset("e[1..], "e[2..6]), Some(1));
assert_eq!(str_offset("e[1..5], "e[2..6]), None);
}
#[test]
fn test_extent() {
use super::Extent;
let quote = "What is a winter wedding a winter wedding."; assert_eq!("e[10..16], "winter");
let ex = Extent::new(quote, "e[10..16]).unwrap();
let s = ex.reconstruct(quote).unwrap();
assert_eq!(s, "winter");
assert!(Extent::new(quote, "winter").is_none());
assert!(ex.reconstruct("Hello world").is_none());
}
}