Skip to content

Commit 7e8308c

Browse files
Implement int_format_into feature
1 parent d00435f commit 7e8308c

File tree

3 files changed

+266
-43
lines changed

3 files changed

+266
-43
lines changed

library/core/src/fmt/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ mod float;
1515
#[cfg(no_fp_fmt_parse)]
1616
mod nofloat;
1717
mod num;
18+
mod num_buffer;
1819
mod rt;
1920

2021
#[stable(feature = "fmt_flags_align", since = "1.28.0")]
@@ -33,6 +34,9 @@ pub enum Alignment {
3334
Center,
3435
}
3536

37+
#[unstable(feature = "int_format_into", issue = "138215")]
38+
pub use num_buffer::{NumBuffer, NumBufferTrait};
39+
3640
#[stable(feature = "debug_builders", since = "1.2.0")]
3741
pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
3842
#[unstable(feature = "debug_closure_helpers", issue = "117729")]

library/core/src/fmt/num.rs

Lines changed: 203 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Integer and floating-point number formatting
22
3+
use crate::fmt::NumBuffer;
34
use crate::mem::MaybeUninit;
45
use crate::num::fmt as numfmt;
56
use crate::ops::{Div, Rem, Sub};
@@ -199,6 +200,17 @@ static DEC_DIGITS_LUT: &[u8; 200] = b"\
199200
6061626364656667686970717273747576777879\
200201
8081828384858687888990919293949596979899";
201202

203+
/// This function converts a slice of ascii characters into a `&str` starting from `offset`.
204+
///
205+
/// Safety notes: `buf` content starting from `offset` index MUST BE initialized and MUST BE ascii
206+
/// characters.
207+
unsafe fn slice_buffer_to_str(buf: &[MaybeUninit<u8>], offset: usize) -> &str {
208+
// SAFETY: All buf content since offset is set.
209+
let written = unsafe { buf.get_unchecked(offset..) };
210+
// SAFETY: Writes use ASCII from the lookup table exclusively.
211+
unsafe { str::from_utf8_unchecked(written.assume_init_ref()) }
212+
}
213+
202214
macro_rules! impl_Display {
203215
($($signed:ident, $unsigned:ident,)* ; as $u:ident via $conv_fn:ident named $gen_name:ident) => {
204216

@@ -248,6 +260,12 @@ macro_rules! impl_Display {
248260
issue = "none"
249261
)]
250262
pub fn _fmt<'a>(self, buf: &'a mut [MaybeUninit::<u8>]) -> &'a str {
263+
let offset = self._fmt_inner(buf);
264+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
265+
unsafe { slice_buffer_to_str(buf, offset) }
266+
}
267+
268+
fn _fmt_inner(self, buf: &mut [MaybeUninit::<u8>]) -> usize {
251269
// Count the number of bytes in buf that are not initialized.
252270
let mut offset = buf.len();
253271
// Consume the least-significant decimals from a working copy.
@@ -309,24 +327,99 @@ macro_rules! impl_Display {
309327
// not used: remain = 0;
310328
}
311329

312-
// SAFETY: All buf content since offset is set.
313-
let written = unsafe { buf.get_unchecked(offset..) };
314-
// SAFETY: Writes use ASCII from the lookup table exclusively.
315-
unsafe {
316-
str::from_utf8_unchecked(slice::from_raw_parts(
317-
MaybeUninit::slice_as_ptr(written),
318-
written.len(),
319-
))
330+
offset
331+
}
332+
}
333+
334+
impl $signed {
335+
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
336+
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
337+
///
338+
/// # Examples
339+
///
340+
/// ```
341+
/// #![feature(int_format_into)]
342+
/// use core::fmt::NumBuffer;
343+
///
344+
#[doc = concat!("let n = 0", stringify!($signed), ";")]
345+
/// let mut buf = NumBuffer::new();
346+
/// assert_eq!(n.format_into(&mut buf), "0");
347+
///
348+
#[doc = concat!("let n1 = 32", stringify!($unsigned), ";")]
349+
/// let mut buf1 = NumBuffer::new();
350+
/// assert_eq!(n1.format_into(&mut buf1), "32");
351+
///
352+
#[doc = concat!("let n2 = ", stringify!($unsigned::MAX), ";")]
353+
/// let mut buf2 = NumBuffer::new();
354+
#[doc = concat!("assert_eq!(n2.format_into(&mut buf2), ", stringify!($unsigned::MAX), ".to_string());")]
355+
/// ```
356+
#[unstable(feature = "int_format_into", issue = "138215")]
357+
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
358+
let mut offset;
359+
360+
#[cfg(not(feature = "optimize_for_size"))]
361+
{
362+
offset = self.unsigned_abs()._fmt_inner(&mut buf.buf);
320363
}
364+
#[cfg(feature = "optimize_for_size")]
365+
{
366+
offset = _inner_slow_integer_to_str(self.unsigned_abs().$conv_fn(), &mut buf.buf);
367+
}
368+
// Only difference between signed and unsigned are these 4 lines.
369+
if self < 0 {
370+
offset -= 1;
371+
buf.buf[offset].write(b'-');
372+
}
373+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
374+
unsafe { slice_buffer_to_str(&buf.buf, offset) }
321375
}
322-
})*
376+
}
377+
378+
impl $unsigned {
379+
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
380+
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
381+
///
382+
/// # Examples
383+
///
384+
/// ```
385+
/// #![feature(int_format_into)]
386+
/// use core::fmt::NumBuffer;
387+
///
388+
#[doc = concat!("let n = 0", stringify!($signed), ";")]
389+
/// let mut buf = NumBuffer::new();
390+
/// assert_eq!(n.format_into(&mut buf), "0");
391+
///
392+
#[doc = concat!("let n1 = 32", stringify!($unsigned), ";")]
393+
/// let mut buf1 = NumBuffer::new();
394+
/// assert_eq!(n1.format_into(&mut buf1), "32");
395+
///
396+
#[doc = concat!("let n2 = ", stringify!($unsigned::MAX), ";")]
397+
/// let mut buf2 = NumBuffer::new();
398+
#[doc = concat!("assert_eq!(n2.format_into(&mut buf2), ", stringify!($unsigned::MAX), ".to_string());")]
399+
/// ```
400+
#[unstable(feature = "int_format_into", issue = "138215")]
401+
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
402+
let offset;
403+
404+
#[cfg(not(feature = "optimize_for_size"))]
405+
{
406+
offset = self._fmt_inner(&mut buf.buf);
407+
}
408+
#[cfg(feature = "optimize_for_size")]
409+
{
410+
offset = _inner_slow_integer_to_str(self.$conv_fn(), &mut buf.buf);
411+
}
412+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
413+
unsafe { slice_buffer_to_str(&buf.buf, offset) }
414+
}
415+
}
416+
417+
418+
)*
323419

324420
#[cfg(feature = "optimize_for_size")]
325-
fn $gen_name(mut n: $u, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326-
const MAX_DEC_N: usize = $u::MAX.ilog(10) as usize + 1;
327-
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
328-
let mut curr = MAX_DEC_N;
329-
let buf_ptr = MaybeUninit::slice_as_mut_ptr(&mut buf);
421+
fn _inner_slow_integer_to_str(mut n: $u, buf: &mut [MaybeUninit::<u8>]) -> usize {
422+
let mut curr = buf.len();
330423

331424
// SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning
332425
// `curr == buf.len() == 39 > log(n)` since `n < 2^128 < 10^39`, and at
@@ -336,20 +429,25 @@ macro_rules! impl_Display {
336429
unsafe {
337430
loop {
338431
curr -= 1;
339-
buf_ptr.add(curr).write((n % 10) as u8 + b'0');
432+
buf[curr].write((n % 10) as u8 + b'0');
340433
n /= 10;
341434

342435
if n == 0 {
343436
break;
344437
}
345438
}
346439
}
440+
cur
441+
}
347442

348-
// SAFETY: `curr` > 0 (since we made `buf` large enough), and all the chars are valid UTF-8
349-
let buf_slice = unsafe {
350-
str::from_utf8_unchecked(
351-
slice::from_raw_parts(buf_ptr.add(curr), buf.len() - curr))
352-
};
443+
#[cfg(feature = "optimize_for_size")]
444+
fn $gen_name(n: $u, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445+
const MAX_DEC_N: usize = $u::MAX.ilog(10) as usize + 1;
446+
let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N];
447+
448+
let offset = _inner_slow_integer_to_str(n, &mut buf);
449+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
450+
let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) };
353451
f.pad_integral(is_nonnegative, "", buf_slice)
354452
}
355453
};
@@ -566,7 +664,7 @@ mod imp {
566664
impl_Exp!(i128, u128 as u128 via to_u128 named exp_u128);
567665

568666
/// Helper function for writing a u64 into `buf` going from last to first, with `curr`.
569-
fn parse_u64_into<const N: usize>(mut n: u64, buf: &mut [MaybeUninit<u8>; N], curr: &mut usize) {
667+
fn parse_u64_into(mut n: u64, buf: &mut [MaybeUninit<u8>], curr: &mut usize) {
570668
let buf_ptr = MaybeUninit::slice_as_mut_ptr(buf);
571669
let lut_ptr = DEC_DIGITS_LUT.as_ptr();
572670
assert!(*curr > 19);
@@ -673,58 +771,120 @@ impl fmt::Display for i128 {
673771
}
674772
}
675773

774+
impl u128 {
775+
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
776+
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
777+
///
778+
/// # Examples
779+
///
780+
/// ```
781+
/// #![feature(int_format_into)]
782+
/// use core::fmt::NumBuffer;
783+
///
784+
/// let n = 0u128;
785+
/// let mut buf = NumBuffer::new();
786+
/// assert_eq!(n.format_into(&mut buf), "0");
787+
///
788+
/// let n1 = 32u128;
789+
/// let mut buf1 = NumBuffer::new();
790+
/// assert_eq!(n1.format_into(&mut buf1), "32");
791+
///
792+
/// let n2 = u128::MAX;
793+
/// let mut buf2 = NumBuffer::new();
794+
/// assert_eq!(n2.format_into(&mut buf2), u128::MAX.to_string());
795+
/// ```
796+
#[unstable(feature = "int_format_into", issue = "138215")]
797+
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
798+
let offset = fmt_u128_inner(self, &mut buf.buf);
799+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
800+
unsafe { slice_buffer_to_str(&buf.buf, offset) }
801+
}
802+
}
803+
804+
impl i128 {
805+
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
806+
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
807+
///
808+
/// # Examples
809+
///
810+
/// ```
811+
/// #![feature(int_format_into)]
812+
/// use core::fmt::NumBuffer;
813+
///
814+
/// let n = 0i128;
815+
/// let mut buf = NumBuffer::new();
816+
/// assert_eq!(n.format_into(&mut buf), "0");
817+
///
818+
/// let n1 = 32i128;
819+
/// let mut buf1 = NumBuffer::new();
820+
/// assert_eq!(n1.format_into(&mut buf1), "32");
821+
///
822+
/// let n2 = i128::MAX;
823+
/// let mut buf2 = NumBuffer::new();
824+
/// assert_eq!(n2.format_into(&mut buf2), i128::MAX.to_string());
825+
/// ```
826+
#[unstable(feature = "int_format_into", issue = "138215")]
827+
pub fn format_into(self, buf: &mut NumBuffer<Self>) -> &str {
828+
let mut offset = fmt_u128_inner(self.unsigned_abs(), &mut buf.buf);
829+
// Only difference between signed and unsigned are these 4 lines.
830+
if self < 0 {
831+
offset -= 1;
832+
buf.buf[offset].write(b'-');
833+
}
834+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
835+
unsafe { slice_buffer_to_str(&buf.buf, offset) }
836+
}
837+
}
838+
676839
/// Specialized optimization for u128. Instead of taking two items at a time, it splits
677840
/// into at most 2 u64s, and then chunks by 10e16, 10e8, 10e4, 10e2, and then 10e1.
678841
/// It also has to handle 1 last item, as 10^40 > 2^128 > 10^39, whereas
679842
/// 10^20 > 2^64 > 10^19.
680-
fn fmt_u128(n: u128, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
681-
// 2^128 is about 3*10^38, so 39 gives an extra byte of space
682-
let mut buf = [MaybeUninit::<u8>::uninit(); 39];
843+
///
844+
/// IMPORTANT: `buf` length MUST BE at least 39.
845+
fn fmt_u128_inner(n: u128, buf: &mut [MaybeUninit<u8>]) -> usize {
683846
let mut curr = buf.len();
684-
685847
let (n, rem) = udiv_1e19(n);
686-
parse_u64_into(rem, &mut buf, &mut curr);
848+
parse_u64_into(rem, buf, &mut curr);
687849

688850
if n != 0 {
689851
// 0 pad up to point
690852
let target = buf.len() - 19;
691853
// SAFETY: Guaranteed that we wrote at most 19 bytes, and there must be space
692-
// remaining since it has length 39
854+
// remaining since it has length of at least 39
693855
unsafe {
694-
ptr::write_bytes(
695-
MaybeUninit::slice_as_mut_ptr(&mut buf).add(target),
696-
b'0',
697-
curr - target,
698-
);
856+
ptr::write_bytes(MaybeUninit::slice_as_mut_ptr(buf).add(target), b'0', curr - target);
699857
}
700858
curr = target;
701859

702860
let (n, rem) = udiv_1e19(n);
703-
parse_u64_into(rem, &mut buf, &mut curr);
861+
parse_u64_into(rem, buf, &mut curr);
704862
// Should this following branch be annotated with unlikely?
705863
if n != 0 {
706864
let target = buf.len() - 38;
707865
// The raw `buf_ptr` pointer is only valid until `buf` is used the next time,
708866
// buf `buf` is not used in this scope so we are good.
709-
let buf_ptr = MaybeUninit::slice_as_mut_ptr(&mut buf);
867+
let buf_ptr = MaybeUninit::slice_as_mut_ptr(buf);
710868
// SAFETY: At this point we wrote at most 38 bytes, pad up to that point,
711-
// There can only be at most 1 digit remaining.
869+
// There can only be at most 1 digit remaining (+ another one if this is actually
870+
// converting a `i128` type which has a bigger size).
712871
unsafe {
713872
ptr::write_bytes(buf_ptr.add(target), b'0', curr - target);
714873
curr = target - 1;
715874
*buf_ptr.add(curr) = (n as u8) + b'0';
716875
}
717876
}
718877
}
878+
curr
879+
}
719880

720-
// SAFETY: `curr` > 0 (since we made `buf` large enough), and all the chars are valid
721-
// UTF-8 since `DEC_DIGITS_LUT` is
722-
let buf_slice = unsafe {
723-
str::from_utf8_unchecked(slice::from_raw_parts(
724-
MaybeUninit::slice_as_mut_ptr(&mut buf).add(curr),
725-
buf.len() - curr,
726-
))
727-
};
881+
fn fmt_u128(n: u128, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882+
// 2^128 is about 3*10^38, so 39 gives an extra byte of space
883+
let mut buf = [MaybeUninit::<u8>::uninit(); 39];
884+
885+
let offset = fmt_u128_inner(n, &mut buf);
886+
// SAFETY: Starting from `offset`, all elements of the slice have been set.
887+
let buf_slice = unsafe { slice_buffer_to_str(&buf, offset) };
728888
f.pad_integral(is_nonnegative, "", buf_slice)
729889
}
730890

0 commit comments

Comments
 (0)