Skip to content

Commit d247480

Browse files
Added functionality for int_format_into
1 parent 2c6a12e commit d247480

File tree

2 files changed

+153
-0
lines changed

2 files changed

+153
-0
lines changed

library/core/src/num/int_format.rs

+148
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
use crate::mem::MaybeUninit;
2+
use crate::{slice, str};
3+
4+
/// A minimal buffer implementation containing elements of type
5+
/// `MaybeUninit::<u8>`.
6+
pub struct NumBuffer<const N: usize> {
7+
pub contents: [MaybeUninit::<u8>; N]
8+
}
9+
10+
impl<const N: usize> NumBuffer<N> {
11+
fn new() -> NumBuffer<N> {
12+
NumBuffer {
13+
contents: [MaybeUninit::<u8>::uninit(); N]
14+
}
15+
}
16+
}
17+
18+
// 2 digit decimal look up table
19+
static DEC_DIGITS_LUT: &[u8; 200] = b"\
20+
0001020304050607080910111213141516171819\
21+
2021222324252627282930313233343536373839\
22+
4041424344454647484950515253545556575859\
23+
6061626364656667686970717273747576777879\
24+
8081828384858687888990919293949596979899";
25+
26+
static NEGATIVE_SIGN = &[u8; 1] = b"-";
27+
28+
macro_rules! int_impl_format_into {
29+
($($T:ident)*) => {
30+
$(
31+
#[unstable(feature = "int_format_into", issue = "138215")]
32+
impl $T {
33+
/// Allows users to write an integer (in signed decimal format) into a variable `buf` of
34+
/// type [`NumBuffer`] that is passed by the caller by mutable reference.
35+
///
36+
/// This function panics if `buf` does not have enough size to store
37+
/// the signed decimal version of the number.
38+
///
39+
/// # Examples
40+
/// ```
41+
#[doc = concat!("let n = 32", stringify!($T), ";")]
42+
/// let mut buf = NumBuffer::<3>::new();
43+
///
44+
/// assert_eq!(n.format_into(&mut buf), "32");
45+
/// ```
46+
///
47+
fn format_into(self, buf: &mut NumBuffer) -> &str {
48+
// counting space for negative sign too, if `self` is negative
49+
let sign_offset = if self < 0 {1} else {0};
50+
let decimal_string_size: usize = self.ilog(10) as usize + 1 + sign_offset;
51+
52+
// `buf` must have minimum size to store the decimal string version.
53+
if buf.contents.len() < decimal_string_size {
54+
panic!("Not enough buffer size to format into!");
55+
}
56+
57+
// Count the number of bytes in `buf` that are not initialized.
58+
let mut offset = buf.contents.len();
59+
// Consume the least-significant decimals from a working copy.
60+
let mut remain = self;
61+
62+
// Format per four digits from the lookup table.
63+
// Four digits need a 16-bit $unsigned or wider.
64+
while size_of::<Self>() > 1 && remain > 999.try_into().expect("branch is not hit for types that cannot fit 999 (u8)") {
65+
// SAFETY: All of the decimals fit in buf, since it now is size-checked
66+
// and the while condition ensures at least 4 more decimals.
67+
unsafe { core::hint::assert_unchecked(offset >= 4) }
68+
// SAFETY: The offset counts down from its initial buf.contents.len()
69+
// without underflow due to the previous precondition.
70+
unsafe { core::hint::assert_unchecked(offset <= buf.contents.len()) }
71+
offset -= 4;
72+
73+
// pull two pairs
74+
let scale: Self = 1_00_00.try_into().expect("branch is not hit for types that cannot fit 1E4 (u8)");
75+
let quad = remain % scale;
76+
remain /= scale;
77+
let pair1 = (quad / 100) as usize;
78+
let pair2 = (quad % 100) as usize;
79+
buf.contents[offset + 0].write(DEC_DIGITS_LUT[pair1 * 2 + 0]);
80+
buf.contents[offset + 1].write(DEC_DIGITS_LUT[pair1 * 2 + 1]);
81+
buf.contents[offset + 2].write(DEC_DIGITS_LUT[pair2 * 2 + 0]);
82+
buf.contents[offset + 3].write(DEC_DIGITS_LUT[pair2 * 2 + 1]);
83+
}
84+
85+
// Format per two digits from the lookup table.
86+
if remain > 9 {
87+
// SAFETY: All of the decimals fit in buf, since it now is size-checked
88+
// and the while condition ensures at least 2 more decimals.
89+
unsafe { core::hint::assert_unchecked(offset >= 2) }
90+
// SAFETY: The offset counts down from its initial buf.contents.len()
91+
// without underflow due to the previous precondition.
92+
unsafe { core::hint::assert_unchecked(offset <= buf.contents.len()) }
93+
offset -= 2;
94+
95+
let pair = (remain % 100) as usize;
96+
remain /= 100;
97+
buf.contents[offset + 0].write(DEC_DIGITS_LUT[pair * 2 + 0]);
98+
buf.contents[offset + 1].write(DEC_DIGITS_LUT[pair * 2 + 1]);
99+
}
100+
101+
// Format the last remaining digit, if any.
102+
if remain != 0 || self == 0 {
103+
// SAFETY: All of the decimals fit in buf, since it now is size-checked
104+
// and the if condition ensures (at least) 1 more decimals.
105+
unsafe { core::hint::assert_unchecked(offset >= 1) }
106+
// SAFETY: The offset counts down from its initial buf.contents.len()
107+
// without underflow due to the previous precondition.
108+
unsafe { core::hint::assert_unchecked(offset <= buf.contents.len()) }
109+
offset -= 1;
110+
111+
// Either the compiler sees that remain < 10, or it prevents
112+
// a boundary check up next.
113+
let last = (remain & 15) as usize;
114+
buf.contents[offset].write(DEC_DIGITS_LUT[last * 2 + 1]);
115+
// not used: remain = 0;
116+
}
117+
118+
if self < 0 {
119+
// SAFETY: All of the decimals (with the sign) fit in buf, since it now is size-checked
120+
// and the if condition ensures (at least) that the sign can be added.
121+
unsafe { core::hint::assert_unchecked(offset >= 1) }
122+
123+
// SAFETY: The offset counts down from its initial buf.contents.len()
124+
// without underflow due to the previous precondition.
125+
unsafe { core::hint::assert_unchecked(offset <= buf.contents.len()) }
126+
127+
// Setting sign for the negative number
128+
offset -= 1;
129+
buf.contents.[offset].write(NEGATIVE_SIGN[0])
130+
}
131+
132+
// SAFETY: All buf content since offset is set.
133+
let written = unsafe { buf.contents.get_unchecked(offset..) };
134+
135+
// SAFETY: Writes use ASCII from the lookup table
136+
// (and `NEGATIVE_SIGN` in case of negative numbers) exclusively.
137+
let as_str = unsafe {
138+
str::from_utf8_unchecked(slice::from_raw_parts(
139+
MaybeUninit::slice_as_ptr(written),
140+
written.len(),
141+
))
142+
};
143+
as_str
144+
}
145+
}
146+
)*
147+
};
148+
}

library/core/src/num/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ pub mod fmt;
4242
mod int_macros; // import int_impl!
4343
#[macro_use]
4444
mod uint_macros; // import uint_impl!
45+
#[macro_use]
46+
mod int_format; // import int_impl_format_into!
4547

4648
mod error;
4749
mod int_log10;
@@ -1602,3 +1604,6 @@ macro_rules! from_str_int_impl {
16021604

16031605
from_str_int_impl! { signed isize i8 i16 i32 i64 i128 }
16041606
from_str_int_impl! { unsigned usize u8 u16 u32 u64 u128 }
1607+
1608+
int_impl_format_into! { i8 i16 i32 i64 i128 isize }
1609+
int_impl_format_into! { u8 u16 u32 u64 u128 usize }

0 commit comments

Comments
 (0)