|
| 1 | +use core::{ffi::c_char, marker::PhantomData, num::NonZeroUsize, ptr::NonNull, slice}; |
| 2 | + |
| 3 | +/// Marks a [`CStr`] whose length is not known. |
| 4 | +#[derive(Clone, Copy)] |
| 5 | +pub struct Thin { |
| 6 | + _private: (), |
| 7 | +} |
| 8 | + |
| 9 | +/// Marks a [`CStr`] that retains its length, including the terminating NUL. |
| 10 | +#[derive(Clone, Copy)] |
| 11 | +pub struct Fat { |
| 12 | + len_with_nul: NonZeroUsize, |
| 13 | +} |
| 14 | + |
| 15 | +/// A borrowed NUL-terminated string. |
| 16 | +/// |
| 17 | +/// [`CStr<'_, Thin>`] stores only the string pointer, while |
| 18 | +/// [`CStr<'_, Fat>`] also stores the length including the terminating NUL. |
| 19 | +#[derive(Clone, Copy)] |
| 20 | +pub struct CStr<'a, R> { |
| 21 | + ptr: NonNull<c_char>, |
| 22 | + repr: R, |
| 23 | + lifetime: PhantomData<&'a c_char>, |
| 24 | +} |
| 25 | + |
| 26 | +impl<R> CStr<'_, R> { |
| 27 | + /// Returns a pointer to the first byte of this C string. |
| 28 | + #[must_use] |
| 29 | + pub const fn as_ptr(&self) -> *const c_char { |
| 30 | + self.ptr.as_ptr() |
| 31 | + } |
| 32 | + |
| 33 | + #[doc(hidden)] |
| 34 | + #[must_use] |
| 35 | + pub fn into_repr(self) -> R { |
| 36 | + self.repr |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl Fat { |
| 41 | + #[doc(hidden)] |
| 42 | + #[must_use] |
| 43 | + pub const fn len_with_nul(self) -> usize { |
| 44 | + self.len_with_nul.get() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl<'a> CStr<'a, Thin> { |
| 49 | + /// Creates a thin C string view without finding its length. |
| 50 | + /// |
| 51 | + /// # Safety |
| 52 | + /// |
| 53 | + /// `ptr` must be non-null and point to an immutable NUL-terminated string |
| 54 | + /// that remains valid for the lifetime of the returned view. |
| 55 | + #[must_use] |
| 56 | + pub const unsafe fn from_ptr(ptr: *const c_char) -> Self { |
| 57 | + Self { |
| 58 | + // SAFETY: upheld by the caller. |
| 59 | + ptr: unsafe { NonNull::new_unchecked(ptr.cast_mut()) }, |
| 60 | + repr: Thin { _private: () }, |
| 61 | + lifetime: PhantomData, |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /// Counts through the terminating NUL and returns a length-retaining view. |
| 66 | + #[must_use] |
| 67 | + pub fn count(self) -> CStr<'a, Fat> { |
| 68 | + let mut count = 0; |
| 69 | + // Volatile reads prevent this loop from being replaced with a libc |
| 70 | + // `strlen` call, which is forbidden by `sigsafe` on Linux. |
| 71 | + // SAFETY: `CStr<Thin>` points to a NUL-terminated string. |
| 72 | + while unsafe { self.as_ptr().add(count).read_volatile() } != 0 { |
| 73 | + count += 1; |
| 74 | + } |
| 75 | + |
| 76 | + CStr { |
| 77 | + ptr: self.ptr, |
| 78 | + repr: Fat { |
| 79 | + // SAFETY: the count includes at least the terminating NUL. |
| 80 | + len_with_nul: unsafe { NonZeroUsize::new_unchecked(count + 1) }, |
| 81 | + }, |
| 82 | + lifetime: PhantomData, |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +impl<'a> CStr<'a, Fat> { |
| 88 | + /// Creates a length-retaining C string from bytes without validation. |
| 89 | + /// |
| 90 | + /// # Safety |
| 91 | + /// |
| 92 | + /// `bytes` must end with exactly one NUL byte and contain no other NUL |
| 93 | + /// bytes. |
| 94 | + #[must_use] |
| 95 | + pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &'a [u8]) -> Self { |
| 96 | + Self { |
| 97 | + // SAFETY: a valid C string is nonempty, so its pointer is non-null. |
| 98 | + ptr: unsafe { NonNull::new_unchecked(bytes.as_ptr().cast::<c_char>().cast_mut()) }, |
| 99 | + repr: Fat { |
| 100 | + // SAFETY: a valid C string contains at least its terminating NUL. |
| 101 | + len_with_nul: unsafe { NonZeroUsize::new_unchecked(bytes.len()) }, |
| 102 | + }, |
| 103 | + lifetime: PhantomData, |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + /// Returns the string's bytes, including the terminating NUL. |
| 108 | + #[must_use] |
| 109 | + pub const fn as_bytes_with_nul(&self) -> &'a [u8] { |
| 110 | + // SAFETY: this view carries the exact initialized C string length. |
| 111 | + unsafe { slice::from_raw_parts(self.ptr.as_ptr().cast(), self.len_with_nul()) } |
| 112 | + } |
| 113 | + |
| 114 | + /// Returns the number of bytes including the terminating NUL. |
| 115 | + #[must_use] |
| 116 | + pub const fn len_with_nul(&self) -> usize { |
| 117 | + self.repr.len_with_nul() |
| 118 | + } |
| 119 | + |
| 120 | + #[cfg(target_os = "macos")] |
| 121 | + pub(crate) const fn as_core_c_str(&self) -> &core::ffi::CStr { |
| 122 | + // SAFETY: `CStr<Fat>` maintains the same byte invariant. |
| 123 | + unsafe { core::ffi::CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) } |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +#[cfg(test)] |
| 128 | +mod tests { |
| 129 | + use core::mem::size_of; |
| 130 | + |
| 131 | + use super::{CStr, Fat, Thin}; |
| 132 | + |
| 133 | + #[test] |
| 134 | + fn representations_retain_the_expected_metadata() { |
| 135 | + // SAFETY: the input contains one trailing NUL. |
| 136 | + let fat = unsafe { CStr::<Fat>::from_bytes_with_nul_unchecked(b"abc\0") }; |
| 137 | + // SAFETY: the input contains one trailing NUL. |
| 138 | + let counted = unsafe { CStr::<Thin>::from_ptr(c"abc".as_ptr()) }.count(); |
| 139 | + |
| 140 | + assert_eq!(size_of::<CStr<'_, Thin>>(), size_of::<*const u8>()); |
| 141 | + assert_eq!(size_of::<CStr<'_, Fat>>(), size_of::<(*const u8, usize)>()); |
| 142 | + assert_eq!(fat.len_with_nul(), 4); |
| 143 | + assert_eq!(fat.as_bytes_with_nul(), b"abc\0"); |
| 144 | + assert_eq!(counted.as_bytes_with_nul(), fat.as_bytes_with_nul()); |
| 145 | + } |
| 146 | +} |
0 commit comments