Skip to content
Snippets Groups Projects
Unverified Commit 639ea091 authored by Jeremy Soller's avatar Jeremy Soller Committed by GitHub
Browse files

Merge pull request #56 from Arcterus/master

string: address performance concerns for strncmp()
parents 3890ec58 cfc1014c
No related branches found
No related tags found
No related merge requests found
...@@ -156,25 +156,17 @@ pub unsafe extern "C" fn strncat(s1: *mut c_char, s2: *const c_char, n: usize) - ...@@ -156,25 +156,17 @@ pub unsafe extern "C" fn strncat(s1: *mut c_char, s2: *const c_char, n: usize) -
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn strncmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int { pub unsafe extern "C" fn strncmp(s1: *const c_char, s2: *const c_char, n: usize) -> c_int {
let s1 = platform::c_str_n(s1, n); let s1 = core::slice::from_raw_parts(s1 as *const c_uchar, n);
let s2 = platform::c_str_n(s2, n); let s2 = core::slice::from_raw_parts(s2 as *const c_uchar, n);
let min_len = n.min(s1.len()).min(s2.len()); for (&a, &b) in s1.iter().zip(s2.iter()) {
for i in 0..min_len { let val = (a as c_int) - (b as c_int);
let val = s1[i] - s2[i]; if a != b || a == 0 {
if val != 0 { return val;
return val as c_int;
} }
} }
// we can't just check for the NUL byte in the loop as c_str_n() removes it 0
if s1.len() > s2.len() {
s1[min_len] as c_int
} else if s1.len() < s2.len() {
-(s2[min_len] as c_int)
} else {
0
}
} }
#[no_mangle] #[no_mangle]
......
...@@ -27,5 +27,6 @@ ...@@ -27,5 +27,6 @@
/rmdir /rmdir
/setid /setid
/stdlib/strtol /stdlib/strtol
/string/strncmp
/unlink /unlink
/write /write
...@@ -21,7 +21,8 @@ BINS=\ ...@@ -21,7 +21,8 @@ BINS=\
rmdir \ rmdir \
setid \ setid \
sleep \ sleep \
stdlib/strtol \ stdlib/strtol \
string/strncmp \
unlink \ unlink \
write write
......
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
printf("%d\n", strncmp("a", "aa", 2));
printf("%d\n", strncmp("a", "aä", 2));
printf("%d\n", strncmp("\xFF", "\xFE", 2));
printf("%d\n", strncmp("", "\xFF", 1));
printf("%d\n", strncmp("a", "c", 1));
printf("%d\n", strncmp("a", "a", 2));
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment