Functionality for int_format_into
for integer types by madhav-madhusoodanan · Pull Request #138338 · rust-lang/rust (original) (raw)
as mentioned on the ACP and listed as an unresolved issue, I think NumBuffer
should have a generic parameter for the type of integer being formatted (we could extend this to support floats later), so when we add future types like u8192
you don't have to have a huge buffer for u32
even though u8192
needs a huge buffer.
#[unstable(...)] // impl details
/// Safety: Buffer
must be [MaybeUninit<u8>; N]
where N
is big enough to fit any value of Self
when formatted.
pub unsafe trait NumBufferTrait {
type Buffer: AsMut<[MaybeUninit]> + AsRef<[MaybeUninit]> + 'static + Sync + Send;
const UNINIT_BUFFER: Self::Buffer;
}
// impl NumBufferTrait for u8, i8, u16, i16, ...
pub struct NumBuffer<T: NumBufferTrait> { contents: T::Buffer, }
impl<T: NumBufferTrait> NumBuffer { pub const fn new() -> Self { Self { contents: T::UNINIT_BUFFER } }
pub fn len(&self) -> usize {
self.contents.as_ref().len()
}
pub(crate) unsafe fn extract<I>(&self, index: I) -> &I::Output
where
I: SliceIndex<[MaybeUninit<u8>]>,
{
// SAFETY: `index` is bound-checked by the caller.
unsafe { self.contents.as_ref().get_unchecked(index) }
}
#[cfg(feature = "optimize_for_size")]
pub(crate) fn extract_start_mut_ptr(buf: &mut Self) -> *mut u8 {
MaybeUninit::slice_as_mut_ptr(buf.contents.as_mut())
}
pub(crate) unsafe fn write(&mut self, offset: usize, data: u8) {
self.contents.as_mut()[offset].write(data);
}
}