Skip to content

Commit

Permalink
Use memmem for finding needle in haystack
Browse files Browse the repository at this point in the history
  • Loading branch information
topjohnwu committed Apr 10, 2024
1 parent ffc1e38 commit c50ee72
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
31 changes: 30 additions & 1 deletion native/src/base/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,40 @@ impl<T> LibcReturn for *mut T {
}
}

pub trait BytesExt {
fn find(&self, needle: &[u8]) -> Option<usize>;
fn contains(&self, needle: &[u8]) -> bool {
self.find(needle).is_some()
}
}

impl<T: AsRef<[u8]> + ?Sized> BytesExt for T {
fn find(&self, needle: &[u8]) -> Option<usize> {
fn inner(haystack: &[u8], needle: &[u8]) -> Option<usize> {
unsafe {
let ptr: *const u8 = libc::memmem(
haystack.as_ptr().cast(),
haystack.len(),
needle.as_ptr().cast(),
needle.len(),
)
.cast();
if ptr.is_null() {
None
} else {
Some(ptr.offset_from(haystack.as_ptr()) as usize)
}
}
}
inner(self.as_ref(), needle)
}
}

pub trait MutBytesExt {
fn patch(&mut self, from: &[u8], to: &[u8]) -> Vec<usize>;
}

impl<T: AsMut<[u8]>> MutBytesExt for T {
impl<T: AsMut<[u8]> + ?Sized> MutBytesExt for T {
fn patch(&mut self, from: &[u8], to: &[u8]) -> Vec<usize> {
ffi::mut_u8_patch(self.as_mut(), from, to)
}
Expand Down
6 changes: 3 additions & 3 deletions native/src/boot/cpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use base::libc::{
S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR,
};
use base::{
log_err, map_args, EarlyExitExt, FsPath, LoggedResult, MappedFile, ResultExt, Utf8CStr,
WriteExt,
log_err, map_args, BytesExt, EarlyExitExt, FsPath, LoggedResult, MappedFile, ResultExt,
Utf8CStr, WriteExt,
};

use crate::ffi::{unxz, xz};
Expand Down Expand Up @@ -246,7 +246,7 @@ impl Cpio {
continue;
}
if name == "TRAILER!!!" {
match data[pos..].windows(6).position(|x| x == b"070701") {
match data[pos..].find(b"070701") {
Some(x) => pos += x,
None => break,
}
Expand Down

0 comments on commit c50ee72

Please sign in to comment.