const-itoa 0.1.0

Fast integer primitive to string conversion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! [![github]](https://github.com/dtolnay/itoa) [![crates-io]](https://crates.io/crates/itoa) [![docs-rs]](https://docs.rs/itoa)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! This crate provides a fast conversion of integer primitives to decimal
//! strings. The implementation comes straight from [libcore] but avoids the
//! performance penalty of going through [`core::fmt::Formatter`].
//!
//! See also [`ryu`] for printing floating point primitives.
//!
//! [libcore]: https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254
//! [`ryu`]: https://github.com/dtolnay/ryu
//!
//! # Example
//!
//! ```
//! fn main() {
//!     let mut buffer = const_itoa::Buffer::new();
//!     let printed = buffer.format(128u64);
//!     assert_eq!(printed, "128");
//! }
//! ```
//!
//! # Performance (lower is better)
//!
//! ![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png)

#![doc(html_root_url = "https://docs.rs/itoa/1.0.15")]
#![no_std]
#![allow(
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::expl_impl_clone_on_copy,
    clippy::must_use_candidate,
    clippy::needless_doctest_main,
    clippy::unreadable_literal
)]

mod udiv128;

use core::hint;
use core::mem::MaybeUninit;
use core::{ptr, slice, str};
#[cfg(feature = "no-panic")]
use no_panic::no_panic;

/// A correctly sized stack allocation for the formatted integer to be written
/// into.
///
/// # Example
///
/// ```
/// let mut buffer = const_itoa::Buffer::new();
/// let printed = buffer.format(1234);
/// assert_eq!(printed, "1234");
/// ```
pub struct Buffer {
    bytes: [MaybeUninit<u8>; i128::MAX_STR_LEN],
}

impl Default for Buffer {
    #[inline]
    fn default() -> Buffer {
        Buffer::new()
    }
}

impl Copy for Buffer {}

#[allow(clippy::non_canonical_clone_impl)]
impl Clone for Buffer {
    #[inline]
    fn clone(&self) -> Self {
        Buffer::new()
    }
}

impl Buffer {
    /// This is a cheap operation; you don't need to worry about reusing buffers
    /// for efficiency.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub const fn new() -> Buffer {
        let bytes = [MaybeUninit::<u8>::uninit(); i128::MAX_STR_LEN];
        Buffer { bytes }
    }

    /// Print an integer into this buffer and return a reference to its string
    /// representation within the buffer.
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn format<I: Integer>(&mut self, i: I) -> &str {
        #[expect(clippy::ptr_as_ptr)]
        #[expect(clippy::borrow_as_ptr)]
        let string = i.write(unsafe {
            &mut *(&mut self.bytes as *mut [MaybeUninit<u8>; i128::MAX_STR_LEN]
                as *mut <I as private::Sealed>::Buffer)
        });
        if string.len() > I::MAX_STR_LEN {
            unsafe { hint::unreachable_unchecked() };
        }
        string
    }
}

/// An integer that can be written into an [`const_itoa::Buffer`][Buffer].
///
/// This trait is sealed and cannot be implemented for types outside of itoa.
pub trait Integer: private::Sealed {
    /// The maximum length of string that formatting an integer of this type can
    /// produce on the current target platform.
    const MAX_STR_LEN: usize;
}

/// Const version of `T: Integer`
struct ConstInteger<T>(T);

// Seal to prevent downstream implementations of the Integer trait.
mod private {
    #[doc(hidden)]
    pub trait Sealed: Copy {
        #[doc(hidden)]
        type Buffer: 'static;
        fn write(self, buf: &mut Self::Buffer) -> &str;
    }
}

const DEC_DIGITS_LUT: [u8; 200] = *b"\
      0001020304050607080910111213141516171819\
      2021222324252627282930313233343536373839\
      4041424344454647484950515253545556575859\
      6061626364656667686970717273747576777879\
      8081828384858687888990919293949596979899";

// Adaptation of the original implementation at
// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266
macro_rules! impl_Integer {
    ($t:ty[len = $max_len:expr] as $large_unsigned:ty) => {
        impl Integer for $t {
            const MAX_STR_LEN: usize = $max_len;
        }

        impl private::Sealed for $t {
            type Buffer = [MaybeUninit<u8>; $max_len];

            #[inline]
            #[cfg_attr(feature = "no-panic", no_panic)]
            fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
                ConstInteger(self).write(buf)
            }
        }

        impl ConstInteger<$t> {
            #[allow(unused_comparisons)]
            #[inline]
            pub const fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
                let Self(this) = self;
                let is_nonnegative = this >= 0;
                let mut n = if is_nonnegative {
                    this as $large_unsigned
                } else {
                    // Convert negative number to positive by summing 1 to its two's complement.
                    (!(this as $large_unsigned)).wrapping_add(1)
                };
                let mut curr = buf.len();
                #[expect(clippy::ptr_as_ptr)]
                let buf_ptr = buf.as_mut_ptr() as *mut u8;
                let lut_ptr = DEC_DIGITS_LUT.as_ptr();

                // Render 4 digits at a time.
                while n >= 10000 {
                    let rem = n % 10000;
                    n /= 10000;

                    let d1 = ((rem / 100) << 1) as usize;
                    let d2 = ((rem % 100) << 1) as usize;
                    curr -= 4;
                    unsafe {
                        ptr::copy_nonoverlapping(lut_ptr.add(d1), buf_ptr.add(curr), 2);
                        ptr::copy_nonoverlapping(lut_ptr.add(d2), buf_ptr.add(curr + 2), 2);
                    }
                }

                // Render 2 more digits, if >2 digits.
                if n >= 100 {
                    let d1 = ((n % 100) << 1) as usize;
                    n /= 100;
                    curr -= 2;
                    unsafe {
                        ptr::copy_nonoverlapping(lut_ptr.add(d1), buf_ptr.add(curr), 2);
                    }
                }

                // Render last 1 or 2 digits.
                if n < 10 {
                    curr -= 1;
                    unsafe {
                        *buf_ptr.add(curr) = (n as u8) + b'0';
                    }
                } else {
                    let d1 = (n << 1) as usize;
                    curr -= 2;
                    unsafe {
                        ptr::copy_nonoverlapping(lut_ptr.add(d1), buf_ptr.add(curr), 2);
                    }
                }

                if !is_nonnegative {
                    curr -= 1;
                    unsafe {
                        *buf_ptr.add(curr) = b'-';
                    }
                }

                let len = buf.len() - curr;
                let bytes = unsafe { slice::from_raw_parts(buf_ptr.add(curr), len) };
                unsafe { str::from_utf8_unchecked(bytes) }
            }
        }
    };
}

impl_Integer!(i8[len = 4] as u32);
impl_Integer!(u8[len = 3] as u32);
impl_Integer!(i16[len = 6] as u32);
impl_Integer!(u16[len = 5] as u32);
impl_Integer!(i32[len = 11] as u32);
impl_Integer!(u32[len = 10] as u32);
impl_Integer!(i64[len = 20] as u64);
impl_Integer!(u64[len = 20] as u64);

macro_rules! impl_Integer_size {
    ($t:ty as $primitive:ident #[cfg(target_pointer_width = $width:literal)]) => {
        #[cfg(target_pointer_width = $width)]
        impl Integer for $t {
            const MAX_STR_LEN: usize = <$primitive as Integer>::MAX_STR_LEN;
        }

        #[cfg(target_pointer_width = $width)]
        impl private::Sealed for $t {
            type Buffer = <$primitive as private::Sealed>::Buffer;

            #[inline]
            #[cfg_attr(feature = "no-panic", no_panic)]
            fn write(self, buf: &mut Self::Buffer) -> &str {
                (self as $primitive).write(buf)
            }
        }

        #[cfg(target_pointer_width = $width)]
        impl ConstInteger<$t> {
            #[inline]
            const fn write(
                self,
                buf: &mut [MaybeUninit<u8>; <$t as Integer>::MAX_STR_LEN],
            ) -> &str {
                ConstInteger(self.0 as $primitive).write(buf)
            }
        }
    };
}

impl_Integer_size!(isize as i16 #[cfg(target_pointer_width = "16")]);
impl_Integer_size!(usize as u16 #[cfg(target_pointer_width = "16")]);
impl_Integer_size!(isize as i32 #[cfg(target_pointer_width = "32")]);
impl_Integer_size!(usize as u32 #[cfg(target_pointer_width = "32")]);
impl_Integer_size!(isize as i64 #[cfg(target_pointer_width = "64")]);
impl_Integer_size!(usize as u64 #[cfg(target_pointer_width = "64")]);

macro_rules! impl_Integer128 {
    ($t:ty[len = $max_len:expr]) => {
        impl Integer for $t {
            const MAX_STR_LEN: usize = $max_len;
        }

        impl private::Sealed for $t {
            type Buffer = [MaybeUninit<u8>; $max_len];

            #[inline]
            #[cfg_attr(feature = "no-panic", no_panic)]
            fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
                ConstInteger(self).write(buf)
            }
        }

        impl ConstInteger<$t> {
            #[allow(unused_comparisons)]
            #[inline]
            #[cfg_attr(feature = "no-panic", no_panic)]
            pub const fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
                let Self(this) = self;
                let is_nonnegative = this >= 0;
                let n = if is_nonnegative {
                    this as u128
                } else {
                    // Convert negative number to positive by summing 1 to its two's complement.
                    (!(this as u128)).wrapping_add(1)
                };
                let mut curr = buf.len();
                #[expect(clippy::ptr_as_ptr)]
                let buf_ptr = buf.as_mut_ptr() as *mut u8;

                // Divide by 10^19 which is the highest power less than 2^64.
                let (n, rem) = udiv128::udivmod_1e19(n);
                #[expect(clippy::ptr_as_ptr)]
                let buf1 = unsafe {
                    buf_ptr.add(curr - u64::MAX_STR_LEN) as *mut [MaybeUninit<u8>; u64::MAX_STR_LEN]
                };
                curr -= ConstInteger(rem).write(unsafe { &mut *buf1 }).len();

                if n != 0 {
                    // Memset the base10 leading zeros of rem.
                    let target = buf.len() - 19;
                    unsafe {
                        ptr::write_bytes(buf_ptr.add(target), b'0', curr - target);
                    }
                    curr = target;

                    // Divide by 10^19 again.
                    let (n, rem) = udiv128::udivmod_1e19(n);
                    #[expect(clippy::ptr_as_ptr)]
                    let buf2 = unsafe {
                        buf_ptr.add(curr - u64::MAX_STR_LEN)
                            as *mut [MaybeUninit<u8>; u64::MAX_STR_LEN]
                    };
                    curr -= ConstInteger(rem).write(unsafe { &mut *buf2 }).len();

                    if n != 0 {
                        // Memset the leading zeros.
                        let target = buf.len() - 38;
                        unsafe {
                            ptr::write_bytes(buf_ptr.add(target), b'0', curr - target);
                        }
                        curr = target;

                        // There is at most one digit left
                        // because u128::MAX / 10^19 / 10^19 is 3.
                        curr -= 1;
                        unsafe {
                            *buf_ptr.add(curr) = (n as u8) + b'0';
                        }
                    }
                }

                if !is_nonnegative {
                    curr -= 1;
                    unsafe {
                        *buf_ptr.add(curr) = b'-';
                    }
                }

                let len = buf.len() - curr;
                let bytes = unsafe { slice::from_raw_parts(buf_ptr.add(curr), len) };
                unsafe { str::from_utf8_unchecked(bytes) }
            }
        }
    };
}

impl_Integer128!(i128[len = 40]);
impl_Integer128!(u128[len = 39]);

/// Const version of [`Buffer::format()`].
///
/// ```
/// let mut buffer = const_itoa::Buffer::new();
/// let printed = buffer.format(1234i16);
/// assert_eq!(printed, "1234");
///
/// # const { macro_rules! assert_eq {($a:expr,$b:expr)=>{{mod __b {pub const VAL: &[u8] = $b.as_bytes();}assert!(matches!($a.as_bytes(), __b::VAL))}}}
/// let mut buffer = const_itoa::Buffer::new();
/// let printed = const_itoa::Format(&mut buffer, 1234u16).call_once();
/// assert_eq!(printed, "1234");
///
/// let mut buffer = [std::mem::MaybeUninit::<u8>::uninit(); <i128 as const_itoa::Integer>::MAX_STR_LEN];
/// let printed = const_itoa::Format(&mut buffer, -1234i128).call_once();
/// assert_eq!(printed, "-1234");
/// # }
/// ```
pub struct Format<'a, B, T>(pub &'a mut B, pub T);

macro_rules! impl_fns {
    (
        type $T:ident = each_of!$each_of:tt;

        $($rest:tt)*
    ) => {
        impl_fns! { @impl $T $each_of {$($rest)*} }
    };
    (@impl $T:ident [$($Ty:ty),* $(,)?] $impl_body:tt) => {$(
        const _: () = {
            type $T = $Ty;
            const _: () = $impl_body;
        };
    )*};
}
impl_fns!(
    type I = each_of![
        i8, u8, i16, u16, i32, u32, i64, u64, //
        isize, usize, //
        i128, u128, //
    ];

    impl<'a> Format<'a, [MaybeUninit<u8>; <I as Integer>::MAX_STR_LEN], I> {
        pub const fn call_once(self) -> &'a str {
            let Self(buf, i) = self;

            ConstInteger(i).write(buf)
        }
    }

    impl<'a> Format<'a, Buffer, I> {
        /// Const version of [`Buffer::format()`].
        pub const fn call_once(self) -> &'a str {
            let Self(buf, i) = self;
            let i = ConstInteger(i);

            #[expect(clippy::ptr_as_ptr)]
            #[expect(clippy::borrow_as_ptr)]
            let string = i.write(unsafe {
                &mut *(&mut buf.bytes as *mut [MaybeUninit<u8>; i128::MAX_STR_LEN]
                    as *mut <I as private::Sealed>::Buffer)
            });
            if string.len() > I::MAX_STR_LEN {
                unsafe { hint::unreachable_unchecked() };
            }
            string
        }
    }
);