Skip to content

Commit

Permalink
test utils, fix one off error in bytes_till_null
Browse files Browse the repository at this point in the history
  • Loading branch information
Veykril committed Jan 28, 2020
1 parent af998de commit 56fdcf5
Showing 1 changed file with 68 additions and 1 deletion.
69 changes: 68 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub unsafe fn bytes_till_null<'a>(ptr: *const libc::c_char) -> &'a [u8] {
ptr = ptr.add(1);
len += 1;
}
core::slice::from_raw_parts(start, len - 1)
core::slice::from_raw_parts(start, len)
}

pub unsafe fn cstr_to_str<'a>(ptr: *const libc::c_char) -> &'a str {
Expand All @@ -31,3 +31,70 @@ pub unsafe fn eq_cstr_str(cstr: *const libc::c_char, str: &str) -> bool {
}
}
}

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

#[test]
fn test_bytes_till_null() {
let bytes_null = b"abcdef\0";
let bytes = b"abcdef";
assert_eq!(
unsafe { bytes_till_null(bytes_null.as_ptr().cast()) },
bytes
);
}

#[test]
fn test_bytes_till_null_null() {
assert_eq!(unsafe { bytes_till_null(core::ptr::null()) }, &[]);
}

#[test]
fn test_cstr_to_str() {
let cstr = b"abcdef\0";
let str = "abcdef";
assert_eq!(unsafe { cstr_to_str(cstr.as_ptr().cast()) }, str);
}

#[test]
fn test_eq_cstr_str_is_eq() {
let cstr = b"abcdef\0";
let str = "abcdef";
assert!(unsafe { eq_cstr_str(cstr.as_ptr().cast(), str) });
}

#[test]
fn test_eq_cstr_str_is_null() {
assert!(unsafe { !eq_cstr_str(core::ptr::null(), "") });
}

#[test]
fn test_eq_cstr_str_is_neq() {
let cstr = b"abcdef\0";
let str = "abcgef";
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
}

#[test]
fn test_eq_cstr_str_is_neq_null() {
let cstr = b"abcdef\0";
let str = "abcdef\0";
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
}

#[test]
fn test_eq_cstr_str_is_neq_beyond() {
let cstr = b"abcdef\0";
let str = "abcdef\0agsdg";
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
}

#[test]
fn test_eq_cstr_str_is_neq_short() {
let cstr = b"abcdef\0";
let str = "abc";
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
}
}

0 comments on commit 56fdcf5

Please sign in to comment.