|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! String representations. |
| 4 | +
|
| 5 | +use core::ops::{self, Deref, Index}; |
| 6 | + |
| 7 | +use crate::bindings; |
| 8 | +use crate::c_types; |
| 9 | + |
| 10 | +/// Byte string without UTF-8 validity guarantee. |
| 11 | +/// |
| 12 | +/// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning. |
| 13 | +pub type BStr = [u8]; |
| 14 | + |
| 15 | +/// Creates a new [`BStr`] from a string literal. |
| 16 | +/// |
| 17 | +/// `b_str!` converts the supplied string literal to byte string, so non-ASCII |
| 18 | +/// characters can be included. |
| 19 | +/// |
| 20 | +/// # Examples |
| 21 | +/// |
| 22 | +/// ```rust,no_run |
| 23 | +/// const MY_BSTR: &'static BStr = b_str!("My awesome BStr!"); |
| 24 | +/// ``` |
| 25 | +#[macro_export] |
| 26 | +macro_rules! b_str { |
| 27 | + ($str:literal) => {{ |
| 28 | + const S: &'static str = $str; |
| 29 | + const C: &'static $crate::str::BStr = S.as_bytes(); |
| 30 | + C |
| 31 | + }}; |
| 32 | +} |
| 33 | + |
| 34 | +/// Possible errors when using conversion functions in [`CStr`]. |
| 35 | +#[derive(Debug, Clone, Copy)] |
| 36 | +pub enum CStrConvertError { |
| 37 | + /// Supplied bytes contain an interior `NUL`. |
| 38 | + InteriorNul, |
| 39 | + |
| 40 | + /// Supplied bytes are not terminated by `NUL`. |
| 41 | + NotNulTerminated, |
| 42 | +} |
| 43 | + |
| 44 | +impl From<CStrConvertError> for crate::Error { |
| 45 | + #[inline] |
| 46 | + fn from(_: CStrConvertError) -> crate::Error { |
| 47 | + crate::Error::EINVAL |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/// A string that is guaranteed to have exactly one `NUL` byte, which is at the |
| 52 | +/// end. |
| 53 | +/// |
| 54 | +/// Used for interoperability with kernel APIs that take C strings. |
| 55 | +#[repr(transparent)] |
| 56 | +pub struct CStr([u8]); |
| 57 | + |
| 58 | +impl CStr { |
| 59 | + /// Returns the length of this string excluding `NUL`. |
| 60 | + #[inline] |
| 61 | + pub const fn len(&self) -> usize { |
| 62 | + self.0.len() - 1 |
| 63 | + } |
| 64 | + |
| 65 | + /// Returns the length of this string with `NUL`. |
| 66 | + #[inline] |
| 67 | + pub const fn len_with_nul(&self) -> usize { |
| 68 | + self.0.len() |
| 69 | + } |
| 70 | + |
| 71 | + /// Returns `true` if the string only includes `NUL`. |
| 72 | + #[inline] |
| 73 | + pub const fn is_empty(&self) -> bool { |
| 74 | + self.len() == 0 |
| 75 | + } |
| 76 | + |
| 77 | + /// Wraps a raw C string pointer. |
| 78 | + /// |
| 79 | + /// # Safety |
| 80 | + /// |
| 81 | + /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must |
| 82 | + /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr` |
| 83 | + /// must not be mutated. |
| 84 | + #[inline] |
| 85 | + pub unsafe fn from_char_ptr<'a>(ptr: *const c_types::c_char) -> &'a Self { |
| 86 | + let len = bindings::strlen(ptr) + 1; |
| 87 | + Self::from_bytes_with_nul_unchecked(core::slice::from_raw_parts(ptr as _, len as _)) |
| 88 | + } |
| 89 | + |
| 90 | + /// Creates a [`CStr`] from a `[u8]`. |
| 91 | + /// |
| 92 | + /// The provided slice must be `NUL`-terminated, does not contain any |
| 93 | + /// interior `NUL` bytes. |
| 94 | + pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> { |
| 95 | + if bytes.is_empty() { |
| 96 | + return Err(CStrConvertError::NotNulTerminated); |
| 97 | + } |
| 98 | + if bytes[bytes.len() - 1] != 0 { |
| 99 | + return Err(CStrConvertError::NotNulTerminated); |
| 100 | + } |
| 101 | + if bytes[..bytes.len()].contains(&0) { |
| 102 | + return Err(CStrConvertError::InteriorNul); |
| 103 | + } |
| 104 | + // SAFETY: We just checked that all properties hold. |
| 105 | + Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }) |
| 106 | + } |
| 107 | + |
| 108 | + /// Creates a [`CStr`] from a `[u8]` without performing any additional |
| 109 | + /// checks. |
| 110 | + /// |
| 111 | + /// # Safety |
| 112 | + /// |
| 113 | + /// `bytes` *must* end with a `NUL` byte, and should only have a single |
| 114 | + /// `NUL` byte (or the string will be truncated). |
| 115 | + #[inline] |
| 116 | + pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { |
| 117 | + // Note: This can be done using pointer deref (which requires |
| 118 | + // const_raw_ptr_deref to be const) or transmute (which requires |
| 119 | + // const_transmute to be const) or ptr::from_raw_parts (which |
| 120 | + // requires ptr_metadata). |
| 121 | + // While none of them are current stable, it is very likely that |
| 122 | + // one of them will eventually be. |
| 123 | + &*(bytes as *const [u8] as *const Self) |
| 124 | + } |
| 125 | + |
| 126 | + /// Returns a C pointer to the string. |
| 127 | + #[inline] |
| 128 | + pub const fn as_char_ptr(&self) -> *const c_types::c_char { |
| 129 | + self.0.as_ptr() as _ |
| 130 | + } |
| 131 | + |
| 132 | + /// Convert the string to a byte slice without the trailing 0 byte. |
| 133 | + #[inline] |
| 134 | + pub fn as_bytes(&self) -> &[u8] { |
| 135 | + &self.0[..self.0.len() - 1] |
| 136 | + } |
| 137 | + |
| 138 | + /// Convert the string to a byte slice containing the trailing 0 byte. |
| 139 | + #[inline] |
| 140 | + pub const fn as_bytes_with_nul(&self) -> &[u8] { |
| 141 | + &self.0 |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +impl AsRef<BStr> for CStr { |
| 146 | + #[inline] |
| 147 | + fn as_ref(&self) -> &BStr { |
| 148 | + self.as_bytes() |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +impl Deref for CStr { |
| 153 | + type Target = BStr; |
| 154 | + |
| 155 | + #[inline] |
| 156 | + fn deref(&self) -> &Self::Target { |
| 157 | + self.as_bytes() |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +impl Index<ops::RangeFrom<usize>> for CStr { |
| 162 | + type Output = CStr; |
| 163 | + |
| 164 | + #[inline] |
| 165 | + fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output { |
| 166 | + assert!( |
| 167 | + index.start <= self.len(), |
| 168 | + "range start index {} out of range for slice of length {}", |
| 169 | + index.start, |
| 170 | + self.len() |
| 171 | + ); |
| 172 | + // SAFETY: We just checked the length. |
| 173 | + unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +impl Index<ops::RangeFull> for CStr { |
| 178 | + type Output = CStr; |
| 179 | + |
| 180 | + #[inline] |
| 181 | + fn index(&self, _index: ops::RangeFull) -> &Self::Output { |
| 182 | + self |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +#[doc(hidden)] |
| 187 | +pub trait CStrIndex {} |
| 188 | + |
| 189 | +impl CStrIndex for usize {} |
| 190 | +impl CStrIndex for ops::Range<usize> {} |
| 191 | +impl CStrIndex for ops::RangeInclusive<usize> {} |
| 192 | +impl CStrIndex for ops::RangeToInclusive<usize> {} |
| 193 | + |
| 194 | +impl<Idx> Index<Idx> for CStr |
| 195 | +where |
| 196 | + Idx: CStrIndex, |
| 197 | + BStr: Index<Idx>, |
| 198 | +{ |
| 199 | + type Output = <BStr as Index<Idx>>::Output; |
| 200 | + |
| 201 | + #[inline] |
| 202 | + fn index(&self, index: Idx) -> &Self::Output { |
| 203 | + &self.0[index] |
| 204 | + } |
| 205 | +} |
| 206 | + |
| 207 | +/// Creates a new [`CStr`] from a string literal. |
| 208 | +/// |
| 209 | +/// The string literal should not contain any `NUL` bytes. |
| 210 | +/// |
| 211 | +/// # Examples |
| 212 | +/// |
| 213 | +/// ```rust,no_run |
| 214 | +/// const MY_CSTR: &'static CStr = c_str!("My awesome CStr!"); |
| 215 | +/// ``` |
| 216 | +#[macro_export] |
| 217 | +macro_rules! c_str { |
| 218 | + ($str:literal) => {{ |
| 219 | + // FIXME: Check that `$str` does not contain interior `NUL`. |
| 220 | + const S: &str = concat!($str, "\0"); |
| 221 | + const C: &$crate::str::CStr = |
| 222 | + { unsafe { $crate::str::CStr::from_bytes_with_nul_unchecked(S.as_bytes()) } }; |
| 223 | + C |
| 224 | + }}; |
| 225 | +} |
0 commit comments