|
| 1 | +//! Rust implementation of C library function `strchr` |
| 2 | +//! |
| 3 | +//! Copyright (c) 42 Technology Ltd |
| 4 | +//! Licensed under the Blue Oak Model Licence 1.0.0 |
| 5 | +
|
| 6 | +use crate::{CChar, CInt}; |
| 7 | + |
| 8 | +/// Rust implementation of C library function `strchr` |
| 9 | +#[no_mangle] |
| 10 | +pub unsafe extern "C" fn strchr(haystack: *const CChar, needle: CInt) -> *const CChar { |
| 11 | + for idx in 0.. { |
| 12 | + let ptr = haystack.offset(idx); |
| 13 | + if needle == (*ptr) as i32 { |
| 14 | + return ptr; |
| 15 | + } |
| 16 | + if (*ptr) == 0 { |
| 17 | + break; |
| 18 | + } |
| 19 | + } |
| 20 | + core::ptr::null() |
| 21 | +} |
| 22 | + |
| 23 | +#[cfg(test)] |
| 24 | +mod test { |
| 25 | + use super::*; |
| 26 | + |
| 27 | + #[test] |
| 28 | + fn no_match() { |
| 29 | + let haystack = b"haystack\0".as_ptr(); |
| 30 | + let result = unsafe { strchr(haystack, b'X' as CInt) }; |
| 31 | + assert_eq!(result, core::ptr::null()); |
| 32 | + } |
| 33 | + |
| 34 | + #[test] |
| 35 | + fn null() { |
| 36 | + let haystack = b"haystack\0".as_ptr(); |
| 37 | + let result = unsafe { strchr(haystack, 0) }; |
| 38 | + assert_eq!(result, unsafe { haystack.offset(8) }); |
| 39 | + } |
| 40 | + |
| 41 | + #[test] |
| 42 | + fn start() { |
| 43 | + let haystack = b"haystack\0".as_ptr(); |
| 44 | + let result = unsafe { strchr(haystack, b'h' as CInt) }; |
| 45 | + assert_eq!(result, haystack); |
| 46 | + } |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn middle() { |
| 50 | + let haystack = b"haystack\0".as_ptr(); |
| 51 | + let result = unsafe { strchr(haystack, b'y' as CInt) }; |
| 52 | + assert_eq!(result, unsafe { haystack.offset(2) }); |
| 53 | + } |
| 54 | + |
| 55 | + #[test] |
| 56 | + fn end() { |
| 57 | + let haystack = b"haystack\0".as_ptr(); |
| 58 | + let result = unsafe { strchr(haystack, b'k' as CInt) }; |
| 59 | + assert_eq!(result, unsafe { haystack.offset(7) }); |
| 60 | + } |
| 61 | +} |
0 commit comments