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