Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1e8098b

Browse files
committed
Size optimize int formatting
1 parenta74509c commit1e8098b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎core/src/fmt/num.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
212212

213213
macro_rules! impl_Display{
214214
($($t:ident),*as $u:ident via $conv_fn:ident named $name:ident) =>{
215+
#[cfg(not(feature ="optimize_for_size"))]
215216
fn $name(mut n: $u, is_nonnegative:bool, f:&mut fmt::Formatter<'_>) -> fmt::Result{
216217
// 2^128 is about 3*10^38, so 39 gives an extra byte of space
217218
letmut buf =[MaybeUninit::<u8>::uninit();39];
@@ -277,6 +278,38 @@ macro_rules! impl_Display {
277278
f.pad_integral(is_nonnegative,"", buf_slice)
278279
}
279280

281+
#[cfg(feature ="optimize_for_size")]
282+
fn $name(mut n: $u, is_nonnegative:bool, f:&mut fmt::Formatter<'_>) -> fmt::Result{
283+
// 2^128 is about 3*10^38, so 39 gives an extra byte of space
284+
letmut buf =[MaybeUninit::<u8>::uninit();39];
285+
letmut curr = buf.len();
286+
let buf_ptr =MaybeUninit::slice_as_mut_ptr(&mut buf);
287+
288+
// SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning
289+
// `curr == buf.len() == 39 > log(n)` since `n < 2^128 < 10^39`, and at
290+
// each step this is kept the same as `n` is divided. Since `n` is always
291+
// non-negative, this means that `curr > 0` so `buf_ptr[curr..curr + 1]`
292+
// is safe to access.
293+
unsafe{
294+
loop{
295+
curr -=1;
296+
buf_ptr.add(curr).write((n %10)asu8 +b'0');
297+
n /=10;
298+
299+
if n ==0{
300+
break;
301+
}
302+
}
303+
}
304+
305+
// SAFETY: `curr` > 0 (since we made `buf` large enough), and all the chars are valid UTF-8
306+
let buf_slice =unsafe{
307+
str::from_utf8_unchecked(
308+
slice::from_raw_parts(buf_ptr.add(curr), buf.len() - curr))
309+
};
310+
f.pad_integral(is_nonnegative,"", buf_slice)
311+
}
312+
280313
$(#[stable(feature ="rust1", since ="1.0.0")]
281314
impl fmt::Displayfor $t{
282315
#[allow(unused_comparisons)]

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp