~ [ 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-4.16.18)


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

~ [ 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