Skip to content

Commit 2f74f79

Browse files
authored
Merge pull request #15 from artichoke/lopopolo/imp-contains-nul
Add a `contains_nul` const fn to `imp` module
2 parents 91e6aaa + 2a7cf56 commit 2f74f79

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/imp.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Return the first index, if any, where the given byte occurs.
12
#[must_use]
23
pub const fn find(slice: &[u8], elem: u8) -> Option<usize> {
34
let mut idx = 0;
@@ -12,14 +13,22 @@ pub const fn find(slice: &[u8], elem: u8) -> Option<usize> {
1213
}
1314
}
1415

16+
// Return true if the slice contains a single NUL byte in the last position of
17+
// the slice.
1518
#[must_use]
1619
pub const fn is_cstr(slice: &[u8]) -> bool {
1720
matches!(find(slice, 0), Some(nul_pos) if nul_pos + 1 == slice.len())
1821
}
1922

23+
// Returns true if the slice contains any NUL bytes.
24+
#[must_use]
25+
pub const fn contains_nul(slice: &[u8]) -> bool {
26+
matches!(find(slice, 0), Some(_))
27+
}
28+
2029
#[cfg(test)]
2130
mod tests {
22-
use super::{find, is_cstr};
31+
use super::{contains_nul, find, is_cstr};
2332

2433
#[test]
2534
fn find_nul_byte() {
@@ -52,4 +61,20 @@ mod tests {
5261
assert!(is_cstr(b"abc\0"));
5362
assert!(is_cstr(b"abc\xFFxyz\0"));
5463
}
64+
65+
#[test]
66+
fn check_contains_nul_byte() {
67+
assert!(!contains_nul(b""));
68+
assert!(!contains_nul(b"abc"));
69+
assert!(!contains_nul(b"abc\xFFxyz"));
70+
71+
assert!(contains_nul(b"abc\0xyz"));
72+
assert!(contains_nul(b"abc\0xyz\0"));
73+
assert!(contains_nul(b"abc\xFF\0xyz"));
74+
assert!(contains_nul(b"abc\xFF\0xyz\0"));
75+
76+
assert!(contains_nul(b"\0"));
77+
assert!(contains_nul(b"abc\0"));
78+
assert!(contains_nul(b"abc\xFFxyz\0"));
79+
}
5580
}

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ macro_rules! const_assert_bytes_has_no_nul {
282282
($bytes:expr $(,)?) => {{
283283
const _: &[u8] = $bytes;
284284

285-
$crate::const_assert!($crate::imp::find($bytes, 0_u8).is_none());
285+
$crate::const_assert!(!$crate::imp::contains_nul($bytes));
286286
}};
287287
}
288288

0 commit comments

Comments
 (0)