Skip to content

Commit 6e47c00

Browse files
Andreas Hindborgkawasaki
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. Signed-off-by: Andreas Hindborg <[email protected]>
1 parent 0950afe commit 6e47c00

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

rust/kernel/str.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::alloc::{flags::*, AllocError, KVec};
66
use crate::prelude::*;
77
use core::{
88
fmt::{self, Write},
9+
marker::PhantomData,
910
ops::{self, Deref, DerefMut, Index},
1011
};
1112

@@ -794,9 +795,9 @@ impl fmt::Write for RawFormatter {
794795
/// Allows formatting of [`fmt::Arguments`] into a raw buffer.
795796
///
796797
/// Fails if callers attempt to write more than will fit in the buffer.
797-
pub(crate) struct Formatter(RawFormatter);
798+
pub(crate) struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>);
798799

799-
impl Formatter {
800+
impl Formatter<'_> {
800801
/// Creates a new instance of [`Formatter`] with the given buffer.
801802
///
802803
/// # Safety
@@ -805,19 +806,27 @@ impl Formatter {
805806
/// for the lifetime of the returned [`Formatter`].
806807
pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
807808
// SAFETY: The safety requirements of this function satisfy those of the callee.
808-
Self(unsafe { RawFormatter::from_buffer(buf, len) })
809+
Self(unsafe { RawFormatter::from_buffer(buf, len) }, PhantomData)
810+
}
811+
812+
/// Create a new [`Self`] instance.
813+
#[expect(dead_code)]
814+
pub(crate) fn new<'a>(buffer: &'a mut [u8]) -> Formatter<'a> {
815+
// SAFETY: `buffer` is valid for writes for the entire length for
816+
// the lifetime of `Self`.
817+
unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) }
809818
}
810819
}
811820

812-
impl Deref for Formatter {
821+
impl Deref for Formatter<'_> {
813822
type Target = RawFormatter;
814823

815824
fn deref(&self) -> &Self::Target {
816825
&self.0
817826
}
818827
}
819828

820-
impl fmt::Write for Formatter {
829+
impl fmt::Write for Formatter<'_> {
821830
fn write_str(&mut self, s: &str) -> fmt::Result {
822831
self.0.write_str(s)?;
823832

0 commit comments

Comments
 (0)