~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/rust/kernel/str.rs

Version: ~ [ linux-6.12-rc7 ] ~ [ linux-6.11.7 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.60 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.116 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.171 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.229 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.285 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.323 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.12 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /rust/kernel/str.rs (Version linux-6.12-rc7) and /rust/kernel/str.rs (Version linux-6.9.12)


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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php