Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: str: add `Formatter` type

Add the `Formatter` type, which leverages `RawFormatter`,
but fails if callers attempt to write more than will fit
in the buffer.

In order to so, implement the `RawFormatter::from_buffer()`
constructor as well.

Co-developed-by: Adam Bratschi-Kaye <ark.email@gmail.com>
Signed-off-by: Adam Bratschi-Kaye <ark.email@gmail.com>
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
[Reworded, adapted for upstream and applied latest changes]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

authored by

Wedson Almeida Filho and committed by
Miguel Ojeda
fffed679 b18cb00e

+57
+57
rust/kernel/str.rs
··· 406 406 } 407 407 } 408 408 409 + /// Creates a new instance of [`RawFormatter`] with the given buffer. 410 + /// 411 + /// # Safety 412 + /// 413 + /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes 414 + /// for the lifetime of the returned [`RawFormatter`]. 415 + pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { 416 + let pos = buf as usize; 417 + // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements 418 + // guarantees that the memory region is valid for writes. 419 + Self { 420 + pos, 421 + beg: pos, 422 + end: pos.saturating_add(len), 423 + } 424 + } 425 + 409 426 /// Returns the current insert position. 410 427 /// 411 428 /// N.B. It may point to invalid memory. ··· 454 437 455 438 self.pos = pos_new; 456 439 Ok(()) 440 + } 441 + } 442 + 443 + /// Allows formatting of [`fmt::Arguments`] into a raw buffer. 444 + /// 445 + /// Fails if callers attempt to write more than will fit in the buffer. 446 + pub(crate) struct Formatter(RawFormatter); 447 + 448 + impl Formatter { 449 + /// Creates a new instance of [`Formatter`] with the given buffer. 450 + /// 451 + /// # Safety 452 + /// 453 + /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes 454 + /// for the lifetime of the returned [`Formatter`]. 455 + #[allow(dead_code)] 456 + pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { 457 + // SAFETY: The safety requirements of this function satisfy those of the callee. 458 + Self(unsafe { RawFormatter::from_buffer(buf, len) }) 459 + } 460 + } 461 + 462 + impl Deref for Formatter { 463 + type Target = RawFormatter; 464 + 465 + fn deref(&self) -> &Self::Target { 466 + &self.0 467 + } 468 + } 469 + 470 + impl fmt::Write for Formatter { 471 + fn write_str(&mut self, s: &str) -> fmt::Result { 472 + self.0.write_str(s)?; 473 + 474 + // Fail the request if we go past the end of the buffer. 475 + if self.0.pos > self.0.end { 476 + Err(fmt::Error) 477 + } else { 478 + Ok(()) 479 + } 457 480 } 458 481 }