Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
* [#23] - Add `strncasecmp`

## v0.3.0 (2022-10-18)

Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ all = [
"abs",
"strcmp",
"strncmp",
"strncasecmp",
"strcpy",
"strncpy",
"strlen",
Expand All @@ -46,6 +47,7 @@ all = [
abs = []
strcmp = []
strncmp = []
strncasecmp = []
strcpy = []
strncpy = []
strlen = []
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ This crate basically came about so that the [nrfxlib](https://github.com/NordicP
* isupper
* strcmp
* strncmp
* strncasecmp
* strcpy
* strncpy
* strlen
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ mod strncmp;
#[cfg(feature = "strncmp")]
pub use self::strncmp::strncmp;

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

mod strcpy;
#[cfg(feature = "strcpy")]
pub use self::strcpy::strcpy;
Expand Down
53 changes: 53 additions & 0 deletions src/strncasecmp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! Rust implementation of C library function `strncasecmp`
//!
//! Licensed under the Blue Oak Model Licence 1.0.0

use crate::{CChar, CInt};

/// Rust implementation of C library function `strncasecmp`. Passing NULL
/// (core::ptr::null()) gives undefined behaviour.
#[cfg_attr(feature = "strncasecmp", no_mangle)]
pub unsafe extern "C" fn strncasecmp(s1: *const CChar, s2: *const CChar, n: usize) -> CInt {
for i in 0..n {
let s1_i = s1.add(i);
let s2_i = s2.add(i);

let val = (*s1_i).to_ascii_lowercase() as CInt - (*s2_i).to_ascii_lowercase() as CInt;
if val != 0 || *s1_i == 0 {
return val;
}
}
0
}

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

#[test]
fn matches() {
let a = b"abc\0";
let b = b"AbCDEF\0";
let result = unsafe { strncasecmp(a.as_ptr(), b.as_ptr(), 3) };
// Match!
assert_eq!(result, 0);
}

#[test]
fn no_match() {
let a = b"123\0";
let b = b"x1234\0";
let result = unsafe { strncasecmp(a.as_ptr(), b.as_ptr(), 3) };
// No match, first string first
assert!(result < 0);
}

#[test]
fn no_match2() {
let a = b"bbbbb\0";
let b = b"aaaaa\0";
let result = unsafe { strncasecmp(a.as_ptr(), b.as_ptr(), 3) };
// No match, second string first
assert!(result > 0);
}
}