kernel/str.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! String representations.
4
5use crate::{
6 alloc::{
7 AllocError,
8 KVec, //
9 },
10 error::{
11 to_result,
12 Result, //
13 },
14 fmt::{
15 self,
16 Write, //
17 },
18 prelude::*, //
19};
20use core::{
21 marker::PhantomData,
22 ops::{
23 Deref,
24 DerefMut,
25 Index, //
26 }, //
27};
28
29pub use crate::prelude::CStr;
30
31pub mod parse_int;
32
33/// Byte string without UTF-8 validity guarantee.
34#[repr(transparent)]
35pub struct BStr([u8]);
36
37impl BStr {
38 /// Returns the length of this string.
39 #[inline]
40 pub const fn len(&self) -> usize {
41 self.0.len()
42 }
43
44 /// Returns `true` if the string is empty.
45 #[inline]
46 pub const fn is_empty(&self) -> bool {
47 self.len() == 0
48 }
49
50 /// Creates a [`BStr`] from a `[u8]`.
51 #[inline]
52 pub const fn from_bytes(bytes: &[u8]) -> &Self {
53 // SAFETY: `BStr` is transparent to `[u8]`.
54 unsafe { &*(core::ptr::from_ref(bytes) as *const BStr) }
55 }
56
57 /// Strip a prefix from `self`. Delegates to [`slice::strip_prefix`].
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// # use kernel::b_str;
63 /// assert_eq!(Some(b_str!("bar")), b_str!("foobar").strip_prefix(b_str!("foo")));
64 /// assert_eq!(None, b_str!("foobar").strip_prefix(b_str!("bar")));
65 /// assert_eq!(Some(b_str!("foobar")), b_str!("foobar").strip_prefix(b_str!("")));
66 /// assert_eq!(Some(b_str!("")), b_str!("foobar").strip_prefix(b_str!("foobar")));
67 /// ```
68 pub fn strip_prefix(&self, pattern: impl AsRef<Self>) -> Option<&BStr> {
69 self.deref()
70 .strip_prefix(pattern.as_ref().deref())
71 .map(Self::from_bytes)
72 }
73}
74
75impl fmt::Display for BStr {
76 /// Formats printable ASCII characters, escaping the rest.
77 ///
78 /// ```
79 /// # use kernel::{prelude::fmt, b_str, str::{BStr, CString}};
80 /// let ascii = b_str!("Hello, BStr!");
81 /// let s = CString::try_from_fmt(fmt!("{ascii}"))?;
82 /// assert_eq!(s.to_bytes(), "Hello, BStr!".as_bytes());
83 ///
84 /// let non_ascii = b_str!("🦀");
85 /// let s = CString::try_from_fmt(fmt!("{non_ascii}"))?;
86 /// assert_eq!(s.to_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes());
87 /// # Ok::<(), kernel::error::Error>(())
88 /// ```
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 for &b in &self.0 {
91 match b {
92 // Common escape codes.
93 b'\t' => f.write_str("\\t")?,
94 b'\n' => f.write_str("\\n")?,
95 b'\r' => f.write_str("\\r")?,
96 // Printable characters.
97 0x20..=0x7e => f.write_char(b as char)?,
98 _ => write!(f, "\\x{b:02x}")?,
99 }
100 }
101 Ok(())
102 }
103}
104
105impl fmt::Debug for BStr {
106 /// Formats printable ASCII characters with a double quote on either end,
107 /// escaping the rest.
108 ///
109 /// ```
110 /// # use kernel::{prelude::fmt, b_str, str::{BStr, CString}};
111 /// // Embedded double quotes are escaped.
112 /// let ascii = b_str!("Hello, \"BStr\"!");
113 /// let s = CString::try_from_fmt(fmt!("{ascii:?}"))?;
114 /// assert_eq!(s.to_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes());
115 ///
116 /// let non_ascii = b_str!("😺");
117 /// let s = CString::try_from_fmt(fmt!("{non_ascii:?}"))?;
118 /// assert_eq!(s.to_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes());
119 /// # Ok::<(), kernel::error::Error>(())
120 /// ```
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_char('"')?;
123 for &b in &self.0 {
124 match b {
125 // Common escape codes.
126 b'\t' => f.write_str("\\t")?,
127 b'\n' => f.write_str("\\n")?,
128 b'\r' => f.write_str("\\r")?,
129 // String escape characters.
130 b'\"' => f.write_str("\\\"")?,
131 b'\\' => f.write_str("\\\\")?,
132 // Printable characters.
133 0x20..=0x7e => f.write_char(b as char)?,
134 _ => write!(f, "\\x{b:02x}")?,
135 }
136 }
137 f.write_char('"')
138 }
139}
140
141impl Deref for BStr {
142 type Target = [u8];
143
144 #[inline]
145 fn deref(&self) -> &Self::Target {
146 &self.0
147 }
148}
149
150impl PartialEq for BStr {
151 fn eq(&self, other: &Self) -> bool {
152 self.deref().eq(other.deref())
153 }
154}
155
156impl<Idx> Index<Idx> for BStr
157where
158 [u8]: Index<Idx, Output = [u8]>,
159{
160 type Output = Self;
161
162 fn index(&self, index: Idx) -> &Self::Output {
163 BStr::from_bytes(&self.0[index])
164 }
165}
166
167impl AsRef<BStr> for [u8] {
168 fn as_ref(&self) -> &BStr {
169 BStr::from_bytes(self)
170 }
171}
172
173impl AsRef<BStr> for BStr {
174 fn as_ref(&self) -> &BStr {
175 self
176 }
177}
178
179/// Creates a new [`BStr`] from a string literal.
180///
181/// `b_str!` converts the supplied string literal to byte string, so non-ASCII
182/// characters can be included.
183///
184/// # Examples
185///
186/// ```
187/// # use kernel::b_str;
188/// # use kernel::str::BStr;
189/// const MY_BSTR: &BStr = b_str!("My awesome BStr!");
190/// ```
191#[macro_export]
192macro_rules! b_str {
193 ($str:literal) => {{
194 const S: &'static str = $str;
195 const C: &'static $crate::str::BStr = $crate::str::BStr::from_bytes(S.as_bytes());
196 C
197 }};
198}
199
200/// Returns a C pointer to the string.
201// It is a free function rather than a method on an extension trait because:
202//
203// - error[E0379]: functions in trait impls cannot be declared const
204#[inline]
205#[expect(clippy::disallowed_methods, reason = "internal implementation")]
206pub const fn as_char_ptr_in_const_context(c_str: &CStr) -> *const c_char {
207 c_str.as_ptr().cast()
208}
209
210mod private {
211 pub trait Sealed {}
212
213 impl Sealed for super::CStr {}
214}
215
216/// Extensions to [`CStr`].
217pub trait CStrExt: private::Sealed {
218 /// Wraps a raw C string pointer.
219 ///
220 /// # Safety
221 ///
222 /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must
223 /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr`
224 /// must not be mutated.
225 // This function exists to paper over the fact that `CStr::from_ptr` takes a `*const
226 // core::ffi::c_char` rather than a `*const crate::ffi::c_char`.
227 unsafe fn from_char_ptr<'a>(ptr: *const c_char) -> &'a Self;
228
229 /// Creates a mutable [`CStr`] from a `[u8]` without performing any
230 /// additional checks.
231 ///
232 /// # Safety
233 ///
234 /// `bytes` *must* end with a `NUL` byte, and should only have a single
235 /// `NUL` byte (or the string will be truncated).
236 unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut Self;
237
238 /// Returns a C pointer to the string.
239 // This function exists to paper over the fact that `CStr::as_ptr` returns a `*const
240 // core::ffi::c_char` rather than a `*const crate::ffi::c_char`.
241 fn as_char_ptr(&self) -> *const c_char;
242
243 /// Convert this [`CStr`] into a [`CString`] by allocating memory and
244 /// copying over the string data.
245 fn to_cstring(&self) -> Result<CString, AllocError>;
246
247 /// Converts this [`CStr`] to its ASCII lower case equivalent in-place.
248 ///
249 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
250 /// but non-ASCII letters are unchanged.
251 ///
252 /// To return a new lowercased value without modifying the existing one, use
253 /// [`to_ascii_lowercase()`].
254 ///
255 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
256 fn make_ascii_lowercase(&mut self);
257
258 /// Converts this [`CStr`] to its ASCII upper case equivalent in-place.
259 ///
260 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
261 /// but non-ASCII letters are unchanged.
262 ///
263 /// To return a new uppercased value without modifying the existing one, use
264 /// [`to_ascii_uppercase()`].
265 ///
266 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
267 fn make_ascii_uppercase(&mut self);
268
269 /// Returns a copy of this [`CString`] where each character is mapped to its
270 /// ASCII lower case equivalent.
271 ///
272 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
273 /// but non-ASCII letters are unchanged.
274 ///
275 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
276 ///
277 /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
278 fn to_ascii_lowercase(&self) -> Result<CString, AllocError>;
279
280 /// Returns a copy of this [`CString`] where each character is mapped to its
281 /// ASCII upper case equivalent.
282 ///
283 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
284 /// but non-ASCII letters are unchanged.
285 ///
286 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
287 ///
288 /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
289 fn to_ascii_uppercase(&self) -> Result<CString, AllocError>;
290}
291
292impl fmt::Display for CStr {
293 /// Formats printable ASCII characters, escaping the rest.
294 ///
295 /// ```
296 /// # use kernel::prelude::fmt;
297 /// # use kernel::str::CStr;
298 /// # use kernel::str::CString;
299 /// let penguin = c"🐧";
300 /// let s = CString::try_from_fmt(fmt!("{penguin}"))?;
301 /// assert_eq!(s.to_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
302 ///
303 /// let ascii = c"so \"cool\"";
304 /// let s = CString::try_from_fmt(fmt!("{ascii}"))?;
305 /// assert_eq!(s.to_bytes_with_nul(), "so \"cool\"\0".as_bytes());
306 /// # Ok::<(), kernel::error::Error>(())
307 /// ```
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 for &c in self.to_bytes() {
310 if (0x20..0x7f).contains(&c) {
311 // Printable character.
312 f.write_char(c as char)?;
313 } else {
314 write!(f, "\\x{c:02x}")?;
315 }
316 }
317 Ok(())
318 }
319}
320
321/// Converts a mutable C string to a mutable byte slice.
322///
323/// # Safety
324///
325/// The caller must ensure that the slice ends in a NUL byte and contains no other NUL bytes before
326/// the borrow ends and the underlying [`CStr`] is used.
327unsafe fn to_bytes_mut(s: &mut CStr) -> &mut [u8] {
328 // SAFETY: the cast from `&CStr` to `&[u8]` is safe since `CStr` has the same layout as `&[u8]`
329 // (this is technically not guaranteed, but we rely on it here). The pointer dereference is
330 // safe since it comes from a mutable reference which is guaranteed to be valid for writes.
331 unsafe { &mut *(core::ptr::from_mut(s) as *mut [u8]) }
332}
333
334impl CStrExt for CStr {
335 #[inline]
336 #[expect(clippy::disallowed_methods, reason = "internal implementation")]
337 unsafe fn from_char_ptr<'a>(ptr: *const c_char) -> &'a Self {
338 // SAFETY: The safety preconditions are the same as for `CStr::from_ptr`.
339 unsafe { CStr::from_ptr(ptr.cast()) }
340 }
341
342 #[inline]
343 unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut Self {
344 // SAFETY: the cast from `&[u8]` to `&CStr` is safe since the properties of `bytes` are
345 // guaranteed by the safety precondition and `CStr` has the same layout as `&[u8]` (this is
346 // technically not guaranteed, but we rely on it here). The pointer dereference is safe
347 // since it comes from a mutable reference which is guaranteed to be valid for writes.
348 unsafe { &mut *(core::ptr::from_mut(bytes) as *mut CStr) }
349 }
350
351 #[inline]
352 #[expect(clippy::disallowed_methods, reason = "internal implementation")]
353 fn as_char_ptr(&self) -> *const c_char {
354 self.as_ptr().cast()
355 }
356
357 fn to_cstring(&self) -> Result<CString, AllocError> {
358 CString::try_from(self)
359 }
360
361 fn make_ascii_lowercase(&mut self) {
362 // SAFETY: This doesn't introduce or remove NUL bytes in the C string.
363 unsafe { to_bytes_mut(self) }.make_ascii_lowercase();
364 }
365
366 fn make_ascii_uppercase(&mut self) {
367 // SAFETY: This doesn't introduce or remove NUL bytes in the C string.
368 unsafe { to_bytes_mut(self) }.make_ascii_uppercase();
369 }
370
371 fn to_ascii_lowercase(&self) -> Result<CString, AllocError> {
372 let mut s = self.to_cstring()?;
373
374 s.make_ascii_lowercase();
375
376 Ok(s)
377 }
378
379 fn to_ascii_uppercase(&self) -> Result<CString, AllocError> {
380 let mut s = self.to_cstring()?;
381
382 s.make_ascii_uppercase();
383
384 Ok(s)
385 }
386}
387
388impl AsRef<BStr> for CStr {
389 #[inline]
390 fn as_ref(&self) -> &BStr {
391 BStr::from_bytes(self.to_bytes())
392 }
393}
394
395/// Creates a new [`CStr`] at compile time.
396///
397/// Rust supports C string literals since Rust 1.77, and they should be used instead of this macro
398/// where possible. This macro exists to allow static *non-literal* C strings to be created at
399/// compile time. This is most often used in other macros.
400///
401/// # Panics
402///
403/// This macro panics if the operand contains an interior `NUL` byte.
404///
405/// # Examples
406///
407/// ```
408/// # use kernel::c_str;
409/// # use kernel::str::CStr;
410/// // This is allowed, but `c"literal"` should be preferred for literals.
411/// const BAD: &CStr = c_str!("literal");
412///
413/// // `c_str!` is still needed for static non-literal C strings.
414/// const GOOD: &CStr = c_str!(concat!(file!(), ":", line!(), ": My CStr!"));
415/// ```
416#[macro_export]
417macro_rules! c_str {
418 // NB: We could write `($str:lit) => compile_error!("use a C string literal instead");` here but
419 // that would trigger when the literal is at the top of several macro expansions. That would be
420 // too limiting to macro authors.
421 ($str:expr) => {{
422 const S: &str = concat!($str, "\0");
423 const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
424 Ok(v) => v,
425 Err(_) => panic!("string contains interior NUL"),
426 };
427 C
428 }};
429}
430
431#[kunit_tests(rust_kernel_str)]
432mod tests {
433 use super::*;
434
435 impl From<core::ffi::FromBytesWithNulError> for Error {
436 #[inline]
437 fn from(_: core::ffi::FromBytesWithNulError) -> Error {
438 EINVAL
439 }
440 }
441
442 macro_rules! format {
443 ($($f:tt)*) => ({
444 CString::try_from_fmt(fmt!($($f)*))?.to_str()?
445 })
446 }
447
448 const ALL_ASCII_CHARS: &str =
449 "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\
450 \\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \
451 !\"#$%&'()*+,-./0123456789:;<=>?@\
452 ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f\
453 \\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\
454 \\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\
455 \\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\
456 \\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\
457 \\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\
458 \\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\
459 \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\
460 \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff";
461
462 #[test]
463 fn test_cstr_to_str() -> Result {
464 let cstr = c"\xf0\x9f\xa6\x80";
465 let checked_str = cstr.to_str()?;
466 assert_eq!(checked_str, "🦀");
467 Ok(())
468 }
469
470 #[test]
471 fn test_cstr_to_str_invalid_utf8() -> Result {
472 let cstr = c"\xc3\x28";
473 assert!(cstr.to_str().is_err());
474 Ok(())
475 }
476
477 #[test]
478 fn test_cstr_display() -> Result {
479 let hello_world = c"hello, world!";
480 assert_eq!(format!("{hello_world}"), "hello, world!");
481 let non_printables = c"\x01\x09\x0a";
482 assert_eq!(format!("{non_printables}"), "\\x01\\x09\\x0a");
483 let non_ascii = c"d\xe9j\xe0 vu";
484 assert_eq!(format!("{non_ascii}"), "d\\xe9j\\xe0 vu");
485 let good_bytes = c"\xf0\x9f\xa6\x80";
486 assert_eq!(format!("{good_bytes}"), "\\xf0\\x9f\\xa6\\x80");
487 Ok(())
488 }
489
490 #[test]
491 fn test_cstr_display_all_bytes() -> Result {
492 let mut bytes: [u8; 256] = [0; 256];
493 // fill `bytes` with [1..=255] + [0]
494 for i in u8::MIN..=u8::MAX {
495 bytes[i as usize] = i.wrapping_add(1);
496 }
497 let cstr = CStr::from_bytes_with_nul(&bytes)?;
498 assert_eq!(format!("{cstr}"), ALL_ASCII_CHARS);
499 Ok(())
500 }
501
502 #[test]
503 fn test_cstr_debug() -> Result {
504 let hello_world = c"hello, world!";
505 assert_eq!(format!("{hello_world:?}"), "\"hello, world!\"");
506 let non_printables = c"\x01\x09\x0a";
507 assert_eq!(format!("{non_printables:?}"), "\"\\x01\\t\\n\"");
508 let non_ascii = c"d\xe9j\xe0 vu";
509 assert_eq!(format!("{non_ascii:?}"), "\"d\\xe9j\\xe0 vu\"");
510 Ok(())
511 }
512
513 #[test]
514 fn test_bstr_display() -> Result {
515 let hello_world = BStr::from_bytes(b"hello, world!");
516 assert_eq!(format!("{hello_world}"), "hello, world!");
517 let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
518 assert_eq!(format!("{escapes}"), "_\\t_\\n_\\r_\\_'_\"_");
519 let others = BStr::from_bytes(b"\x01");
520 assert_eq!(format!("{others}"), "\\x01");
521 let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
522 assert_eq!(format!("{non_ascii}"), "d\\xe9j\\xe0 vu");
523 let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
524 assert_eq!(format!("{good_bytes}"), "\\xf0\\x9f\\xa6\\x80");
525 Ok(())
526 }
527
528 #[test]
529 fn test_bstr_debug() -> Result {
530 let hello_world = BStr::from_bytes(b"hello, world!");
531 assert_eq!(format!("{hello_world:?}"), "\"hello, world!\"");
532 let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_");
533 assert_eq!(format!("{escapes:?}"), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\"");
534 let others = BStr::from_bytes(b"\x01");
535 assert_eq!(format!("{others:?}"), "\"\\x01\"");
536 let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu");
537 assert_eq!(format!("{non_ascii:?}"), "\"d\\xe9j\\xe0 vu\"");
538 let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80");
539 assert_eq!(format!("{good_bytes:?}"), "\"\\xf0\\x9f\\xa6\\x80\"");
540 Ok(())
541 }
542}
543
544/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
545///
546/// It does not fail if callers write past the end of the buffer so that they can calculate the
547/// size required to fit everything.
548///
549/// # Invariants
550///
551/// The memory region between `pos` (inclusive) and `end` (exclusive) is valid for writes if `pos`
552/// is less than `end`.
553pub struct RawFormatter {
554 // Use `usize` to use `saturating_*` functions.
555 beg: usize,
556 pos: usize,
557 end: usize,
558}
559
560impl RawFormatter {
561 /// Creates a new instance of [`RawFormatter`] with an empty buffer.
562 fn new() -> Self {
563 // INVARIANT: The buffer is empty, so the region that needs to be writable is empty.
564 Self {
565 beg: 0,
566 pos: 0,
567 end: 0,
568 }
569 }
570
571 /// Creates a new instance of [`RawFormatter`] with the given buffer pointers.
572 ///
573 /// # Safety
574 ///
575 /// If `pos` is less than `end`, then the region between `pos` (inclusive) and `end`
576 /// (exclusive) must be valid for writes for the lifetime of the returned [`RawFormatter`].
577 pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
578 // INVARIANT: The safety requirements guarantee the type invariants.
579 Self {
580 beg: pos as usize,
581 pos: pos as usize,
582 end: end as usize,
583 }
584 }
585
586 /// Creates a new instance of [`RawFormatter`] with the given buffer.
587 ///
588 /// # Safety
589 ///
590 /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
591 /// for the lifetime of the returned [`RawFormatter`].
592 pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
593 let pos = buf as usize;
594 // INVARIANT: We ensure that `end` is never less than `buf`, and the safety requirements
595 // guarantees that the memory region is valid for writes.
596 Self {
597 pos,
598 beg: pos,
599 end: pos.saturating_add(len),
600 }
601 }
602
603 /// Returns the current insert position.
604 ///
605 /// N.B. It may point to invalid memory.
606 pub(crate) fn pos(&self) -> *mut u8 {
607 self.pos as *mut u8
608 }
609
610 /// Returns the number of bytes written to the formatter.
611 pub fn bytes_written(&self) -> usize {
612 self.pos - self.beg
613 }
614}
615
616impl fmt::Write for RawFormatter {
617 fn write_str(&mut self, s: &str) -> fmt::Result {
618 // `pos` value after writing `len` bytes. This does not have to be bounded by `end`, but we
619 // don't want it to wrap around to 0.
620 let pos_new = self.pos.saturating_add(s.len());
621
622 // Amount that we can copy. `saturating_sub` ensures we get 0 if `pos` goes past `end`.
623 let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
624
625 if len_to_copy > 0 {
626 // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end`
627 // yet, so it is valid for write per the type invariants.
628 unsafe {
629 core::ptr::copy_nonoverlapping(
630 s.as_bytes().as_ptr(),
631 self.pos as *mut u8,
632 len_to_copy,
633 )
634 };
635 }
636
637 self.pos = pos_new;
638 Ok(())
639 }
640}
641
642/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
643///
644/// Fails if callers attempt to write more than will fit in the buffer.
645pub struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>);
646
647impl Formatter<'_> {
648 /// Creates a new instance of [`Formatter`] with the given buffer.
649 ///
650 /// # Safety
651 ///
652 /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
653 /// for the lifetime of the returned [`Formatter`].
654 pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
655 // SAFETY: The safety requirements of this function satisfy those of the callee.
656 Self(unsafe { RawFormatter::from_buffer(buf, len) }, PhantomData)
657 }
658
659 /// Create a new [`Self`] instance.
660 pub fn new(buffer: &mut [u8]) -> Self {
661 // SAFETY: `buffer` is valid for writes for the entire length for
662 // the lifetime of `Self`.
663 unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) }
664 }
665}
666
667impl Deref for Formatter<'_> {
668 type Target = RawFormatter;
669
670 fn deref(&self) -> &Self::Target {
671 &self.0
672 }
673}
674
675impl fmt::Write for Formatter<'_> {
676 fn write_str(&mut self, s: &str) -> fmt::Result {
677 self.0.write_str(s)?;
678
679 // Fail the request if we go past the end of the buffer.
680 if self.0.pos > self.0.end {
681 Err(fmt::Error)
682 } else {
683 Ok(())
684 }
685 }
686}
687
688/// A mutable reference to a byte buffer where a string can be written into.
689///
690/// The buffer will be automatically null terminated after the last written character.
691///
692/// # Invariants
693///
694/// * The first byte of `buffer` is always zero.
695/// * The length of `buffer` is at least 1.
696pub struct NullTerminatedFormatter<'a> {
697 buffer: &'a mut [u8],
698}
699
700impl<'a> NullTerminatedFormatter<'a> {
701 /// Create a new [`Self`] instance.
702 pub fn new(buffer: &'a mut [u8]) -> Option<NullTerminatedFormatter<'a>> {
703 *(buffer.first_mut()?) = 0;
704
705 // INVARIANT:
706 // - We wrote zero to the first byte above.
707 // - If buffer was not at least length 1, `buffer.first_mut()` would return None.
708 Some(Self { buffer })
709 }
710}
711
712impl Write for NullTerminatedFormatter<'_> {
713 fn write_str(&mut self, s: &str) -> fmt::Result {
714 let bytes = s.as_bytes();
715 let len = bytes.len();
716
717 // We want space for a zero. By type invariant, buffer length is always at least 1, so no
718 // underflow.
719 if len > self.buffer.len() - 1 {
720 return Err(fmt::Error);
721 }
722
723 let buffer = core::mem::take(&mut self.buffer);
724 // We break the zero start invariant for a short while.
725 buffer[..len].copy_from_slice(bytes);
726 // INVARIANT: We checked above that buffer will have size at least 1 after this assignment.
727 self.buffer = &mut buffer[len..];
728
729 // INVARIANT: We write zero to the first byte of the buffer.
730 self.buffer[0] = 0;
731
732 Ok(())
733 }
734}
735
736/// # Safety
737///
738/// - `string` must point to a null terminated string that is valid for read.
739unsafe fn kstrtobool_raw(string: *const u8) -> Result<bool> {
740 let mut result: bool = false;
741
742 // SAFETY:
743 // - By function safety requirement, `string` is a valid null-terminated string.
744 // - `result` is a valid `bool` that we own.
745 to_result(unsafe { bindings::kstrtobool(string, &mut result) })?;
746 Ok(result)
747}
748
749/// Convert common user inputs into boolean values using the kernel's `kstrtobool` function.
750///
751/// This routine returns `Ok(bool)` if the first character is one of 'YyTt1NnFf0', or
752/// \[oO\]\[NnFf\] for "on" and "off". Otherwise it will return `Err(EINVAL)`.
753///
754/// # Examples
755///
756/// ```
757/// # use kernel::str::kstrtobool;
758///
759/// // Lowercase
760/// assert_eq!(kstrtobool(c"true"), Ok(true));
761/// assert_eq!(kstrtobool(c"tr"), Ok(true));
762/// assert_eq!(kstrtobool(c"t"), Ok(true));
763/// assert_eq!(kstrtobool(c"twrong"), Ok(true));
764/// assert_eq!(kstrtobool(c"false"), Ok(false));
765/// assert_eq!(kstrtobool(c"f"), Ok(false));
766/// assert_eq!(kstrtobool(c"yes"), Ok(true));
767/// assert_eq!(kstrtobool(c"no"), Ok(false));
768/// assert_eq!(kstrtobool(c"on"), Ok(true));
769/// assert_eq!(kstrtobool(c"off"), Ok(false));
770///
771/// // Camel case
772/// assert_eq!(kstrtobool(c"True"), Ok(true));
773/// assert_eq!(kstrtobool(c"False"), Ok(false));
774/// assert_eq!(kstrtobool(c"Yes"), Ok(true));
775/// assert_eq!(kstrtobool(c"No"), Ok(false));
776/// assert_eq!(kstrtobool(c"On"), Ok(true));
777/// assert_eq!(kstrtobool(c"Off"), Ok(false));
778///
779/// // All caps
780/// assert_eq!(kstrtobool(c"TRUE"), Ok(true));
781/// assert_eq!(kstrtobool(c"FALSE"), Ok(false));
782/// assert_eq!(kstrtobool(c"YES"), Ok(true));
783/// assert_eq!(kstrtobool(c"NO"), Ok(false));
784/// assert_eq!(kstrtobool(c"ON"), Ok(true));
785/// assert_eq!(kstrtobool(c"OFF"), Ok(false));
786///
787/// // Numeric
788/// assert_eq!(kstrtobool(c"1"), Ok(true));
789/// assert_eq!(kstrtobool(c"0"), Ok(false));
790///
791/// // Invalid input
792/// assert_eq!(kstrtobool(c"invalid"), Err(EINVAL));
793/// assert_eq!(kstrtobool(c"2"), Err(EINVAL));
794/// ```
795pub fn kstrtobool(string: &CStr) -> Result<bool> {
796 // SAFETY:
797 // - The pointer returned by `CStr::as_char_ptr` is guaranteed to be
798 // null terminated.
799 // - `string` is live and thus the string is valid for read.
800 unsafe { kstrtobool_raw(string.as_char_ptr()) }
801}
802
803/// Convert `&[u8]` to `bool` by deferring to [`kernel::str::kstrtobool`].
804///
805/// Only considers at most the first two bytes of `bytes`.
806pub fn kstrtobool_bytes(bytes: &[u8]) -> Result<bool> {
807 // `ktostrbool` only considers the first two bytes of the input.
808 let stack_string = [*bytes.first().unwrap_or(&0), *bytes.get(1).unwrap_or(&0), 0];
809 // SAFETY: `stack_string` is null terminated and it is live on the stack so
810 // it is valid for read.
811 unsafe { kstrtobool_raw(stack_string.as_ptr()) }
812}
813
814/// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
815///
816/// Used for interoperability with kernel APIs that take C strings.
817///
818/// # Invariants
819///
820/// The string is always `NUL`-terminated and contains no other `NUL` bytes.
821///
822/// # Examples
823///
824/// ```
825/// use kernel::{str::CString, prelude::fmt};
826///
827/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20))?;
828/// assert_eq!(s.to_bytes_with_nul(), "abc1020\0".as_bytes());
829///
830/// let tmp = "testing";
831/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123))?;
832/// assert_eq!(s.to_bytes_with_nul(), "testing123\0".as_bytes());
833///
834/// // This fails because it has an embedded `NUL` byte.
835/// let s = CString::try_from_fmt(fmt!("a\0b{}", 123));
836/// assert_eq!(s.is_ok(), false);
837/// # Ok::<(), kernel::error::Error>(())
838/// ```
839pub struct CString {
840 buf: KVec<u8>,
841}
842
843impl CString {
844 /// Creates an instance of [`CString`] from the given formatted arguments.
845 pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
846 // Calculate the size needed (formatted string plus `NUL` terminator).
847 let mut f = RawFormatter::new();
848 f.write_fmt(args)?;
849 f.write_str("\0")?;
850 let size = f.bytes_written();
851
852 // Allocate a vector with the required number of bytes, and write to it.
853 let mut buf = KVec::with_capacity(size, GFP_KERNEL)?;
854 // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
855 let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
856 f.write_fmt(args)?;
857 f.write_str("\0")?;
858
859 // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
860 // `buf`'s capacity. The `Formatter` is created with `size` as its limit, and the `?`
861 // operators on `write_fmt` and `write_str` above ensure that if writing exceeds this
862 // limit, an error is returned early. The contents of the buffer have been initialised
863 // by writes to `f`.
864 unsafe { buf.inc_len(f.bytes_written()) };
865
866 // Check that there are no `NUL` bytes before the end.
867 // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
868 // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator)
869 // so `f.bytes_written() - 1` doesn't underflow.
870 let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, f.bytes_written() - 1) };
871 if !ptr.is_null() {
872 return Err(EINVAL);
873 }
874
875 // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes
876 // exist in the buffer.
877 Ok(Self { buf })
878 }
879}
880
881impl Deref for CString {
882 type Target = CStr;
883
884 fn deref(&self) -> &Self::Target {
885 // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no
886 // other `NUL` bytes exist.
887 unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
888 }
889}
890
891impl DerefMut for CString {
892 fn deref_mut(&mut self) -> &mut Self::Target {
893 // SAFETY: A `CString` is always NUL-terminated and contains no other
894 // NUL bytes.
895 unsafe { CStr::from_bytes_with_nul_unchecked_mut(self.buf.as_mut_slice()) }
896 }
897}
898
899impl<'a> TryFrom<&'a CStr> for CString {
900 type Error = AllocError;
901
902 fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
903 let mut buf = KVec::new();
904
905 buf.extend_from_slice(cstr.to_bytes_with_nul(), GFP_KERNEL)?;
906
907 // INVARIANT: The `CStr` and `CString` types have the same invariants for
908 // the string data, and we copied it over without changes.
909 Ok(CString { buf })
910 }
911}
912
913impl fmt::Debug for CString {
914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915 fmt::Debug::fmt(&**self, f)
916 }
917}