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