Linux Audio

Check our new training course

Loading...
v6.8
  1// SPDX-License-Identifier: GPL-2.0
  2
  3//! String representations.
  4
  5use alloc::alloc::AllocError;
  6use alloc::vec::Vec;
  7use core::fmt::{self, Write};
  8use core::ops::{self, Deref, Index};
  9
 10use crate::{
 11    bindings,
 12    error::{code::*, Error},
 13};
 14
 15/// Byte string without UTF-8 validity guarantee.
 16///
 17/// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning.
 18pub type BStr = [u8];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 19
 20/// Creates a new [`BStr`] from a string literal.
 21///
 22/// `b_str!` converts the supplied string literal to byte string, so non-ASCII
 23/// characters can be included.
 24///
 25/// # Examples
 26///
 27/// ```
 28/// # use kernel::b_str;
 29/// # use kernel::str::BStr;
 30/// const MY_BSTR: &BStr = b_str!("My awesome BStr!");
 31/// ```
 32#[macro_export]
 33macro_rules! b_str {
 34    ($str:literal) => {{
 35        const S: &'static str = $str;
 36        const C: &'static $crate::str::BStr = S.as_bytes();
 37        C
 38    }};
 39}
 40
 41/// Possible errors when using conversion functions in [`CStr`].
 42#[derive(Debug, Clone, Copy)]
 43pub enum CStrConvertError {
 44    /// Supplied bytes contain an interior `NUL`.
 45    InteriorNul,
 46
 47    /// Supplied bytes are not terminated by `NUL`.
 48    NotNulTerminated,
 49}
 50
 51impl From<CStrConvertError> for Error {
 52    #[inline]
 53    fn from(_: CStrConvertError) -> Error {
 54        EINVAL
 55    }
 56}
 57
 58/// A string that is guaranteed to have exactly one `NUL` byte, which is at the
 59/// end.
 60///
 61/// Used for interoperability with kernel APIs that take C strings.
 62#[repr(transparent)]
 63pub struct CStr([u8]);
 64
 65impl CStr {
 66    /// Returns the length of this string excluding `NUL`.
 67    #[inline]
 68    pub const fn len(&self) -> usize {
 69        self.len_with_nul() - 1
 70    }
 71
 72    /// Returns the length of this string with `NUL`.
 73    #[inline]
 74    pub const fn len_with_nul(&self) -> usize {
 75        // SAFETY: This is one of the invariant of `CStr`.
 76        // We add a `unreachable_unchecked` here to hint the optimizer that
 77        // the value returned from this function is non-zero.
 78        if self.0.is_empty() {
 
 
 
 79            unsafe { core::hint::unreachable_unchecked() };
 80        }
 81        self.0.len()
 82    }
 83
 84    /// Returns `true` if the string only includes `NUL`.
 85    #[inline]
 86    pub const fn is_empty(&self) -> bool {
 87        self.len() == 0
 88    }
 89
 90    /// Wraps a raw C string pointer.
 91    ///
 92    /// # Safety
 93    ///
 94    /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must
 95    /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr`
 96    /// must not be mutated.
 97    #[inline]
 98    pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self {
 99        // SAFETY: The safety precondition guarantees `ptr` is a valid pointer
100        // to a `NUL`-terminated C string.
101        let len = unsafe { bindings::strlen(ptr) } + 1;
102        // SAFETY: Lifetime guaranteed by the safety precondition.
103        let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
104        // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
105        // As we have added 1 to `len`, the last byte is known to be `NUL`.
106        unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
107    }
108
109    /// Creates a [`CStr`] from a `[u8]`.
110    ///
111    /// The provided slice must be `NUL`-terminated, does not contain any
112    /// interior `NUL` bytes.
113    pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
114        if bytes.is_empty() {
115            return Err(CStrConvertError::NotNulTerminated);
116        }
117        if bytes[bytes.len() - 1] != 0 {
118            return Err(CStrConvertError::NotNulTerminated);
119        }
120        let mut i = 0;
121        // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking,
122        // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`.
123        while i + 1 < bytes.len() {
124            if bytes[i] == 0 {
125                return Err(CStrConvertError::InteriorNul);
126            }
127            i += 1;
128        }
129        // SAFETY: We just checked that all properties hold.
130        Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
131    }
132
133    /// Creates a [`CStr`] from a `[u8]` without performing any additional
134    /// checks.
135    ///
136    /// # Safety
137    ///
138    /// `bytes` *must* end with a `NUL` byte, and should only have a single
139    /// `NUL` byte (or the string will be truncated).
140    #[inline]
141    pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
142        // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
143        unsafe { core::mem::transmute(bytes) }
144    }
145
 
 
 
 
 
 
 
 
 
 
 
 
 
146    /// Returns a C pointer to the string.
147    #[inline]
148    pub const fn as_char_ptr(&self) -> *const core::ffi::c_char {
149        self.0.as_ptr() as _
150    }
151
152    /// Convert the string to a byte slice without the trailing 0 byte.
153    #[inline]
154    pub fn as_bytes(&self) -> &[u8] {
155        &self.0[..self.len()]
156    }
157
158    /// Convert the string to a byte slice containing the trailing 0 byte.
159    #[inline]
160    pub const fn as_bytes_with_nul(&self) -> &[u8] {
161        &self.0
162    }
163
164    /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8.
165    ///
166    /// If the contents of the [`CStr`] are valid UTF-8 data, this
167    /// function will return the corresponding [`&str`] slice. Otherwise,
168    /// it will return an error with details of where UTF-8 validation failed.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// # use kernel::str::CStr;
174    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
175    /// assert_eq!(cstr.to_str(), Ok("foo"));
176    /// ```
177    #[inline]
178    pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
179        core::str::from_utf8(self.as_bytes())
180    }
181
182    /// Unsafely convert this [`CStr`] into a [`&str`], without checking for
183    /// valid UTF-8.
184    ///
185    /// # Safety
186    ///
187    /// The contents must be valid UTF-8.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// # use kernel::c_str;
193    /// # use kernel::str::CStr;
 
194    /// // SAFETY: String literals are guaranteed to be valid UTF-8
195    /// // by the Rust compiler.
196    /// let bar = c_str!("ツ");
197    /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ");
198    /// ```
199    #[inline]
200    pub unsafe fn as_str_unchecked(&self) -> &str {
 
201        unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
202    }
203
204    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
205    /// copying over the string data.
206    pub fn to_cstring(&self) -> Result<CString, AllocError> {
207        CString::try_from(self)
208    }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209}
210
211impl fmt::Display for CStr {
212    /// Formats printable ASCII characters, escaping the rest.
213    ///
214    /// ```
215    /// # use kernel::c_str;
216    /// # use kernel::fmt;
217    /// # use kernel::str::CStr;
218    /// # use kernel::str::CString;
219    /// let penguin = c_str!("🐧");
220    /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap();
221    /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
222    ///
223    /// let ascii = c_str!("so \"cool\"");
224    /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
225    /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes());
226    /// ```
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        for &c in self.as_bytes() {
229            if (0x20..0x7f).contains(&c) {
230                // Printable character.
231                f.write_char(c as char)?;
232            } else {
233                write!(f, "\\x{:02x}", c)?;
234            }
235        }
236        Ok(())
237    }
238}
239
240impl fmt::Debug for CStr {
241    /// Formats printable ASCII characters with a double quote on either end, escaping the rest.
242    ///
243    /// ```
244    /// # use kernel::c_str;
245    /// # use kernel::fmt;
246    /// # use kernel::str::CStr;
247    /// # use kernel::str::CString;
248    /// let penguin = c_str!("🐧");
249    /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap();
250    /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
251    ///
252    /// // Embedded double quotes are escaped.
253    /// let ascii = c_str!("so \"cool\"");
254    /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
255    /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
256    /// ```
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        f.write_str("\"")?;
259        for &c in self.as_bytes() {
260            match c {
261                // Printable characters.
262                b'\"' => f.write_str("\\\"")?,
263                0x20..=0x7e => f.write_char(c as char)?,
264                _ => write!(f, "\\x{:02x}", c)?,
265            }
266        }
267        f.write_str("\"")
268    }
269}
270
271impl AsRef<BStr> for CStr {
272    #[inline]
273    fn as_ref(&self) -> &BStr {
274        self.as_bytes()
275    }
276}
277
278impl Deref for CStr {
279    type Target = BStr;
280
281    #[inline]
282    fn deref(&self) -> &Self::Target {
283        self.as_bytes()
284    }
285}
286
287impl Index<ops::RangeFrom<usize>> for CStr {
288    type Output = CStr;
289
290    #[inline]
291    fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
292        // Delegate bounds checking to slice.
293        // Assign to _ to mute clippy's unnecessary operation warning.
294        let _ = &self.as_bytes()[index.start..];
295        // SAFETY: We just checked the bounds.
296        unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
297    }
298}
299
300impl Index<ops::RangeFull> for CStr {
301    type Output = CStr;
302
303    #[inline]
304    fn index(&self, _index: ops::RangeFull) -> &Self::Output {
305        self
306    }
307}
308
309mod private {
310    use core::ops;
311
312    // Marker trait for index types that can be forward to `BStr`.
313    pub trait CStrIndex {}
314
315    impl CStrIndex for usize {}
316    impl CStrIndex for ops::Range<usize> {}
317    impl CStrIndex for ops::RangeInclusive<usize> {}
318    impl CStrIndex for ops::RangeToInclusive<usize> {}
319}
320
321impl<Idx> Index<Idx> for CStr
322where
323    Idx: private::CStrIndex,
324    BStr: Index<Idx>,
325{
326    type Output = <BStr as Index<Idx>>::Output;
327
328    #[inline]
329    fn index(&self, index: Idx) -> &Self::Output {
330        &self.as_bytes()[index]
331    }
332}
333
334/// Creates a new [`CStr`] from a string literal.
335///
336/// The string literal should not contain any `NUL` bytes.
337///
338/// # Examples
339///
340/// ```
341/// # use kernel::c_str;
342/// # use kernel::str::CStr;
343/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
344/// ```
345#[macro_export]
346macro_rules! c_str {
347    ($str:expr) => {{
348        const S: &str = concat!($str, "\0");
349        const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
350            Ok(v) => v,
351            Err(_) => panic!("string contains interior NUL"),
352        };
353        C
354    }};
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361    #[test]
362    fn test_cstr_to_str() {
363        let good_bytes = b"\xf0\x9f\xa6\x80\0";
364        let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
365        let checked_str = checked_cstr.to_str().unwrap();
366        assert_eq!(checked_str, "🦀");
367    }
368
369    #[test]
370    #[should_panic]
371    fn test_cstr_to_str_panic() {
372        let bad_bytes = b"\xc3\x28\0";
373        let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap();
374        checked_cstr.to_str().unwrap();
375    }
376
377    #[test]
378    fn test_cstr_as_str_unchecked() {
379        let good_bytes = b"\xf0\x9f\x90\xA7\0";
380        let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
381        let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
382        assert_eq!(unchecked_str, "🐧");
383    }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384}
385
386/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
387///
388/// It does not fail if callers write past the end of the buffer so that they can calculate the
389/// size required to fit everything.
390///
391/// # Invariants
392///
393/// The memory region between `pos` (inclusive) and `end` (exclusive) is valid for writes if `pos`
394/// is less than `end`.
395pub(crate) struct RawFormatter {
396    // Use `usize` to use `saturating_*` functions.
397    beg: usize,
398    pos: usize,
399    end: usize,
400}
401
402impl RawFormatter {
403    /// Creates a new instance of [`RawFormatter`] with an empty buffer.
404    fn new() -> Self {
405        // INVARIANT: The buffer is empty, so the region that needs to be writable is empty.
406        Self {
407            beg: 0,
408            pos: 0,
409            end: 0,
410        }
411    }
412
413    /// Creates a new instance of [`RawFormatter`] with the given buffer pointers.
414    ///
415    /// # Safety
416    ///
417    /// If `pos` is less than `end`, then the region between `pos` (inclusive) and `end`
418    /// (exclusive) must be valid for writes for the lifetime of the returned [`RawFormatter`].
419    pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
420        // INVARIANT: The safety requirements guarantee the type invariants.
421        Self {
422            beg: pos as _,
423            pos: pos as _,
424            end: end as _,
425        }
426    }
427
428    /// Creates a new instance of [`RawFormatter`] with the given buffer.
429    ///
430    /// # Safety
431    ///
432    /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
433    /// for the lifetime of the returned [`RawFormatter`].
434    pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
435        let pos = buf as usize;
436        // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements
437        // guarantees that the memory region is valid for writes.
438        Self {
439            pos,
440            beg: pos,
441            end: pos.saturating_add(len),
442        }
443    }
444
445    /// Returns the current insert position.
446    ///
447    /// N.B. It may point to invalid memory.
448    pub(crate) fn pos(&self) -> *mut u8 {
449        self.pos as _
450    }
451
452    /// Return the number of bytes written to the formatter.
453    pub(crate) fn bytes_written(&self) -> usize {
454        self.pos - self.beg
455    }
456}
457
458impl fmt::Write for RawFormatter {
459    fn write_str(&mut self, s: &str) -> fmt::Result {
460        // `pos` value after writing `len` bytes. This does not have to be bounded by `end`, but we
461        // don't want it to wrap around to 0.
462        let pos_new = self.pos.saturating_add(s.len());
463
464        // Amount that we can copy. `saturating_sub` ensures we get 0 if `pos` goes past `end`.
465        let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
466
467        if len_to_copy > 0 {
468            // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end`
469            // yet, so it is valid for write per the type invariants.
470            unsafe {
471                core::ptr::copy_nonoverlapping(
472                    s.as_bytes().as_ptr(),
473                    self.pos as *mut u8,
474                    len_to_copy,
475                )
476            };
477        }
478
479        self.pos = pos_new;
480        Ok(())
481    }
482}
483
484/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
485///
486/// Fails if callers attempt to write more than will fit in the buffer.
487pub(crate) struct Formatter(RawFormatter);
488
489impl Formatter {
490    /// Creates a new instance of [`Formatter`] with the given buffer.
491    ///
492    /// # Safety
493    ///
494    /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
495    /// for the lifetime of the returned [`Formatter`].
496    pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
497        // SAFETY: The safety requirements of this function satisfy those of the callee.
498        Self(unsafe { RawFormatter::from_buffer(buf, len) })
499    }
500}
501
502impl Deref for Formatter {
503    type Target = RawFormatter;
504
505    fn deref(&self) -> &Self::Target {
506        &self.0
507    }
508}
509
510impl fmt::Write for Formatter {
511    fn write_str(&mut self, s: &str) -> fmt::Result {
512        self.0.write_str(s)?;
513
514        // Fail the request if we go past the end of the buffer.
515        if self.0.pos > self.0.end {
516            Err(fmt::Error)
517        } else {
518            Ok(())
519        }
520    }
521}
522
523/// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
524///
525/// Used for interoperability with kernel APIs that take C strings.
526///
527/// # Invariants
528///
529/// The string is always `NUL`-terminated and contains no other `NUL` bytes.
530///
531/// # Examples
532///
533/// ```
534/// use kernel::{str::CString, fmt};
535///
536/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap();
537/// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes());
538///
539/// let tmp = "testing";
540/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap();
541/// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes());
542///
543/// // This fails because it has an embedded `NUL` byte.
544/// let s = CString::try_from_fmt(fmt!("a\0b{}", 123));
545/// assert_eq!(s.is_ok(), false);
546/// ```
547pub struct CString {
548    buf: Vec<u8>,
549}
550
551impl CString {
552    /// Creates an instance of [`CString`] from the given formatted arguments.
553    pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
554        // Calculate the size needed (formatted string plus `NUL` terminator).
555        let mut f = RawFormatter::new();
556        f.write_fmt(args)?;
557        f.write_str("\0")?;
558        let size = f.bytes_written();
559
560        // Allocate a vector with the required number of bytes, and write to it.
561        let mut buf = Vec::try_with_capacity(size)?;
562        // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
563        let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
564        f.write_fmt(args)?;
565        f.write_str("\0")?;
566
567        // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
568        // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`.
569        unsafe { buf.set_len(f.bytes_written()) };
570
571        // Check that there are no `NUL` bytes before the end.
572        // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
573        // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator)
574        // so `f.bytes_written() - 1` doesn't underflow.
575        let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) };
576        if !ptr.is_null() {
577            return Err(EINVAL);
578        }
579
580        // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes
581        // exist in the buffer.
582        Ok(Self { buf })
583    }
584}
585
586impl Deref for CString {
587    type Target = CStr;
588
589    fn deref(&self) -> &Self::Target {
590        // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no
591        // other `NUL` bytes exist.
592        unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
593    }
594}
595
 
 
 
 
 
 
 
 
596impl<'a> TryFrom<&'a CStr> for CString {
597    type Error = AllocError;
598
599    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
600        let mut buf = Vec::new();
601
602        buf.try_extend_from_slice(cstr.as_bytes_with_nul())
603            .map_err(|_| AllocError)?;
604
605        // INVARIANT: The `CStr` and `CString` types have the same invariants for
606        // the string data, and we copied it over without changes.
607        Ok(CString { buf })
608    }
609}
610
611impl fmt::Debug for CString {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        fmt::Debug::fmt(&**self, f)
614    }
615}
616
617/// A convenience alias for [`core::format_args`].
618#[macro_export]
619macro_rules! fmt {
620    ($($f:tt)*) => ( core::format_args!($($f)*) )
621}
v6.13.7
  1// SPDX-License-Identifier: GPL-2.0
  2
  3//! String representations.
  4
  5use crate::alloc::{flags::*, AllocError, KVec};
 
  6use core::fmt::{self, Write};
  7use core::ops::{self, Deref, DerefMut, Index};
  8
  9use crate::error::{code::*, Error};
 
 
 
 10
 11/// Byte string without UTF-8 validity guarantee.
 12#[repr(transparent)]
 13pub struct BStr([u8]);
 14
 15impl BStr {
 16    /// Returns the length of this string.
 17    #[inline]
 18    pub const fn len(&self) -> usize {
 19        self.0.len()
 20    }
 21
 22    /// Returns `true` if the string is empty.
 23    #[inline]
 24    pub const fn is_empty(&self) -> bool {
 25        self.len() == 0
 26    }
 27
 28    /// Creates a [`BStr`] from a `[u8]`.
 29    #[inline]
 30    pub const fn from_bytes(bytes: &[u8]) -> &Self {
 31        // SAFETY: `BStr` is transparent to `[u8]`.
 32        unsafe { &*(bytes as *const [u8] as *const BStr) }
 33    }
 34}
 35
 36impl fmt::Display for BStr {
 37    /// Formats printable ASCII characters, escaping the rest.
 38    ///
 39    /// ```
 40    /// # use kernel::{fmt, b_str, str::{BStr, CString}};
 41    /// let ascii = b_str!("Hello, BStr!");
 42    /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
 43    /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes());
 44    ///
 45    /// let non_ascii = b_str!("🦀");
 46    /// let s = CString::try_from_fmt(fmt!("{}", non_ascii)).unwrap();
 47    /// assert_eq!(s.as_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes());
 48    /// ```
 49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 50        for &b in &self.0 {
 51            match b {
 52                // Common escape codes.
 53                b'\t' => f.write_str("\\t")?,
 54                b'\n' => f.write_str("\\n")?,
 55                b'\r' => f.write_str("\\r")?,
 56                // Printable characters.
 57                0x20..=0x7e => f.write_char(b as char)?,
 58                _ => write!(f, "\\x{:02x}", b)?,
 59            }
 60        }
 61        Ok(())
 62    }
 63}
 64
 65impl fmt::Debug for BStr {
 66    /// Formats printable ASCII characters with a double quote on either end,
 67    /// escaping the rest.
 68    ///
 69    /// ```
 70    /// # use kernel::{fmt, b_str, str::{BStr, CString}};
 71    /// // Embedded double quotes are escaped.
 72    /// let ascii = b_str!("Hello, \"BStr\"!");
 73    /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
 74    /// assert_eq!(s.as_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes());
 75    ///
 76    /// let non_ascii = b_str!("😺");
 77    /// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii)).unwrap();
 78    /// assert_eq!(s.as_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes());
 79    /// ```
 80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 81        f.write_char('"')?;
 82        for &b in &self.0 {
 83            match b {
 84                // Common escape codes.
 85                b'\t' => f.write_str("\\t")?,
 86                b'\n' => f.write_str("\\n")?,
 87                b'\r' => f.write_str("\\r")?,
 88                // String escape characters.
 89                b'\"' => f.write_str("\\\"")?,
 90                b'\\' => f.write_str("\\\\")?,
 91                // Printable characters.
 92                0x20..=0x7e => f.write_char(b as char)?,
 93                _ => write!(f, "\\x{:02x}", b)?,
 94            }
 95        }
 96        f.write_char('"')
 97    }
 98}
 99
100impl Deref for BStr {
101    type Target = [u8];
102
103    #[inline]
104    fn deref(&self) -> &Self::Target {
105        &self.0
106    }
107}
108
109/// Creates a new [`BStr`] from a string literal.
110///
111/// `b_str!` converts the supplied string literal to byte string, so non-ASCII
112/// characters can be included.
113///
114/// # Examples
115///
116/// ```
117/// # use kernel::b_str;
118/// # use kernel::str::BStr;
119/// const MY_BSTR: &BStr = b_str!("My awesome BStr!");
120/// ```
121#[macro_export]
122macro_rules! b_str {
123    ($str:literal) => {{
124        const S: &'static str = $str;
125        const C: &'static $crate::str::BStr = $crate::str::BStr::from_bytes(S.as_bytes());
126        C
127    }};
128}
129
130/// Possible errors when using conversion functions in [`CStr`].
131#[derive(Debug, Clone, Copy)]
132pub enum CStrConvertError {
133    /// Supplied bytes contain an interior `NUL`.
134    InteriorNul,
135
136    /// Supplied bytes are not terminated by `NUL`.
137    NotNulTerminated,
138}
139
140impl From<CStrConvertError> for Error {
141    #[inline]
142    fn from(_: CStrConvertError) -> Error {
143        EINVAL
144    }
145}
146
147/// A string that is guaranteed to have exactly one `NUL` byte, which is at the
148/// end.
149///
150/// Used for interoperability with kernel APIs that take C strings.
151#[repr(transparent)]
152pub struct CStr([u8]);
153
154impl CStr {
155    /// Returns the length of this string excluding `NUL`.
156    #[inline]
157    pub const fn len(&self) -> usize {
158        self.len_with_nul() - 1
159    }
160
161    /// Returns the length of this string with `NUL`.
162    #[inline]
163    pub const fn len_with_nul(&self) -> usize {
 
 
 
164        if self.0.is_empty() {
165            // SAFETY: This is one of the invariant of `CStr`.
166            // We add a `unreachable_unchecked` here to hint the optimizer that
167            // the value returned from this function is non-zero.
168            unsafe { core::hint::unreachable_unchecked() };
169        }
170        self.0.len()
171    }
172
173    /// Returns `true` if the string only includes `NUL`.
174    #[inline]
175    pub const fn is_empty(&self) -> bool {
176        self.len() == 0
177    }
178
179    /// Wraps a raw C string pointer.
180    ///
181    /// # Safety
182    ///
183    /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must
184    /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr`
185    /// must not be mutated.
186    #[inline]
187    pub unsafe fn from_char_ptr<'a>(ptr: *const crate::ffi::c_char) -> &'a Self {
188        // SAFETY: The safety precondition guarantees `ptr` is a valid pointer
189        // to a `NUL`-terminated C string.
190        let len = unsafe { bindings::strlen(ptr) } + 1;
191        // SAFETY: Lifetime guaranteed by the safety precondition.
192        let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len) };
193        // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
194        // As we have added 1 to `len`, the last byte is known to be `NUL`.
195        unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
196    }
197
198    /// Creates a [`CStr`] from a `[u8]`.
199    ///
200    /// The provided slice must be `NUL`-terminated, does not contain any
201    /// interior `NUL` bytes.
202    pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
203        if bytes.is_empty() {
204            return Err(CStrConvertError::NotNulTerminated);
205        }
206        if bytes[bytes.len() - 1] != 0 {
207            return Err(CStrConvertError::NotNulTerminated);
208        }
209        let mut i = 0;
210        // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking,
211        // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`.
212        while i + 1 < bytes.len() {
213            if bytes[i] == 0 {
214                return Err(CStrConvertError::InteriorNul);
215            }
216            i += 1;
217        }
218        // SAFETY: We just checked that all properties hold.
219        Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
220    }
221
222    /// Creates a [`CStr`] from a `[u8]` without performing any additional
223    /// checks.
224    ///
225    /// # Safety
226    ///
227    /// `bytes` *must* end with a `NUL` byte, and should only have a single
228    /// `NUL` byte (or the string will be truncated).
229    #[inline]
230    pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
231        // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
232        unsafe { core::mem::transmute(bytes) }
233    }
234
235    /// Creates a mutable [`CStr`] from a `[u8]` without performing any
236    /// additional checks.
237    ///
238    /// # Safety
239    ///
240    /// `bytes` *must* end with a `NUL` byte, and should only have a single
241    /// `NUL` byte (or the string will be truncated).
242    #[inline]
243    pub unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr {
244        // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
245        unsafe { &mut *(bytes as *mut [u8] as *mut CStr) }
246    }
247
248    /// Returns a C pointer to the string.
249    #[inline]
250    pub const fn as_char_ptr(&self) -> *const crate::ffi::c_char {
251        self.0.as_ptr()
252    }
253
254    /// Convert the string to a byte slice without the trailing `NUL` byte.
255    #[inline]
256    pub fn as_bytes(&self) -> &[u8] {
257        &self.0[..self.len()]
258    }
259
260    /// Convert the string to a byte slice containing the trailing `NUL` byte.
261    #[inline]
262    pub const fn as_bytes_with_nul(&self) -> &[u8] {
263        &self.0
264    }
265
266    /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8.
267    ///
268    /// If the contents of the [`CStr`] are valid UTF-8 data, this
269    /// function will return the corresponding [`&str`] slice. Otherwise,
270    /// it will return an error with details of where UTF-8 validation failed.
271    ///
272    /// # Examples
273    ///
274    /// ```
275    /// # use kernel::str::CStr;
276    /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
277    /// assert_eq!(cstr.to_str(), Ok("foo"));
278    /// ```
279    #[inline]
280    pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
281        core::str::from_utf8(self.as_bytes())
282    }
283
284    /// Unsafely convert this [`CStr`] into a [`&str`], without checking for
285    /// valid UTF-8.
286    ///
287    /// # Safety
288    ///
289    /// The contents must be valid UTF-8.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// # use kernel::c_str;
295    /// # use kernel::str::CStr;
296    /// let bar = c_str!("ツ");
297    /// // SAFETY: String literals are guaranteed to be valid UTF-8
298    /// // by the Rust compiler.
 
299    /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ");
300    /// ```
301    #[inline]
302    pub unsafe fn as_str_unchecked(&self) -> &str {
303        // SAFETY: TODO.
304        unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
305    }
306
307    /// Convert this [`CStr`] into a [`CString`] by allocating memory and
308    /// copying over the string data.
309    pub fn to_cstring(&self) -> Result<CString, AllocError> {
310        CString::try_from(self)
311    }
312
313    /// Converts this [`CStr`] to its ASCII lower case equivalent in-place.
314    ///
315    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
316    /// but non-ASCII letters are unchanged.
317    ///
318    /// To return a new lowercased value without modifying the existing one, use
319    /// [`to_ascii_lowercase()`].
320    ///
321    /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
322    pub fn make_ascii_lowercase(&mut self) {
323        // INVARIANT: This doesn't introduce or remove NUL bytes in the C
324        // string.
325        self.0.make_ascii_lowercase();
326    }
327
328    /// Converts this [`CStr`] to its ASCII upper case equivalent in-place.
329    ///
330    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
331    /// but non-ASCII letters are unchanged.
332    ///
333    /// To return a new uppercased value without modifying the existing one, use
334    /// [`to_ascii_uppercase()`].
335    ///
336    /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
337    pub fn make_ascii_uppercase(&mut self) {
338        // INVARIANT: This doesn't introduce or remove NUL bytes in the C
339        // string.
340        self.0.make_ascii_uppercase();
341    }
342
343    /// Returns a copy of this [`CString`] where each character is mapped to its
344    /// ASCII lower case equivalent.
345    ///
346    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
347    /// but non-ASCII letters are unchanged.
348    ///
349    /// To lowercase the value in-place, use [`make_ascii_lowercase`].
350    ///
351    /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
352    pub fn to_ascii_lowercase(&self) -> Result<CString, AllocError> {
353        let mut s = self.to_cstring()?;
354
355        s.make_ascii_lowercase();
356
357        Ok(s)
358    }
359
360    /// Returns a copy of this [`CString`] where each character is mapped to its
361    /// ASCII upper case equivalent.
362    ///
363    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
364    /// but non-ASCII letters are unchanged.
365    ///
366    /// To uppercase the value in-place, use [`make_ascii_uppercase`].
367    ///
368    /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
369    pub fn to_ascii_uppercase(&self) -> Result<CString, AllocError> {
370        let mut s = self.to_cstring()?;
371
372        s.make_ascii_uppercase();
373
374        Ok(s)
375    }
376}
377
378impl fmt::Display for CStr {
379    /// Formats printable ASCII characters, escaping the rest.
380    ///
381    /// ```
382    /// # use kernel::c_str;
383    /// # use kernel::fmt;
384    /// # use kernel::str::CStr;
385    /// # use kernel::str::CString;
386    /// let penguin = c_str!("🐧");
387    /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap();
388    /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
389    ///
390    /// let ascii = c_str!("so \"cool\"");
391    /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
392    /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes());
393    /// ```
394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395        for &c in self.as_bytes() {
396            if (0x20..0x7f).contains(&c) {
397                // Printable character.
398                f.write_char(c as char)?;
399            } else {
400                write!(f, "\\x{:02x}", c)?;
401            }
402        }
403        Ok(())
404    }
405}
406
407impl fmt::Debug for CStr {
408    /// Formats printable ASCII characters with a double quote on either end, escaping the rest.
409    ///
410    /// ```
411    /// # use kernel::c_str;
412    /// # use kernel::fmt;
413    /// # use kernel::str::CStr;
414    /// # use kernel::str::CString;
415    /// let penguin = c_str!("🐧");
416    /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap();
417    /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
418    ///
419    /// // Embedded double quotes are escaped.
420    /// let ascii = c_str!("so \"cool\"");
421    /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
422    /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
423    /// ```
424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425        f.write_str("\"")?;
426        for &c in self.as_bytes() {
427            match c {
428                // Printable characters.
429                b'\"' => f.write_str("\\\"")?,
430                0x20..=0x7e => f.write_char(c as char)?,
431                _ => write!(f, "\\x{:02x}", c)?,
432            }
433        }
434        f.write_str("\"")
435    }
436}
437
438impl AsRef<BStr> for CStr {
439    #[inline]
440    fn as_ref(&self) -> &BStr {
441        BStr::from_bytes(self.as_bytes())
442    }
443}
444
445impl Deref for CStr {
446    type Target = BStr;
447
448    #[inline]
449    fn deref(&self) -> &Self::Target {
450        self.as_ref()
451    }
452}
453
454impl Index<ops::RangeFrom<usize>> for CStr {
455    type Output = CStr;
456
457    #[inline]
458    fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
459        // Delegate bounds checking to slice.
460        // Assign to _ to mute clippy's unnecessary operation warning.
461        let _ = &self.as_bytes()[index.start..];
462        // SAFETY: We just checked the bounds.
463        unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
464    }
465}
466
467impl Index<ops::RangeFull> for CStr {
468    type Output = CStr;
469
470    #[inline]
471    fn index(&self, _index: ops::RangeFull) -> &Self::Output {
472        self
473    }
474}
475
476mod private {
477    use core::ops;
478
479    // Marker trait for index types that can be forward to `BStr`.
480    pub trait CStrIndex {}
481
482    impl CStrIndex for usize {}
483    impl CStrIndex for ops::Range<usize> {}
484    impl CStrIndex for ops::RangeInclusive<usize> {}
485    impl CStrIndex for ops::RangeToInclusive<usize> {}
486}
487
488impl<Idx> Index<Idx> for CStr
489where
490    Idx: private::CStrIndex,
491    BStr: Index<Idx>,
492{
493    type Output = <BStr as Index<Idx>>::Output;
494
495    #[inline]
496    fn index(&self, index: Idx) -> &Self::Output {
497        &self.as_ref()[index]
498    }
499}
500
501/// Creates a new [`CStr`] from a string literal.
502///
503/// The string literal should not contain any `NUL` bytes.
504///
505/// # Examples
506///
507/// ```
508/// # use kernel::c_str;
509/// # use kernel::str::CStr;
510/// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
511/// ```
512#[macro_export]
513macro_rules! c_str {
514    ($str:expr) => {{
515        const S: &str = concat!($str, "\0");
516        const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
517            Ok(v) => v,
518            Err(_) => panic!("string contains interior NUL"),
519        };
520        C
521    }};
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    struct String(CString);
529
530    impl String {
531        fn from_fmt(args: fmt::Arguments<'_>) -> Self {
532            String(CString::try_from_fmt(args).unwrap())
533        }
534    }
535
536    impl Deref for String {
537        type Target = str;
538
539        fn deref(&self) -> &str {
540            self.0.to_str().unwrap()
541        }
542    }
543
544    macro_rules! format {
545        ($($f:tt)*) => ({
546            &*String::from_fmt(kernel::fmt!($($f)*))
547        })
548    }
549
550    const ALL_ASCII_CHARS: &'static str =
551        "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\
552        \\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \
553        !\"#$%&'()*+,-./0123456789:;<=>?@\
554        ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f\
555        \\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\
556        \\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\
557        \\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\
558        \\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\
559        \\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\
560        \\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\
561        \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\
562        \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff";
563
564    #[test]
565    fn test_cstr_to_str() {
566        let good_bytes = b"\xf0\x9f\xa6\x80\0";
567        let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
568        let checked_str = checked_cstr.to_str().unwrap();
569        assert_eq!(checked_str, "🦀");
570    }
571
572    #[test]
573    #[should_panic]
574    fn test_cstr_to_str_panic() {
575        let bad_bytes = b"\xc3\x28\0";
576        let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap();
577        checked_cstr.to_str().unwrap();
578    }
579
580    #[test]
581    fn test_cstr_as_str_unchecked() {
582        let good_bytes = b"\xf0\x9f\x90\xA7\0";
583        let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
584        let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
585        assert_eq!(unchecked_str, "🐧");
586    }
587
588    #[test]
589    fn test_cstr_display() {
590        let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap();
591        assert_eq!(format!("{}", hello_world), "hello, world!");
592        let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap();
593        assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a");
594        let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap();
595        assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu");
596        let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap();
597        assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80");
598    }
599
600    #[test]
601    fn test_cstr_display_all_bytes() {
602        let mut bytes: [u8; 256] = [0; 256];
603        // fill `bytes` with [1..=255] + [0]
604        for i in u8::MIN..=u8::MAX {
605            bytes[i as usize] = i.wrapping_add(1);
606        }
607        let cstr = CStr::from_bytes_with_nul(&bytes).unwrap();
608        assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS);
609    }
610
611    #[test]
612    fn test_cstr_debug() {
613        let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap();
614        assert_eq!(format!("{:?}", hello_world), "\"hello, world!\"");
615        let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap();
616        assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\"");
617        let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap();
618        assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\"");
619        let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap();
620        assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\"");
621    }
622
623    #[test]
624    fn test_bstr_display() {
625        let hello_world = BStr::from_bytes(b"hello, world!");
626        assert_eq!(format!("{}", hello_world), "hello, world!");
627        let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
628        assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_");
629        let others = BStr::from_bytes(b"\x01");
630        assert_eq!(format!("{}", others), "\\x01");
631        let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
632        assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu");
633        let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
634        assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80");
635    }
636
637    #[test]
638    fn test_bstr_debug() {
639        let hello_world = BStr::from_bytes(b"hello, world!");
640        assert_eq!(format!("{:?}", hello_world), "\"hello, world!\"");
641        let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
642        assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\"");
643        let others = BStr::from_bytes(b"\x01");
644        assert_eq!(format!("{:?}", others), "\"\\x01\"");
645        let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
646        assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\"");
647        let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
648        assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\"");
649    }
650}
651
652/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
653///
654/// It does not fail if callers write past the end of the buffer so that they can calculate the
655/// size required to fit everything.
656///
657/// # Invariants
658///
659/// The memory region between `pos` (inclusive) and `end` (exclusive) is valid for writes if `pos`
660/// is less than `end`.
661pub(crate) struct RawFormatter {
662    // Use `usize` to use `saturating_*` functions.
663    beg: usize,
664    pos: usize,
665    end: usize,
666}
667
668impl RawFormatter {
669    /// Creates a new instance of [`RawFormatter`] with an empty buffer.
670    fn new() -> Self {
671        // INVARIANT: The buffer is empty, so the region that needs to be writable is empty.
672        Self {
673            beg: 0,
674            pos: 0,
675            end: 0,
676        }
677    }
678
679    /// Creates a new instance of [`RawFormatter`] with the given buffer pointers.
680    ///
681    /// # Safety
682    ///
683    /// If `pos` is less than `end`, then the region between `pos` (inclusive) and `end`
684    /// (exclusive) must be valid for writes for the lifetime of the returned [`RawFormatter`].
685    pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
686        // INVARIANT: The safety requirements guarantee the type invariants.
687        Self {
688            beg: pos as _,
689            pos: pos as _,
690            end: end as _,
691        }
692    }
693
694    /// Creates a new instance of [`RawFormatter`] with the given buffer.
695    ///
696    /// # Safety
697    ///
698    /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
699    /// for the lifetime of the returned [`RawFormatter`].
700    pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
701        let pos = buf as usize;
702        // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements
703        // guarantees that the memory region is valid for writes.
704        Self {
705            pos,
706            beg: pos,
707            end: pos.saturating_add(len),
708        }
709    }
710
711    /// Returns the current insert position.
712    ///
713    /// N.B. It may point to invalid memory.
714    pub(crate) fn pos(&self) -> *mut u8 {
715        self.pos as _
716    }
717
718    /// Returns the number of bytes written to the formatter.
719    pub(crate) fn bytes_written(&self) -> usize {
720        self.pos - self.beg
721    }
722}
723
724impl fmt::Write for RawFormatter {
725    fn write_str(&mut self, s: &str) -> fmt::Result {
726        // `pos` value after writing `len` bytes. This does not have to be bounded by `end`, but we
727        // don't want it to wrap around to 0.
728        let pos_new = self.pos.saturating_add(s.len());
729
730        // Amount that we can copy. `saturating_sub` ensures we get 0 if `pos` goes past `end`.
731        let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
732
733        if len_to_copy > 0 {
734            // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end`
735            // yet, so it is valid for write per the type invariants.
736            unsafe {
737                core::ptr::copy_nonoverlapping(
738                    s.as_bytes().as_ptr(),
739                    self.pos as *mut u8,
740                    len_to_copy,
741                )
742            };
743        }
744
745        self.pos = pos_new;
746        Ok(())
747    }
748}
749
750/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
751///
752/// Fails if callers attempt to write more than will fit in the buffer.
753pub(crate) struct Formatter(RawFormatter);
754
755impl Formatter {
756    /// Creates a new instance of [`Formatter`] with the given buffer.
757    ///
758    /// # Safety
759    ///
760    /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
761    /// for the lifetime of the returned [`Formatter`].
762    pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
763        // SAFETY: The safety requirements of this function satisfy those of the callee.
764        Self(unsafe { RawFormatter::from_buffer(buf, len) })
765    }
766}
767
768impl Deref for Formatter {
769    type Target = RawFormatter;
770
771    fn deref(&self) -> &Self::Target {
772        &self.0
773    }
774}
775
776impl fmt::Write for Formatter {
777    fn write_str(&mut self, s: &str) -> fmt::Result {
778        self.0.write_str(s)?;
779
780        // Fail the request if we go past the end of the buffer.
781        if self.0.pos > self.0.end {
782            Err(fmt::Error)
783        } else {
784            Ok(())
785        }
786    }
787}
788
789/// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
790///
791/// Used for interoperability with kernel APIs that take C strings.
792///
793/// # Invariants
794///
795/// The string is always `NUL`-terminated and contains no other `NUL` bytes.
796///
797/// # Examples
798///
799/// ```
800/// use kernel::{str::CString, fmt};
801///
802/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap();
803/// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes());
804///
805/// let tmp = "testing";
806/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap();
807/// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes());
808///
809/// // This fails because it has an embedded `NUL` byte.
810/// let s = CString::try_from_fmt(fmt!("a\0b{}", 123));
811/// assert_eq!(s.is_ok(), false);
812/// ```
813pub struct CString {
814    buf: KVec<u8>,
815}
816
817impl CString {
818    /// Creates an instance of [`CString`] from the given formatted arguments.
819    pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
820        // Calculate the size needed (formatted string plus `NUL` terminator).
821        let mut f = RawFormatter::new();
822        f.write_fmt(args)?;
823        f.write_str("\0")?;
824        let size = f.bytes_written();
825
826        // Allocate a vector with the required number of bytes, and write to it.
827        let mut buf = KVec::with_capacity(size, GFP_KERNEL)?;
828        // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
829        let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
830        f.write_fmt(args)?;
831        f.write_str("\0")?;
832
833        // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
834        // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`.
835        unsafe { buf.set_len(f.bytes_written()) };
836
837        // Check that there are no `NUL` bytes before the end.
838        // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
839        // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator)
840        // so `f.bytes_written() - 1` doesn't underflow.
841        let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, f.bytes_written() - 1) };
842        if !ptr.is_null() {
843            return Err(EINVAL);
844        }
845
846        // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes
847        // exist in the buffer.
848        Ok(Self { buf })
849    }
850}
851
852impl Deref for CString {
853    type Target = CStr;
854
855    fn deref(&self) -> &Self::Target {
856        // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no
857        // other `NUL` bytes exist.
858        unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
859    }
860}
861
862impl DerefMut for CString {
863    fn deref_mut(&mut self) -> &mut Self::Target {
864        // SAFETY: A `CString` is always NUL-terminated and contains no other
865        // NUL bytes.
866        unsafe { CStr::from_bytes_with_nul_unchecked_mut(self.buf.as_mut_slice()) }
867    }
868}
869
870impl<'a> TryFrom<&'a CStr> for CString {
871    type Error = AllocError;
872
873    fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
874        let mut buf = KVec::new();
875
876        buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?;
 
877
878        // INVARIANT: The `CStr` and `CString` types have the same invariants for
879        // the string data, and we copied it over without changes.
880        Ok(CString { buf })
881    }
882}
883
884impl fmt::Debug for CString {
885    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
886        fmt::Debug::fmt(&**self, f)
887    }
888}
889
890/// A convenience alias for [`core::format_args`].
891#[macro_export]
892macro_rules! fmt {
893    ($($f:tt)*) => ( core::format_args!($($f)*) )
894}