|
| 1 | +//! Rust implementation of C library function `strstr` |
| 2 | +//! |
| 3 | +//! Copyright (c) Jonathan 'theJPster' Pallant 2019 |
| 4 | +//! Licensed under the Blue Oak Model Licence 1.0.0 |
| 5 | +
|
| 6 | +use crate::CStringIter; |
| 7 | + |
| 8 | +/// Rust implementation of C library function `strstr` |
| 9 | +#[no_mangle] |
| 10 | +pub unsafe extern "C" fn strstr( |
| 11 | + haystack: *const crate::CChar, |
| 12 | + needle: *const crate::CChar, |
| 13 | +) -> *const crate::CChar { |
| 14 | + if *needle.offset(0) == 0 { |
| 15 | + return haystack; |
| 16 | + } |
| 17 | + for haystack_trim in (0..).map(|idx| haystack.offset(idx)) { |
| 18 | + if *haystack_trim == 0 { |
| 19 | + break; |
| 20 | + } |
| 21 | + let mut len = 0; |
| 22 | + for (inner_idx, nec) in CStringIter::new(needle).enumerate() { |
| 23 | + let hsc = *haystack_trim.offset(inner_idx as isize); |
| 24 | + if hsc != nec { |
| 25 | + break; |
| 26 | + } |
| 27 | + len += 1; |
| 28 | + } |
| 29 | + if *needle.offset(len) == 0 { |
| 30 | + return haystack_trim; |
| 31 | + } |
| 32 | + } |
| 33 | + core::ptr::null() |
| 34 | +} |
| 35 | + |
| 36 | +#[cfg(test)] |
| 37 | +mod test { |
| 38 | + use super::*; |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn no_match() { |
| 42 | + let needle = b"needle\0".as_ptr(); |
| 43 | + let haystack = b"haystack\0".as_ptr(); |
| 44 | + let result = unsafe { strstr(haystack, needle) }; |
| 45 | + assert_eq!(result, core::ptr::null()); |
| 46 | + } |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn start() { |
| 50 | + let needle = b"hay\0".as_ptr(); |
| 51 | + let haystack = b"haystack\0".as_ptr(); |
| 52 | + let result = unsafe { strstr(haystack, needle) }; |
| 53 | + assert_eq!(result, haystack); |
| 54 | + } |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn middle() { |
| 58 | + let needle = b"yst\0".as_ptr(); |
| 59 | + let haystack = b"haystack\0".as_ptr(); |
| 60 | + let result = unsafe { strstr(haystack, needle) }; |
| 61 | + assert_eq!(result, unsafe { haystack.offset(2) }); |
| 62 | + } |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn end() { |
| 66 | + let needle = b"stack\0".as_ptr(); |
| 67 | + let haystack = b"haystack\0".as_ptr(); |
| 68 | + let result = unsafe { strstr(haystack, needle) }; |
| 69 | + assert_eq!(result, unsafe { haystack.offset(3) }); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn partial() { |
| 74 | + let needle = b"haystacka\0".as_ptr(); |
| 75 | + let haystack = b"haystack\0".as_ptr(); |
| 76 | + let result = unsafe { strstr(haystack, needle) }; |
| 77 | + assert_eq!(result, core::ptr::null()); |
| 78 | + } |
| 79 | +} |
0 commit comments