Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add memchr #26

Merged
merged 5 commits into from
Mar 30, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Unreleased

* None
* [#26] - Add `memchr`

## v0.4.0 (2024-03-22)

Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ all = [
"isdigit",
"isalpha",
"isupper",
"memchr",
]
abs = []
strcmp = []
Expand All @@ -68,5 +69,6 @@ isdigit = []
isalpha = []
isupper = []
alloc = []
memchr = []
signal = ["dep:portable-atomic"]
signal-cs = ["portable-atomic/critical-section"]
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This crate basically came about so that the [nrfxlib](https://github.com/NordicP
* isdigit
* isalpha
* isupper
* memchr
* strcmp
* strncmp
* strncasecmp
Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ mod signal;
#[cfg(feature = "signal")]
pub use self::signal::{abort, raise, signal};

#[cfg(feature = "memchr")]
mod memchr;
#[cfg(feature = "memchr")]
pub use self::memchr::memchr;

mod snprintf;

mod ctype;
Expand Down
45 changes: 45 additions & 0 deletions src/memchr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//! Rust implementation of C library function `memchr`
//!
//! Licensed under the Blue Oak Model Licence 1.0.0

use crate::{CChar, CInt, CSizeT, CVoid};

/// Rust implementation of C library function `memchr`
#[cfg_attr(feature = "memchr", no_mangle)]
pub unsafe extern "C" fn memchr(s: *const CVoid, c: CInt, n: CSizeT) -> *const CVoid {
let s = s as *const CChar;
for i in 0..n {
if *s.add(i) as CInt == c {
return s.add(i) as *const CVoid;
}
}
core::ptr::null()
}

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

#[test]
fn null() {
unsafe { assert_eq!(memchr(core::ptr::null(), 0, 0), core::ptr::null()) };
}

#[test]
fn normal() {
let s = b"hello world";
assert_eq!(
unsafe { memchr(s.as_ptr() as *const CVoid, b'w' as CInt, s.len() as CSizeT) },
unsafe { s.as_ptr().offset(6) } as *const CVoid
);
}

#[test]
fn not_found() {
let s = b"hello world";
assert_eq!(
unsafe { memchr(s.as_ptr() as *const CVoid, b'x' as CInt, s.len() as CSizeT) },
core::ptr::null()
)
}
}
Loading