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