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