c/cstr.rs
1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// Internal helpers for NUL-terminated C strings. They are not part of the
5// ABI; they keep pointer arithmetic and c_char signedness out of call sites.
6
7/// Compare a NUL-terminated string with a known byte sequence (typically a
8/// Rust literal). Unlike `strcmp`, the expected side does not need a
9/// trailing NUL and the comparison stops after `want.len()` bytes.
10#[inline]
11pub unsafe fn cstr_eq(s: *const u8, want: &[u8]) -> bool {
12 if s.is_null() {
13 return false;
14 }
15 let mut i = 0usize;
16 while i < want.len() {
17 if *s.add(i) != want[i] {
18 return false;
19 }
20 i += 1;
21 }
22 *s.add(want.len()) == 0
23}
24
25/// Borrow a NUL-terminated string as bytes, excluding the terminator. The
26/// caller must keep the string alive for the lifetime of the slice.
27#[inline]
28pub unsafe fn cstr_bytes<'a>(s: *const c_char) -> &'a [u8] {
29 if s.is_null() {
30 return &[];
31 }
32 let len = strlen(s);
33 core::slice::from_raw_parts(s as *const u8, len)
34}
35
36/// True when `s` contains `needle` under ASCII case folding.
37#[inline]
38pub unsafe fn cstr_contains_ci(s: *const u8, needle: &[u8]) -> bool {
39 if needle.is_empty() {
40 return true;
41 }
42 cstr_bytes(s as *const c_char)
43 .windows(needle.len())
44 .any(|window| window.eq_ignore_ascii_case(needle))
45}