itoa/
lib.rs

1//! [![github]](https://github.com/dtolnay/itoa) [![crates-io]](https://crates.io/crates/itoa) [![docs-rs]](https://docs.rs/itoa)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! This crate provides a fast conversion of integer primitives to decimal
10//! strings. The implementation comes straight from [libcore] but avoids the
11//! performance penalty of going through [`core::fmt::Formatter`].
12//!
13//! See also [`ryu`] for printing floating point primitives.
14//!
15//! [libcore]: https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254
16//! [`core::fmt::Formatter`]: https://doc.rust-lang.org/std/fmt/struct.Formatter.html
17//! [`ryu`]: https://github.com/dtolnay/ryu
18//!
19//! # Example
20//!
21//! ```
22//! fn main() {
23//!     let mut buffer = itoa::Buffer::new();
24//!     let printed = buffer.format(128u64);
25//!     assert_eq!(printed, "128");
26//! }
27//! ```
28//!
29//! # Performance (lower is better)
30//!
31//! ![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png)
32
33#![doc(html_root_url = "https://docs.rs/itoa/1.0.6")]
34#![no_std]
35#![allow(
36    clippy::cast_lossless,
37    clippy::cast_possible_truncation,
38    clippy::must_use_candidate,
39    clippy::unreadable_literal
40)]
41
42mod udiv128;
43
44use core::mem::{self, MaybeUninit};
45use core::{ptr, slice, str};
46#[cfg(feature = "no-panic")]
47use no_panic::no_panic;
48
49/// A correctly sized stack allocation for the formatted integer to be written
50/// into.
51///
52/// # Example
53///
54/// ```
55/// let mut buffer = itoa::Buffer::new();
56/// let printed = buffer.format(1234);
57/// assert_eq!(printed, "1234");
58/// ```
59pub struct Buffer {
60    bytes: [MaybeUninit<u8>; I128_MAX_LEN],
61}
62
63impl Default for Buffer {
64    #[inline]
65    fn default() -> Buffer {
66        Buffer::new()
67    }
68}
69
70impl Clone for Buffer {
71    #[inline]
72    fn clone(&self) -> Self {
73        Buffer::new()
74    }
75}
76
77impl Buffer {
78    /// This is a cheap operation; you don't need to worry about reusing buffers
79    /// for efficiency.
80    #[inline]
81    #[cfg_attr(feature = "no-panic", no_panic)]
82    pub fn new() -> Buffer {
83        let bytes = [MaybeUninit::<u8>::uninit(); I128_MAX_LEN];
84        Buffer { bytes }
85    }
86
87    /// Print an integer into this buffer and return a reference to its string
88    /// representation within the buffer.
89    #[cfg_attr(feature = "no-panic", no_panic)]
90    pub fn format<I: Integer>(&mut self, i: I) -> &str {
91        i.write(unsafe {
92            &mut *(&mut self.bytes as *mut [MaybeUninit<u8>; I128_MAX_LEN]
93                as *mut <I as private::Sealed>::Buffer)
94        })
95    }
96}
97
98/// An integer that can be written into an [`itoa::Buffer`][Buffer].
99///
100/// This trait is sealed and cannot be implemented for types outside of itoa.
101pub trait Integer: private::Sealed {}
102
103// Seal to prevent downstream implementations of the Integer trait.
104mod private {
105    pub trait Sealed: Copy {
106        type Buffer: 'static;
107        fn write(self, buf: &mut Self::Buffer) -> &str;
108    }
109}
110
111const DEC_DIGITS_LUT: &[u8] = b"\
112      0001020304050607080910111213141516171819\
113      2021222324252627282930313233343536373839\
114      4041424344454647484950515253545556575859\
115      6061626364656667686970717273747576777879\
116      8081828384858687888990919293949596979899";
117
118// Adaptation of the original implementation at
119// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266
120macro_rules! impl_Integer {
121    ($($max_len:expr => $t:ident),* as $conv_fn:ident) => {$(
122        impl Integer for $t {}
123
124        impl private::Sealed for $t {
125            type Buffer = [MaybeUninit<u8>; $max_len];
126
127            #[allow(unused_comparisons)]
128            #[inline]
129            #[cfg_attr(feature = "no-panic", no_panic)]
130            fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
131                let is_nonnegative = self >= 0;
132                let mut n = if is_nonnegative {
133                    self as $conv_fn
134                } else {
135                    // convert the negative num to positive by summing 1 to it's 2 complement
136                    (!(self as $conv_fn)).wrapping_add(1)
137                };
138                let mut curr = buf.len() as isize;
139                let buf_ptr = buf.as_mut_ptr() as *mut u8;
140                let lut_ptr = DEC_DIGITS_LUT.as_ptr();
141
142                unsafe {
143                    // need at least 16 bits for the 4-characters-at-a-time to work.
144                    if mem::size_of::<$t>() >= 2 {
145                        // eagerly decode 4 characters at a time
146                        while n >= 10000 {
147                            let rem = (n % 10000) as isize;
148                            n /= 10000;
149
150                            let d1 = (rem / 100) << 1;
151                            let d2 = (rem % 100) << 1;
152                            curr -= 4;
153                            ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
154                            ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2);
155                        }
156                    }
157
158                    // if we reach here numbers are <= 9999, so at most 4 chars long
159                    let mut n = n as isize; // possibly reduce 64bit math
160
161                    // decode 2 more chars, if > 2 chars
162                    if n >= 100 {
163                        let d1 = (n % 100) << 1;
164                        n /= 100;
165                        curr -= 2;
166                        ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
167                    }
168
169                    // decode last 1 or 2 chars
170                    if n < 10 {
171                        curr -= 1;
172                        *buf_ptr.offset(curr) = (n as u8) + b'0';
173                    } else {
174                        let d1 = n << 1;
175                        curr -= 2;
176                        ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
177                    }
178
179                    if !is_nonnegative {
180                        curr -= 1;
181                        *buf_ptr.offset(curr) = b'-';
182                    }
183                }
184
185                let len = buf.len() - curr as usize;
186                let bytes = unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) };
187                unsafe { str::from_utf8_unchecked(bytes) }
188            }
189        }
190    )*};
191}
192
193const I8_MAX_LEN: usize = 4;
194const U8_MAX_LEN: usize = 3;
195const I16_MAX_LEN: usize = 6;
196const U16_MAX_LEN: usize = 5;
197const I32_MAX_LEN: usize = 11;
198const U32_MAX_LEN: usize = 10;
199const I64_MAX_LEN: usize = 20;
200const U64_MAX_LEN: usize = 20;
201
202impl_Integer!(
203    I8_MAX_LEN => i8,
204    U8_MAX_LEN => u8,
205    I16_MAX_LEN => i16,
206    U16_MAX_LEN => u16,
207    I32_MAX_LEN => i32,
208    U32_MAX_LEN => u32
209    as u32);
210
211impl_Integer!(I64_MAX_LEN => i64, U64_MAX_LEN => u64 as u64);
212
213#[cfg(target_pointer_width = "16")]
214impl_Integer!(I16_MAX_LEN => isize, U16_MAX_LEN => usize as u16);
215
216#[cfg(target_pointer_width = "32")]
217impl_Integer!(I32_MAX_LEN => isize, U32_MAX_LEN => usize as u32);
218
219#[cfg(target_pointer_width = "64")]
220impl_Integer!(I64_MAX_LEN => isize, U64_MAX_LEN => usize as u64);
221
222macro_rules! impl_Integer128 {
223    ($($max_len:expr => $t:ident),*) => {$(
224        impl Integer for $t {}
225
226        impl private::Sealed for $t {
227            type Buffer = [MaybeUninit<u8>; $max_len];
228
229            #[allow(unused_comparisons)]
230            #[inline]
231            #[cfg_attr(feature = "no-panic", no_panic)]
232            fn write(self, buf: &mut [MaybeUninit<u8>; $max_len]) -> &str {
233                let is_nonnegative = self >= 0;
234                let n = if is_nonnegative {
235                    self as u128
236                } else {
237                    // convert the negative num to positive by summing 1 to it's 2 complement
238                    (!(self as u128)).wrapping_add(1)
239                };
240                let mut curr = buf.len() as isize;
241                let buf_ptr = buf.as_mut_ptr() as *mut u8;
242
243                unsafe {
244                    // Divide by 10^19 which is the highest power less than 2^64.
245                    let (n, rem) = udiv128::udivmod_1e19(n);
246                    let buf1 = buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [MaybeUninit<u8>; U64_MAX_LEN];
247                    curr -= rem.write(&mut *buf1).len() as isize;
248
249                    if n != 0 {
250                        // Memset the base10 leading zeros of rem.
251                        let target = buf.len() as isize - 19;
252                        ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize);
253                        curr = target;
254
255                        // Divide by 10^19 again.
256                        let (n, rem) = udiv128::udivmod_1e19(n);
257                        let buf2 = buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [MaybeUninit<u8>; U64_MAX_LEN];
258                        curr -= rem.write(&mut *buf2).len() as isize;
259
260                        if n != 0 {
261                            // Memset the leading zeros.
262                            let target = buf.len() as isize - 38;
263                            ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize);
264                            curr = target;
265
266                            // There is at most one digit left
267                            // because u128::max / 10^19 / 10^19 is 3.
268                            curr -= 1;
269                            *buf_ptr.offset(curr) = (n as u8) + b'0';
270                        }
271                    }
272
273                    if !is_nonnegative {
274                        curr -= 1;
275                        *buf_ptr.offset(curr) = b'-';
276                    }
277
278                    let len = buf.len() - curr as usize;
279                    let bytes = slice::from_raw_parts(buf_ptr.offset(curr), len);
280                    str::from_utf8_unchecked(bytes)
281                }
282            }
283        }
284    )*};
285}
286
287const U128_MAX_LEN: usize = 39;
288const I128_MAX_LEN: usize = 40;
289
290impl_Integer128!(I128_MAX_LEN => i128, U128_MAX_LEN => u128);