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: 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>

authored by

Andreas Hindborg and committed by
Jens Axboe
87482d6d d5d060d6

+17 -6
+17 -6
rust/kernel/str.rs
··· 7 7 fmt::{self, Write}, 8 8 prelude::*, 9 9 }; 10 - use core::ops::{self, Deref, DerefMut, Index}; 10 + use core::{ 11 + marker::PhantomData, 12 + ops::{self, Deref, DerefMut, Index}, 13 + }; 11 14 12 15 /// Byte string without UTF-8 validity guarantee. 13 16 #[repr(transparent)] ··· 828 825 /// Allows formatting of [`fmt::Arguments`] into a raw buffer. 829 826 /// 830 827 /// Fails if callers attempt to write more than will fit in the buffer. 831 - pub(crate) struct Formatter(RawFormatter); 828 + pub(crate) struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>); 832 829 833 - impl Formatter { 830 + impl Formatter<'_> { 834 831 /// Creates a new instance of [`Formatter`] with the given buffer. 835 832 /// 836 833 /// # Safety ··· 839 836 /// for the lifetime of the returned [`Formatter`]. 840 837 pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { 841 838 // SAFETY: The safety requirements of this function satisfy those of the callee. 842 - Self(unsafe { RawFormatter::from_buffer(buf, len) }) 839 + Self(unsafe { RawFormatter::from_buffer(buf, len) }, PhantomData) 840 + } 841 + 842 + /// Create a new [`Self`] instance. 843 + #[expect(dead_code)] 844 + pub(crate) fn new(buffer: &mut [u8]) -> Self { 845 + // SAFETY: `buffer` is valid for writes for the entire length for 846 + // the lifetime of `Self`. 847 + unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) } 843 848 } 844 849 } 845 850 846 - impl Deref for Formatter { 851 + impl Deref for Formatter<'_> { 847 852 type Target = RawFormatter; 848 853 849 854 fn deref(&self) -> &Self::Target { ··· 859 848 } 860 849 } 861 850 862 - impl fmt::Write for Formatter { 851 + impl fmt::Write for Formatter<'_> { 863 852 fn write_str(&mut self, s: &str) -> fmt::Result { 864 853 self.0.write_str(s)?; 865 854