Skip to content

Commit 87482d6

Browse files
Andreas Hindborgaxboe
authored andcommitted
rust: str: allow str::Formatter to format into &mut [u8].
Improve `Formatter` so that it can write to an array or slice buffer. Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://lore.kernel.org/r/20250902-rnull-up-v6-16-v7-2-b5212cc89b98@kernel.org Signed-off-by: Jens Axboe <axboe@kernel.dk>
1 parent d5d060d commit 87482d6

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

rust/kernel/str.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ use crate::{
77
fmt::{self, Write},
88
prelude::*,
99
};
10-
use core::ops::{self, Deref, DerefMut, Index};
10+
use core::{
11+
marker::PhantomData,
12+
ops::{self, Deref, DerefMut, Index},
13+
};
1114

1215
/// Byte string without UTF-8 validity guarantee.
1316
#[repr(transparent)]
@@ -825,9 +828,9 @@ impl fmt::Write for RawFormatter {
825828
/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
826829
///
827830
/// Fails if callers attempt to write more than will fit in the buffer.
828-
pub(crate) struct Formatter(RawFormatter);
831+
pub(crate) struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>);
829832

830-
impl Formatter {
833+
impl Formatter<'_> {
831834
/// Creates a new instance of [`Formatter`] with the given buffer.
832835
///
833836
/// # Safety
@@ -836,19 +839,27 @@ impl Formatter {
836839
/// for the lifetime of the returned [`Formatter`].
837840
pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
838841
// SAFETY: The safety requirements of this function satisfy those of the callee.
839-
Self(unsafe { RawFormatter::from_buffer(buf, len) })
842+
Self(unsafe { RawFormatter::from_buffer(buf, len) }, PhantomData)
843+
}
844+
845+
/// Create a new [`Self`] instance.
846+
#[expect(dead_code)]
847+
pub(crate) fn new(buffer: &mut [u8]) -> Self {
848+
// SAFETY: `buffer` is valid for writes for the entire length for
849+
// the lifetime of `Self`.
850+
unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) }
840851
}
841852
}
842853

843-
impl Deref for Formatter {
854+
impl Deref for Formatter<'_> {
844855
type Target = RawFormatter;
845856

846857
fn deref(&self) -> &Self::Target {
847858
&self.0
848859
}
849860
}
850861

851-
impl fmt::Write for Formatter {
862+
impl fmt::Write for Formatter<'_> {
852863
fn write_str(&mut self, s: &str) -> fmt::Result {
853864
self.0.write_str(s)?;
854865

0 commit comments

Comments
 (0)