1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//! Rust implementation of C library function `strstr`
//!
//! Copyright (c) Jonathan 'theJPster' Pallant 2019
//! Licensed under the Blue Oak Model Licence 1.0.0

use crate::{CChar, CStringIter};

/// Rust implementation of C library function `strstr`
#[no_mangle]
pub unsafe extern "C" fn strstr(haystack: *const CChar, needle: *const CChar) -> *const CChar {
    if *needle.offset(0) == 0 {
        return haystack;
    }
    for haystack_trim in (0..).map(|idx| haystack.offset(idx)) {
        if *haystack_trim == 0 {
            break;
        }
        let mut len = 0;
        for (inner_idx, nec) in CStringIter::new(needle).enumerate() {
            let hsc = *haystack_trim.offset(inner_idx as isize);
            if hsc != nec {
                break;
            }
            len += 1;
        }
        if *needle.offset(len) == 0 {
            return haystack_trim;
        }
    }
    core::ptr::null()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn no_match() {
        let needle = b"needle\0".as_ptr();
        let haystack = b"haystack\0".as_ptr();
        let result = unsafe { strstr(haystack, needle) };
        assert_eq!(result, core::ptr::null());
    }

    #[test]
    fn start() {
        let needle = b"hay\0".as_ptr();
        let haystack = b"haystack\0".as_ptr();
        let result = unsafe { strstr(haystack, needle) };
        assert_eq!(result, haystack);
    }

    #[test]
    fn middle() {
        let needle = b"yst\0".as_ptr();
        let haystack = b"haystack\0".as_ptr();
        let result = unsafe { strstr(haystack, needle) };
        assert_eq!(result, unsafe { haystack.offset(2) });
    }

    #[test]
    fn end() {
        let needle = b"stack\0".as_ptr();
        let haystack = b"haystack\0".as_ptr();
        let result = unsafe { strstr(haystack, needle) };
        assert_eq!(result, unsafe { haystack.offset(3) });
    }

    #[test]
    fn partial() {
        let needle = b"haystacka\0".as_ptr();
        let haystack = b"haystack\0".as_ptr();
        let result = unsafe { strstr(haystack, needle) };
        assert_eq!(result, core::ptr::null());
    }
}