Skip to content

Commit 56fdcf5

Browse files
committed
test utils, fix one off error in bytes_till_null
1 parent af998de commit 56fdcf5

File tree

1 file changed

+68
-1
lines changed

1 file changed

+68
-1
lines changed

src/utils.rs

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pub unsafe fn bytes_till_null<'a>(ptr: *const libc::c_char) -> &'a [u8] {
99
ptr = ptr.add(1);
1010
len += 1;
1111
}
12-
core::slice::from_raw_parts(start, len - 1)
12+
core::slice::from_raw_parts(start, len)
1313
}
1414

1515
pub unsafe fn cstr_to_str<'a>(ptr: *const libc::c_char) -> &'a str {
@@ -31,3 +31,70 @@ pub unsafe fn eq_cstr_str(cstr: *const libc::c_char, str: &str) -> bool {
3131
}
3232
}
3333
}
34+
35+
#[cfg(test)]
36+
mod tests {
37+
use super::*;
38+
39+
#[test]
40+
fn test_bytes_till_null() {
41+
let bytes_null = b"abcdef\0";
42+
let bytes = b"abcdef";
43+
assert_eq!(
44+
unsafe { bytes_till_null(bytes_null.as_ptr().cast()) },
45+
bytes
46+
);
47+
}
48+
49+
#[test]
50+
fn test_bytes_till_null_null() {
51+
assert_eq!(unsafe { bytes_till_null(core::ptr::null()) }, &[]);
52+
}
53+
54+
#[test]
55+
fn test_cstr_to_str() {
56+
let cstr = b"abcdef\0";
57+
let str = "abcdef";
58+
assert_eq!(unsafe { cstr_to_str(cstr.as_ptr().cast()) }, str);
59+
}
60+
61+
#[test]
62+
fn test_eq_cstr_str_is_eq() {
63+
let cstr = b"abcdef\0";
64+
let str = "abcdef";
65+
assert!(unsafe { eq_cstr_str(cstr.as_ptr().cast(), str) });
66+
}
67+
68+
#[test]
69+
fn test_eq_cstr_str_is_null() {
70+
assert!(unsafe { !eq_cstr_str(core::ptr::null(), "") });
71+
}
72+
73+
#[test]
74+
fn test_eq_cstr_str_is_neq() {
75+
let cstr = b"abcdef\0";
76+
let str = "abcgef";
77+
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
78+
}
79+
80+
#[test]
81+
fn test_eq_cstr_str_is_neq_null() {
82+
let cstr = b"abcdef\0";
83+
let str = "abcdef\0";
84+
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
85+
}
86+
87+
#[test]
88+
fn test_eq_cstr_str_is_neq_beyond() {
89+
let cstr = b"abcdef\0";
90+
let str = "abcdef\0agsdg";
91+
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
92+
}
93+
94+
#[test]
95+
fn test_eq_cstr_str_is_neq_short() {
96+
let cstr = b"abcdef\0";
97+
let str = "abc";
98+
assert!(unsafe { !eq_cstr_str(cstr.as_ptr().cast(), str) });
99+
}
100+
}

0 commit comments

Comments
 (0)