Skip to main content

kernel/
str.rs

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