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