Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 3 additions & 24 deletions src/bun_core/string/immutable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> {
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<usize> {
bstr::ByteSlice::find(haystack, needle)
highway::memmem(haystack, needle)
}

/// `bun.reinterpretSlice` — `&[T]` → `&[u8]` view (T must be u8/u16 in practice).
Expand Down
32 changes: 32 additions & 0 deletions src/highway/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -140,6 +147,31 @@ pub fn index_of_char(haystack: &[u8], needle: u8) -> Option<usize> {
Some(result)
}

#[inline(always)]
pub fn memmem(haystack: &[u8], needle: &[u8]) -> Option<usize> {
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],
Expand Down
Loading