str.rs 29 KB

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