Skip to content

Commit 325f410

Browse files
committed
Add strchr.
1 parent 66890fb commit 325f410

File tree

5 files changed

+67
-1
lines changed

5 files changed

+67
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ This crate basically came about so that the [nrfxlib](https://github.com/NordicP
1515
* strlen
1616
* strtol
1717
* strstr
18+
* strchr
1819
* snprintf
1920
* vsnprintf
2021

rustfmt.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
hard_tabs = false
2+

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ pub use self::strtol::strtol;
2828
mod strstr;
2929
pub use self::strstr::strstr;
3030

31+
mod strchr;
32+
pub use self::strchr::strchr;
33+
3134
mod atoi;
3235
pub use self::atoi::atoi;
3336

src/strchr.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
}

src/strlen.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,5 +34,4 @@ mod test {
3434
fn test3() {
3535
assert_eq!(unsafe { strlen(b"X\0" as *const CChar) }, 1);
3636
}
37-
3837
}

0 commit comments

Comments
 (0)