Linux Audio

Check our new training course

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