diff --git a/src/bun_core/string/immutable.rs b/src/bun_core/string/immutable.rs index fc8727ea789a..cdf59aeb9e30 100644 --- a/src/bun_core/string/immutable.rs +++ b/src/bun_core/string/immutable.rs @@ -377,31 +377,10 @@ pub use crate::strings_impl::{ to_utf8_from_latin1_z, u16_lead, u16_trail, }; -/// memmem — libc on posix, scalar fallback on windows. -#[cfg(not(windows))] -pub fn memmem(haystack: &[u8], needle: &[u8]) -> Option { - if needle.is_empty() { - return Some(0); - } - // SAFETY: `&[u8]` guarantees both (ptr,len) pairs are valid for reads; - // libc memmem only reads within those bounds. - let p = unsafe { - libc::memmem( - haystack.as_ptr().cast(), - haystack.len(), - needle.as_ptr().cast(), - needle.len(), - ) - }; - if p.is_null() { - None - } else { - Some(p as usize - haystack.as_ptr() as usize) - } -} -#[cfg(windows)] +/// memmem — `highway_memmem` (HWY_DYNAMIC_DISPATCH MemMemImpl), same on all platforms. +#[inline] pub fn memmem(haystack: &[u8], needle: &[u8]) -> Option { - bstr::ByteSlice::find(haystack, needle) + highway::memmem(haystack, needle) } /// `bun.reinterpretSlice` — `&[T]` → `&[u8]` view (T must be u8/u16 in practice). diff --git a/src/highway/lib.rs b/src/highway/lib.rs index 68f9875cb464..32ddd18bed0e 100644 --- a/src/highway/lib.rs +++ b/src/highway/lib.rs @@ -6,6 +6,13 @@ unsafe extern "C" { fn highway_index_of_char(haystack: *const u8, haystack_len: usize, needle: u8) -> usize; + fn highway_memmem( + haystack: *const u8, + haystack_len: usize, + needle: *const u8, + needle_len: usize, + ) -> *const u8; + fn highway_index_of_interesting_character_in_string_literal( text: *const u8, text_len: usize, @@ -140,6 +147,31 @@ pub fn index_of_char(haystack: &[u8], needle: u8) -> Option { Some(result) } +#[inline(always)] +pub fn memmem(haystack: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() { + return Some(0); + } + if haystack.len() < needle.len() { + return None; + } + // SAFETY: both (ptr,len) pairs are valid readable ranges. + let p = unsafe { + highway_memmem( + haystack.as_ptr(), + haystack.len(), + needle.as_ptr(), + needle.len(), + ) + }; + if p.is_null() { + None + } else { + // SAFETY: highway_memmem returns a pointer within `haystack` on success. + Some(unsafe { p.offset_from(haystack.as_ptr()) } as usize) + } +} + #[inline(always)] pub fn index_of_interesting_character_in_string_literal( slice: &[u8],