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
use crate::{CChar, CInt};
#[no_mangle]
pub unsafe extern "C" fn strchr(haystack: *const CChar, needle: CInt) -> *const CChar {
for idx in 0.. {
let ptr = haystack.offset(idx);
if needle == (*ptr) as i32 {
return ptr;
}
if (*ptr) == 0 {
break;
}
}
core::ptr::null()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn no_match() {
let haystack = b"haystack\0".as_ptr();
let result = unsafe { strchr(haystack, b'X' as CInt) };
assert_eq!(result, core::ptr::null());
}
#[test]
fn null() {
let haystack = b"haystack\0".as_ptr();
let result = unsafe { strchr(haystack, 0) };
assert_eq!(result, unsafe { haystack.offset(8) });
}
#[test]
fn start() {
let haystack = b"haystack\0".as_ptr();
let result = unsafe { strchr(haystack, b'h' as CInt) };
assert_eq!(result, haystack);
}
#[test]
fn middle() {
let haystack = b"haystack\0".as_ptr();
let result = unsafe { strchr(haystack, b'y' as CInt) };
assert_eq!(result, unsafe { haystack.offset(2) });
}
#[test]
fn end() {
let haystack = b"haystack\0".as_ptr();
let result = unsafe { strchr(haystack, b'k' as CInt) };
assert_eq!(result, unsafe { haystack.offset(7) });
}
}