itoa/
lib.rs

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