11//! Integer and floating-point number formatting
22
3+ use crate :: fmt:: NumBuffer ;
34use crate :: mem:: MaybeUninit ;
45use crate :: num:: fmt as numfmt;
56use crate :: ops:: { Div , Rem , Sub } ;
@@ -199,6 +200,20 @@ 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
206+ ///
207+ /// `buf` content starting from `offset` index MUST BE initialized and MUST BE ascii
208+ /// characters.
209+ unsafe fn slice_buffer_to_str ( buf : & [ MaybeUninit < u8 > ] , offset : usize ) -> & str {
210+ // SAFETY: `offset` is always included between 0 and `buf`'s length.
211+ let written = unsafe { buf. get_unchecked ( offset..) } ;
212+ // SAFETY: (`assume_init_ref`) All buf content since offset is set.
213+ // SAFETY: (`from_utf8_unchecked`) Writes use ASCII from the lookup table exclusively.
214+ unsafe { str:: from_utf8_unchecked ( written. assume_init_ref ( ) ) }
215+ }
216+
202217macro_rules! impl_Display {
203218 ( $( $signed: ident, $unsigned: ident, ) * ; as $u: ident via $conv_fn: ident named $gen_name: ident) => {
204219
@@ -248,6 +263,13 @@ macro_rules! impl_Display {
248263 issue = "none"
249264 ) ]
250265 pub fn _fmt<' a>( self , buf: & ' a mut [ MaybeUninit :: <u8 >] ) -> & ' a str {
266+ // SAFETY: `buf` will always be big enough to contain all digits.
267+ let offset = unsafe { self . _fmt_inner( buf) } ;
268+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
269+ unsafe { slice_buffer_to_str( buf, offset) }
270+ }
271+
272+ unsafe fn _fmt_inner( self , buf: & mut [ MaybeUninit :: <u8 >] ) -> usize {
251273 // Count the number of bytes in buf that are not initialized.
252274 let mut offset = buf. len( ) ;
253275 // Consume the least-significant decimals from a working copy.
@@ -309,24 +331,97 @@ macro_rules! impl_Display {
309331 // not used: remain = 0;
310332 }
311333
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.
334+ offset
335+ }
336+ }
337+
338+ impl $signed {
339+ /// Allows users to write an integer (in signed decimal format) into a variable `buf` of
340+ /// type [`NumBuffer`] that is passed by the caller by mutable reference.
341+ ///
342+ /// # Examples
343+ ///
344+ /// ```
345+ /// #![feature(int_format_into)]
346+ /// use core::fmt::NumBuffer;
347+ ///
348+ #[ doc = concat!( "let n = 0" , stringify!( $signed) , ";" ) ]
349+ /// let mut buf = NumBuffer::new();
350+ /// assert_eq!(n.format_into(&mut buf), "0");
351+ ///
352+ #[ doc = concat!( "let n1 = 32" , stringify!( $signed) , ";" ) ]
353+ /// assert_eq!(n1.format_into(&mut buf), "32");
354+ ///
355+ #[ doc = concat!( "let n2 = " , stringify!( $signed:: MAX ) , ";" ) ]
356+ #[ doc = concat!( "assert_eq!(n2.format_into(&mut buf), " , stringify!( $signed:: MAX ) , ".to_string());" ) ]
357+ /// ```
358+ #[ unstable( feature = "int_format_into" , issue = "138215" ) ]
359+ pub fn format_into( self , buf: & mut NumBuffer <Self >) -> & str {
360+ let mut offset;
361+
362+ #[ cfg( not( feature = "optimize_for_size" ) ) ]
363+ // SAFETY: `buf` will always be big enough to contain all digits.
315364 unsafe {
316- str :: from_utf8_unchecked( slice:: from_raw_parts(
317- MaybeUninit :: slice_as_ptr( written) ,
318- written. len( ) ,
319- ) )
365+ offset = self . unsigned_abs( ) . _fmt_inner( & mut buf. buf) ;
320366 }
367+ #[ cfg( feature = "optimize_for_size" ) ]
368+ {
369+ offset = _inner_slow_integer_to_str( self . unsigned_abs( ) . $conv_fn( ) , & mut buf. buf) ;
370+ }
371+ // Only difference between signed and unsigned are these 4 lines.
372+ if self < 0 {
373+ offset -= 1 ;
374+ buf. buf[ offset] . write( b'-' ) ;
375+ }
376+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
377+ unsafe { slice_buffer_to_str( & buf. buf, offset) }
321378 }
322- } ) *
379+ }
380+
381+ impl $unsigned {
382+ /// Allows users to write an integer (in signed decimal format) into a variable `buf` of
383+ /// type [`NumBuffer`] that is passed by the caller by mutable reference.
384+ ///
385+ /// # Examples
386+ ///
387+ /// ```
388+ /// #![feature(int_format_into)]
389+ /// use core::fmt::NumBuffer;
390+ ///
391+ #[ doc = concat!( "let n = 0" , stringify!( $unsigned) , ";" ) ]
392+ /// let mut buf = NumBuffer::new();
393+ /// assert_eq!(n.format_into(&mut buf), "0");
394+ ///
395+ #[ doc = concat!( "let n1 = 32" , stringify!( $unsigned) , ";" ) ]
396+ /// assert_eq!(n1.format_into(&mut buf), "32");
397+ ///
398+ #[ doc = concat!( "let n2 = " , stringify!( $unsigned:: MAX ) , ";" ) ]
399+ #[ doc = concat!( "assert_eq!(n2.format_into(&mut buf), " , stringify!( $unsigned:: MAX ) , ".to_string());" ) ]
400+ /// ```
401+ #[ unstable( feature = "int_format_into" , issue = "138215" ) ]
402+ pub fn format_into( self , buf: & mut NumBuffer <Self >) -> & str {
403+ let offset;
404+
405+ #[ cfg( not( feature = "optimize_for_size" ) ) ]
406+ // SAFETY: `buf` will always be big enough to contain all digits.
407+ unsafe {
408+ offset = self . _fmt_inner( & mut buf. buf) ;
409+ }
410+ #[ cfg( feature = "optimize_for_size" ) ]
411+ {
412+ offset = _inner_slow_integer_to_str( self . $conv_fn( ) , & mut buf. buf) ;
413+ }
414+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
415+ unsafe { slice_buffer_to_str( & buf. buf, offset) }
416+ }
417+ }
418+
419+
420+ ) *
323421
324422 #[ 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 . ilog10( ) 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) ;
423+ fn _inner_slow_integer_to_str( mut n: $u, buf: & mut [ MaybeUninit :: <u8 >] ) -> usize {
424+ let mut curr = buf. len( ) ;
330425
331426 // SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning
332427 // `curr == buf.len() == 39 > log(n)` since `n < 2^128 < 10^39`, and at
@@ -336,20 +431,25 @@ macro_rules! impl_Display {
336431 unsafe {
337432 loop {
338433 curr -= 1 ;
339- buf_ptr . add ( curr) . write( ( n % 10 ) as u8 + b'0' ) ;
434+ buf [ curr] . write( ( n % 10 ) as u8 + b'0' ) ;
340435 n /= 10 ;
341436
342437 if n == 0 {
343438 break ;
344439 }
345440 }
346441 }
442+ cur
443+ }
347444
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- } ;
445+ #[ cfg( feature = "optimize_for_size" ) ]
446+ fn $gen_name( n: $u, is_nonnegative: bool , f: & mut fmt:: Formatter <' _>) -> fmt:: Result {
447+ const MAX_DEC_N : usize = $u:: MAX . ilog( 10 ) as usize + 1 ;
448+ let mut buf = [ MaybeUninit :: <u8 >:: uninit( ) ; MAX_DEC_N ] ;
449+
450+ let offset = _inner_slow_integer_to_str( n, & mut buf) ;
451+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
452+ let buf_slice = unsafe { slice_buffer_to_str( & buf, offset) } ;
353453 f. pad_integral( is_nonnegative, "" , buf_slice)
354454 }
355455 } ;
@@ -598,12 +698,20 @@ impl u128 {
598698 issue = "none"
599699 ) ]
600700 pub fn _fmt < ' a > ( self , buf : & ' a mut [ MaybeUninit < u8 > ] ) -> & ' a str {
701+ // SAFETY: `buf` will always be big enough to contain all digits.
702+ let offset = unsafe { self . _fmt_inner ( buf) } ;
703+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
704+ unsafe { slice_buffer_to_str ( buf, offset) }
705+ }
706+
707+ unsafe fn _fmt_inner ( self , buf : & mut [ MaybeUninit < u8 > ] ) -> usize {
601708 // Optimize common-case zero, which would also need special treatment due to
602709 // its "leading" zero.
603710 if self == 0 {
604- return "0" ;
711+ let offset = buf. len ( ) - 1 ;
712+ buf[ offset] . write ( b'0' ) ;
713+ return offset;
605714 }
606-
607715 // Take the 16 least-significant decimals.
608716 let ( quot_1e16, mod_1e16) = div_rem_1e16 ( self ) ;
609717 let ( mut remain, mut offset) = if quot_1e16 == 0 {
@@ -677,16 +785,86 @@ impl u128 {
677785 buf[ offset] . write ( DEC_DIGITS_LUT [ last * 2 + 1 ] ) ;
678786 // not used: remain = 0;
679787 }
788+ offset
789+ }
680790
681- // SAFETY: All buf content since offset is set.
682- let written = unsafe { buf. get_unchecked ( offset..) } ;
683- // SAFETY: Writes use ASCII from the lookup table exclusively.
684- unsafe {
685- str:: from_utf8_unchecked ( slice:: from_raw_parts (
686- MaybeUninit :: slice_as_ptr ( written) ,
687- written. len ( ) ,
688- ) )
791+ /// Allows users to write an integer (in signed decimal format) into a variable `buf` of
792+ /// type [`NumBuffer`] that is passed by the caller by mutable reference.
793+ ///
794+ /// # Examples
795+ ///
796+ /// ```
797+ /// #![feature(int_format_into)]
798+ /// use core::fmt::NumBuffer;
799+ ///
800+ /// let n = 0u128;
801+ /// let mut buf = NumBuffer::new();
802+ /// assert_eq!(n.format_into(&mut buf), "0");
803+ ///
804+ /// let n1 = 32u128;
805+ /// let mut buf1 = NumBuffer::new();
806+ /// assert_eq!(n1.format_into(&mut buf1), "32");
807+ ///
808+ /// let n2 = u128::MAX;
809+ /// let mut buf2 = NumBuffer::new();
810+ /// assert_eq!(n2.format_into(&mut buf2), u128::MAX.to_string());
811+ /// ```
812+ #[ unstable( feature = "int_format_into" , issue = "138215" ) ]
813+ pub fn format_into ( self , buf : & mut NumBuffer < Self > ) -> & str {
814+ let diff = buf. capacity ( ) - U128_MAX_DEC_N ;
815+ // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
816+ // for `fmt_u128_inner`.
817+ //
818+ // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
819+ // offset to ensure the number is correctly generated at the end of the buffer.
820+ // SAFETY: `diff` will always be between 0 and its initial value.
821+ unsafe { self . _fmt ( buf. buf . get_unchecked_mut ( diff..) ) }
822+ }
823+ }
824+
825+ impl i128 {
826+ /// Allows users to write an integer (in signed decimal format) into a variable `buf` of
827+ /// type [`NumBuffer`] that is passed by the caller by mutable reference.
828+ ///
829+ /// # Examples
830+ ///
831+ /// ```
832+ /// #![feature(int_format_into)]
833+ /// use core::fmt::NumBuffer;
834+ ///
835+ /// let n = 0i128;
836+ /// let mut buf = NumBuffer::new();
837+ /// assert_eq!(n.format_into(&mut buf), "0");
838+ ///
839+ /// let n1 = i128::MIN;
840+ /// assert_eq!(n1.format_into(&mut buf), i128::MIN.to_string());
841+ ///
842+ /// let n2 = i128::MAX;
843+ /// assert_eq!(n2.format_into(&mut buf), i128::MAX.to_string());
844+ /// ```
845+ #[ unstable( feature = "int_format_into" , issue = "138215" ) ]
846+ pub fn format_into ( self , buf : & mut NumBuffer < Self > ) -> & str {
847+ let diff = buf. capacity ( ) - U128_MAX_DEC_N ;
848+ // FIXME: Once const generics are better, use `NumberBufferTrait::BUF_SIZE` as generic const
849+ // for `fmt_u128_inner`.
850+ //
851+ // In the meantime, we have to use a slice starting at index 1 and add 1 to the returned
852+ // offset to ensure the number is correctly generated at the end of the buffer.
853+ let mut offset =
854+ // SAFETY: `buf` will always be big enough to contain all digits.
855+ unsafe { self . unsigned_abs ( ) . _fmt_inner ( buf. buf . get_unchecked_mut ( diff..) ) } ;
856+ // We put back the offset at the right position.
857+ offset += diff;
858+ // Only difference between signed and unsigned are these 4 lines.
859+ if self < 0 {
860+ offset -= 1 ;
861+ // SAFETY: `buf` will always be big enough to contain all digits plus the minus sign.
862+ unsafe {
863+ buf. buf . get_unchecked_mut ( offset) . write ( b'-' ) ;
864+ }
689865 }
866+ // SAFETY: Starting from `offset`, all elements of the slice have been set.
867+ unsafe { slice_buffer_to_str ( & buf. buf , offset) }
690868 }
691869}
692870
0 commit comments