Browse Source

Add memrchr()

Mateusz Mikuła 5 years ago
parent
commit
d62db7b1b9
3 changed files with 20 additions and 0 deletions
  1. 14 0
      src/header/string/mod.rs
  2. 1 0
      tests/expected/string/mem.stdout
  3. 5 0
      tests/string/mem.c

+ 14 - 0
src/header/string/mod.rs

@@ -107,6 +107,20 @@ pub unsafe extern "C" fn memmove(s1: *mut c_void, s2: *const c_void, n: size_t)
     s1
 }
 
+#[no_mangle]
+pub unsafe extern "C" fn memrchr(
+    haystack: *const c_void,
+    needle: c_int,
+    len: size_t,
+) -> *mut c_void {
+    let haystack = slice::from_raw_parts(haystack as *const u8, len as usize);
+
+    match memchr::memrchr(needle as u8, haystack) {
+        Some(index) => haystack[index..].as_ptr() as *mut c_void,
+        None => ptr::null_mut(),
+    }
+}
+
 #[no_mangle]
 pub unsafe extern "C" fn memset(s: *mut c_void, c: c_int, n: size_t) -> *mut c_void {
     for i in 0..n {

+ 1 - 0
tests/expected/string/mem.stdout

@@ -1,4 +1,5 @@
 # mem #
 Correct memchr
+Correct memrchr
 Correct memccpy
 Correct memcmp

+ 5 - 0
tests/string/mem.c

@@ -14,6 +14,11 @@ int main(void) {
         exit(EXIT_FAILURE);
     }
     puts("Correct memchr");
+    if ((size_t)memrchr((void *)arr, 1, 100) - (size_t)arr != 50) {
+        puts("Incorrect memrchr");
+        exit(EXIT_FAILURE);
+    }
+    puts("Correct memrchr");
     char arr2[51];
     memset(arr2, 0, 51); // Compiler builtin, should work
     memccpy((void *)arr2, (void *)arr, 1, 100);