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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use super::{
    parse_16_chars, parse_2_chars, parse_32_chars, parse_4_chars, parse_8_chars, trees::*,
    IntErrorKind, ParseIntErrorPublic, MINUS, PLUS,
};

#[cfg(feature = "core_intrinsics")]
macro_rules! likely {
    ($e:expr) => {
        core::intrinsics::likely($e)
    };
}
#[cfg(not(feature = "core_intrinsics"))]
macro_rules! likely {
    ($e:expr) => {
        $e
    };
}

#[cfg(feature = "core_intrinsics")]
macro_rules! unlikely {
    ($e:expr) => {
        core::intrinsics::unlikely($e)
    };
}
#[cfg(not(feature = "core_intrinsics"))]
macro_rules! unlikely {
    ($e:expr) => {
        $e
    };
}

type Pie = ParseIntErrorPublic;

#[doc(hidden)]
pub trait FromStrRadixHelper: PartialOrd + Copy + 'static {
    const MINIMUM: Self;
    const BITS_COUNT: u32;
    const FIRST_SIG: u8;
    const TAIL: Self;
    const TREE: &'static [Self];
    const CHARS: usize;
    fn from_u128(u: u128) -> Self;
    fn from_u64(u: u64) -> Self;
    fn from_u32(u: u32) -> Self;
    fn from_u16(u: u16) -> Self;
    fn from_u8(u: u8) -> Self;

    fn mul_checked(&self, other: Self) -> Option<Self>;
    fn sub_checked(&self, other: Self) -> Option<Self>;
    fn add_checked(&self, other: Self) -> Option<Self>;
    /// # Safety
    /// Caller needs to ensure no overflow can occur.
    unsafe fn mul_unchecked(&self, other: Self) -> Self;
    /// # Safety
    /// Caller needs to ensure no overflow can occur.
    unsafe fn sub_unchecked(&self, other: Self) -> Self;
    /// # Safety
    /// Caller needs to ensure no overflow can occur.
    unsafe fn add_unchecked(&self, other: Self) -> Self;
}

macro_rules! doit {
    ($($t:ty,$tr:expr,$chars:literal,$first_sig:literal,$tail:literal)*) => ($(impl FromStrRadixHelper for $t {
        const MINIMUM: Self = Self::MIN;
        const FIRST_SIG: u8 = $first_sig;
        const TAIL: Self = $tail;
        const BITS_COUNT: u32 = Self::BITS;
        const TREE: &'static[Self] = $tr;
        const CHARS: usize = $chars;
        #[inline(always)]
        fn from_u128(u: u128) -> Self { u as Self }
        #[inline(always)]
        fn from_u64(u: u64) -> Self { u as Self }
        #[inline(always)]
        fn from_u32(u: u32) -> Self { u as Self }
        #[inline(always)]
        fn from_u16(u: u16) -> Self { u as Self }
        #[inline(always)]
        fn from_u8(u: u8) -> Self { u as Self }
        #[inline(always)]
        fn mul_checked(&self, other: Self) -> Option<Self> {
            Self::checked_mul(*self, other as Self)
        }
        #[inline(always)]
        fn sub_checked(&self, other: Self) -> Option<Self> {
            Self::checked_sub(*self, other as Self)
        }
        #[inline(always)]
        fn add_checked(&self, other: Self) -> Option<Self> {
            Self::checked_add(*self, other as Self)
        }
        #[inline(always)]
        unsafe fn mul_unchecked(&self, other: Self) -> Self {
            Self::wrapping_mul(*self, other as Self)
        }
        #[inline(always)]
        unsafe fn sub_unchecked(&self, other: Self) -> Self {
            Self::wrapping_sub(*self, other as Self)
        }
        #[inline(always)]
        unsafe fn add_unchecked(&self, other: Self) -> Self {
            Self::wrapping_add(*self, other as Self)
        }
    })*)
}

doit! {
    i8,TENS_I8,3,1,-28
    i16,TENS_I16,5,3,-2768
    i32,TENS_I32,10,2,-147_483_648
    i64,TENS_I64,19,9,-223_372_036_854_775_808
    i128,TENS_I128,39,1,-70141183460469231731687303715884105728
    u8,TENS_U8,3,2,55
    u16,TENS_U16,5,6,5535
    u32,TENS_U32,10,4,294_967_295
    u64,TENS_U64,20,1,8_446_744_073_709_551_615
    u128,TENS_U128,39,3,40_282_366_920_938_463_463_374_607_431_768_211_455
}

#[cfg(target_pointer_width = "16")] //E.g. msp430-none-elf micro-controller.
doit! {
    isize,TENS_ISIZE,5,3,-2768
    usize,TENS_USIZE,5,6,5535
}

#[cfg(target_pointer_width = "32")]
doit! {
    isize,TENS_ISIZE,10,2,-147_483_648
    usize,TENS_USIZE,10,4,294_967_295
}

#[cfg(target_pointer_width = "64")]
doit! {
    isize,TENS_ISIZE,19,9,-223_372_036_854_775_808
    usize,TENS_USIZE,20,1,8_446_744_073_709_551_615
}

// u128: 0 to 340_282_366_920_938_463_463_374_607_431_768_211_455
// (39 digits!)
#[doc(hidden)]
pub fn parse_challenger<T>(s: &[u8]) -> Result<T, Pie>
where
    T: FromStrRadixHelper,
{
    parse(s)
}

// u128: 0 to 340_282_366_920_938_463_463_374_607_431_768_211_455
// (39 digits!)

macro_rules! invalid {
    () => {
        Pie {
            kind: IntErrorKind::InvalidDigit,
        }
    };
}
macro_rules! empty {
    () => {
        Pie {
            kind: IntErrorKind::Empty,
        }
    };
}

macro_rules! pos_overflow {
    () => {
        Pie {
            kind: IntErrorKind::PosOverflow,
        }
    };
}

macro_rules! neg_overflow {
    () => {
        Pie {
            kind: IntErrorKind::NegOverflow,
        }
    };
}

/// Parses a UTF8 &str as a number.
///
/// It has exactly the same semantics as `std::str::parse`,
/// but faster. (compiled with nightly,simd features
/// and target native cpu will get the absolute fastest result.)
///
/// Positives are slightly faster than negatives when parsing and
/// if you don't need to put a leading `+` then that will be faster too.
/// # Examples
///
/// ```rust
/// let s = "+000123";
/// assert_eq!(atoi_radix10::parse_from_str(s), Ok(123));
/// ```
#[inline(always)]
pub fn parse_from_str<T: FromStrRadixHelper, S: AsRef<str>>(s: S) -> Result<T, Pie> {
    parse(s.as_ref().as_bytes())
}

/// Parses a UTF8 &[u8] slice as a number.
///
/// Takes a `&[u8]` because any non-utf/non-ascii will fail parsing as an integer.
///
/// It has exactly the same semantics as `std::str::parse`,
/// but faster. (compiled with nightly,simd features
/// and target native cpu will get the absolute fastest result.)
///
/// Positives are slightly faster than negatives when parsing and
/// if you don't need to put a leading `+` then that will be faster too.
///
/// # Examples
///
/// ```rust
/// let s: String = "+000123".into();
/// assert_eq!(atoi_radix10::parse::<u8>(s.as_bytes()), Ok(123));
/// ```
pub fn parse<T>(mut s: &[u8]) -> Result<T, Pie>
where
    T: FromStrRadixHelper,
{
    let is_signed_ty = T::from_u32(0) > T::MINIMUM;
    let mut checked: Option<(u8, T)> = None;
    if let Some(val) = s.get(0) {
        let mut val = val.wrapping_sub(b'0');
        loop {
            if likely!(val <= 9) {
                // positive without +. could be long with lots of leading zeros.
                loop {
                    let l = s.len();
                    if likely!(l < T::CHARS) {
                        let mut res = T::from_u8(0);

                        unsafe {
                            for _ in 0..1 {
                                // Align so that s ptr ends b0
                                if s.as_ptr() as usize & 1 != 0 {
                                    let val_t = T::from_u8(val);
                                    s = s.get_unchecked(1..);
                                    if s.is_empty() {
                                        res = val_t;
                                        break;
                                    }
                                    res = val_t.mul_unchecked(*T::TREE.get_unchecked(s.len()));
                                }
                                if s.len() >= 2 && T::BITS_COUNT >= 8 {
                                    // Align so that s ptr ends b00
                                    if s.as_ptr() as usize & 2 != 0 {
                                        let val = T::from_u16(parse_2_chars(s)?);
                                        s = s.get_unchecked(2..);
                                        if s.is_empty() {
                                            res = res.add_unchecked(val);
                                            break;
                                        }
                                        res = res.add_unchecked(
                                            T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                        );
                                    }
                                    if s.len() >= 4 && T::BITS_COUNT >= 16 {
                                        // Align so that s ptr ends b000
                                        if s.as_ptr() as usize & 4 != 0 {
                                            let val = T::from_u16(parse_4_chars(s)?);
                                            s = s.get_unchecked(4..);
                                            if s.is_empty() {
                                                res = res.add_unchecked(val);
                                                break;
                                            }
                                            res = res.add_unchecked(
                                                T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                            );
                                        }
                                        if s.len() >= 8 && T::BITS_COUNT >= 32 {
                                            // Align so that s ptr ends b0000
                                            if s.as_ptr() as usize & 8 != 0 {
                                                let val = T::from_u32(parse_8_chars(s)?);
                                                s = s.get_unchecked(8..);
                                                if s.is_empty() {
                                                    res = res.add_unchecked(val);
                                                    break;
                                                }
                                                res = res.add_unchecked(
                                                    T::TREE
                                                        .get_unchecked(s.len())
                                                        .mul_unchecked(val),
                                                );
                                            }
                                            if s.len() >= 16 && T::BITS_COUNT >= 64 {
                                                // Align so that s ptr ends b00000
                                                if s.as_ptr() as usize & 16 != 0 {
                                                    let val = T::from_u64(parse_16_chars(s)?);
                                                    s = s.get_unchecked(16..);
                                                    if s.is_empty() {
                                                        res = res.add_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.add_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }

                                                // Did you see what we did there? at this point,
                                                // s is aligned for reading as a u128.
                                                if s.len() >= 32 && T::BITS_COUNT >= 128 {
                                                    let val = T::from_u128(parse_32_chars(s)?);
                                                    s = s.get_unchecked(32..);
                                                    if s.is_empty() {
                                                        res = res.add_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.add_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }

                                                //Even if we couldn't take 32 chars, 16 chars is aligned
                                                if s.len() >= 16 {
                                                    let val = T::from_u64(parse_16_chars(s)?);
                                                    s = s.get_unchecked(16..);
                                                    if s.is_empty() {
                                                        res = res.add_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.add_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }
                                            }

                                            if s.len() >= 8 {
                                                let val = T::from_u32(parse_8_chars(s)?);
                                                s = s.get_unchecked(8..);
                                                if s.is_empty() {
                                                    res = res.add_unchecked(val);
                                                    break;
                                                }
                                                res = res.add_unchecked(
                                                    T::TREE
                                                        .get_unchecked(s.len())
                                                        .mul_unchecked(val),
                                                );
                                            }
                                        }

                                        if s.len() >= 4 {
                                            let val = T::from_u16(parse_4_chars(s)?);
                                            s = s.get_unchecked(4..);
                                            if s.is_empty() {
                                                res = res.add_unchecked(val);
                                                break;
                                            }
                                            res = res.add_unchecked(
                                                T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                            );
                                        }
                                    }

                                    if s.len() >= 2 {
                                        let val = T::from_u16(parse_2_chars(s)?);
                                        s = s.get_unchecked(2..);
                                        if s.is_empty() {
                                            res = res.add_unchecked(val);
                                            break;
                                        }
                                        res = res.add_unchecked(
                                            T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                        );
                                    }
                                }

                                if let Some(val) = s.get(0) {
                                    let val = val.wrapping_sub(b'0');
                                    if val > 9 {
                                        return Err(invalid!());
                                    }
                                    res = res.add_unchecked(T::from_u8(val));
                                }
                            }
                            return if let Some((_, checked_t)) = checked {
                                checked_t.add_checked(res).ok_or(pos_overflow!())
                            } else {
                                Ok(res)
                            };
                        }
                    }
                    // Deal with edge cases then get back to the top,
                    if l == T::CHARS && val <= T::FIRST_SIG {
                        // SAFETY: mul is in range as `checked` is constrained to <= T::FIRST_SIG
                        let v = T::from_u8(val);
                        let mult = unsafe { v.mul_unchecked(*T::TREE.get_unchecked(T::CHARS - 1)) };
                        let val_next = unsafe { s.get_unchecked(1) };
                        checked = Some((val, mult));
                        val = val_next.wrapping_sub(b'0');
                        s = &s[1..];
                        if unlikely!(val > 9) {
                            return Err(invalid!());
                        }
                    } else if val == 0 {
                        // Remove leading zeros
                        val = b'0';
                        while val == b'0' {
                            s = &s[1..];
                            val = match s.get(0) {
                                Some(val) => *val,
                                None => return Ok(T::from_u8(0)),
                            }
                        }
                        val = val.wrapping_sub(b'0');
                        if val > 9 {
                            return Err(empty!());
                        }
                    } else {
                        return Err(pos_overflow!());
                    }
                    debug_assert!(val <= 9);
                }
            } else if likely!(is_signed_ty && val == MINUS) {
                s = &s[1..];

                // negative without -. could be long with lots of leading zeros.
                loop {
                    let l = s.len();
                    if likely!(l < T::CHARS && l != 0) {
                        let mut res = T::from_u8(0);
                        unsafe {
                            for _ in 0..1 {
                                // Align so that s ptr ends b0
                                if s.as_ptr() as usize & 1 != 0 {
                                    let val = s.get_unchecked(0).wrapping_sub(b'0');
                                    res = res.sub_unchecked(T::from_u8(val));
                                    if likely!(val <= 9 && l == 1) {
                                        return Ok(res);
                                    } else if likely!(val <= 9) {
                                        s = &s[1..];
                                        res = res.mul_unchecked(*T::TREE.get_unchecked(s.len()));
                                    } else {
                                        return Err(invalid!());
                                    };
                                }
                                if s.len() >= 2 && T::BITS_COUNT >= 8 {
                                    // Align so that s ptr ends b00
                                    if s.as_ptr() as usize & 2 != 0 {
                                        let val = T::from_u16(parse_2_chars(s)?);
                                        s = s.get_unchecked(2..);
                                        if s.is_empty() {
                                            res = res.sub_unchecked(val);
                                            break;
                                        }
                                        res = res.sub_unchecked(
                                            T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                        );
                                    }
                                    if s.len() >= 4 && T::BITS_COUNT >= 16 {
                                        // Align so that s ptr ends b000
                                        if s.as_ptr() as usize & 4 != 0 {
                                            let val = T::from_u16(parse_4_chars(s)?);
                                            s = s.get_unchecked(4..);
                                            if s.is_empty() {
                                                res = res.sub_unchecked(val);
                                                break;
                                            }
                                            res = res.sub_unchecked(
                                                T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                            );
                                        }
                                        if s.len() >= 8 && T::BITS_COUNT >= 32 {
                                            // Align so that s ptr ends b0000
                                            if s.as_ptr() as usize & 8 != 0 {
                                                let val = T::from_u32(parse_8_chars(s)?);
                                                s = s.get_unchecked(8..);
                                                if s.is_empty() {
                                                    res = res.sub_unchecked(val);
                                                    break;
                                                }
                                                res = res.sub_unchecked(
                                                    T::TREE
                                                        .get_unchecked(s.len())
                                                        .mul_unchecked(val),
                                                );
                                            }
                                            if s.len() >= 16 && T::BITS_COUNT >= 64 {
                                                // Align so that s ptr ends b00000
                                                if s.as_ptr() as usize & 16 != 0 {
                                                    let val = T::from_u64(parse_16_chars(s)?);
                                                    s = s.get_unchecked(16..);
                                                    if s.is_empty() {
                                                        res = res.sub_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.sub_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }

                                                // s is aligned so that we can read u128
                                                if s.len() >= 32 && T::BITS_COUNT >= 128 {
                                                    let val = T::from_u128(parse_32_chars(s)?);
                                                    s = &s[32..];
                                                    if s.is_empty() {
                                                        res = res.sub_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.sub_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }
                                                // all the following are now aligned.
                                                if s.len() >= 16 {
                                                    let val = T::from_u64(parse_16_chars(s)?);
                                                    s = &s[16..];
                                                    if s.is_empty() {
                                                        res = res.sub_unchecked(val);
                                                        break;
                                                    }
                                                    res = res.sub_unchecked(
                                                        T::TREE
                                                            .get_unchecked(s.len())
                                                            .mul_unchecked(val),
                                                    );
                                                }
                                            }
                                            if s.len() >= 8 {
                                                let val = T::from_u32(parse_8_chars(s)?);
                                                s = &s[8..];
                                                if s.is_empty() {
                                                    res = res.sub_unchecked(val);
                                                    break;
                                                }
                                                res = res.sub_unchecked(
                                                    T::TREE
                                                        .get_unchecked(s.len())
                                                        .mul_unchecked(val),
                                                );
                                            }
                                        }
                                        if s.len() >= 4 {
                                            let val = T::from_u16(parse_4_chars(s)?);
                                            s = &s[4..];
                                            if s.is_empty() {
                                                res = res.sub_unchecked(val);
                                                break;
                                            }
                                            res = res.sub_unchecked(
                                                T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                            );
                                        }
                                    }
                                    if s.len() >= 2 {
                                        let val = T::from_u16(parse_2_chars(s)?);
                                        s = &s[2..];
                                        if s.is_empty() {
                                            res = res.sub_unchecked(val);
                                            break;
                                        }
                                        res = res.sub_unchecked(
                                            T::TREE.get_unchecked(s.len()).mul_unchecked(val),
                                        );
                                    }
                                }
                                if let Some(val) = s.get(0) {
                                    let val = val.wrapping_sub(b'0');
                                    res = res.sub_unchecked(T::from_u8(val));
                                    if unlikely!(val > 9) {
                                        return Err(invalid!());
                                    };
                                }
                            }
                            return if let Some((chk, chk_t)) = checked {
                                if unlikely!(res == T::TAIL && chk == T::FIRST_SIG) {
                                    return Ok(T::MINIMUM);
                                }
                                res.sub_checked(chk_t).ok_or(neg_overflow!())
                            } else {
                                Ok(res)
                            };
                        }
                    }
                    val = if let Some(val) = s.get(0) {
                        *val
                    } else {
                        return Err(empty!());
                    };
                    val = val.wrapping_sub(b'0');
                    if l == T::CHARS && val <= T::FIRST_SIG {
                        // SAFETY: mul is in range as `checked` is constrained to <= T::FIRST_SIG
                        checked = Some((val, unsafe {
                            T::from_u8(val).mul_unchecked(*T::TREE.get_unchecked(T::CHARS - 1))
                        }));
                        s = &s[1..];
                    } else if val == 0 {
                        val = b'0';
                        while val == b'0' {
                            s = &s[1..];
                            val = match s.get(0) {
                                Some(val) => *val,
                                None => return Ok(T::from_u8(0)),
                            }
                        }
                    } else {
                        return Err(neg_overflow!());
                    }
                }
            } else if val == PLUS {
                s = &s[1..];
                val = match s.get(0) {
                    Some(value) => {
                        let value = value.wrapping_sub(b'0');
                        if likely!(value <= 9) {
                            value
                        } else {
                            return Err(empty!());
                        }
                    }
                    None => return Err(empty!()),
                };
            } else {
                return Err(invalid!());
            }
        }
    } else {
        Err(empty!())
    }
}