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
#![deny(warnings)]
//!
//! Parse &str with common prefixes to integer values
//!
//! ```
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use parse_int::parse;
//!
//! let d = parse::<usize>("42")?;
//! assert_eq!(42, d);
//!
//! let d = parse::<isize>("0x42")?;
//! assert_eq!(66, d);
//!
//! // you can use underscores for more readable inputs
//! let d = parse::<isize>("0x42_424_242")?;
//! assert_eq!(1_111_638_594, d);
//!
//! // octal explicit
//! let d = parse::<u8>("0o42")?;
//! assert_eq!(34, d);
//!
//! ##[cfg(feature = "implicit-octal")]
//! {
//!     let d = parse::<i8>("042")?;
//!     assert_eq!(34, d);
//! }
//!
//! let d = parse::<u16>("0b0110")?;
//! assert_eq!(6, d);
//! #
//! #     Ok(())
//! # }
//! ```

use num_traits::Num;

/// Parse &str with common prefixes to integer values
///
/// ```
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use parse_int::parse;
///
/// // decimal
/// let d = parse::<usize>("42")?;
/// assert_eq!(42, d);
///
/// // hex
/// let d = parse::<isize>("0x42")?;
/// assert_eq!(66, d);
///
/// // you can use underscores for more readable inputs
/// let d = parse::<isize>("0x42_424_242")?;
/// assert_eq!(1_111_638_594, d);
///
/// // octal explicit
/// let d = parse::<u8>("0o42")?;
/// assert_eq!(34, d);
///
/// ##[cfg(feature = "implicit-octal")]
/// {
///     let d = parse::<i8>("042")?;
///     assert_eq!(34, d);
/// }
///
/// // binary
/// let d = parse::<u16>("0b0110")?;
/// assert_eq!(6, d);
/// #
/// #     Ok(())
/// # }
/// ```
#[inline]
pub fn parse<T: Num>(input: &str) -> Result<T, T::FromStrRadixErr> {
    let input = input.trim();

    // invalid start
    if input.starts_with("_") {
        /* With rust 1.55 the return type is stable but we can not construct it yet

        let kind = ::core::num::IntErrorKind::InvalidDigit;
        //let pie = ::core::num::ParseIntError {
        let pie = <<T as num_traits::Num>::FromStrRadixErr as Trait>::A {
            kind
        };
        return Err(pie);
        */
        return T::from_str_radix("XYZ", 2);
    }

    // hex
    if input.starts_with("0x") {
        return parse_with_base(&input[2..], 16);
    }

    // binary
    if input.starts_with("0b") {
        return parse_with_base(&input[2..], 2);
    }

    // octal
    if input.starts_with("0o") {
        return parse_with_base(&input[2..], 8);
    }
    #[cfg(feature = "implicit-octal")]
    {
        if input.starts_with("0") {
            return if input == "0" {
                Ok(T::zero())
            } else {
                parse_with_base(&input[1..], 8)
            };
        }
    }

    // decimal
    parse_with_base(&input, 10)
}

#[inline]
fn parse_with_base<T: Num>(input: &str, base: u32) -> Result<T, T::FromStrRadixErr> {
    let input = input.chars().filter(|&c| c != '_').collect::<String>();
    T::from_str_radix(&input, base)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn turbofish_usize_dec() {
        let s = "42";

        let u = parse::<usize>(s).unwrap();

        assert_eq!(42, u);
    }

    #[test]
    fn deduct_usize_dec() {
        let s = "42";

        let u = parse(s).unwrap();

        assert_eq!(42usize, u);
    }

    macro_rules! int_parse {
        ($type:ident, $s:literal, $e:literal) => {
            #[test]
            fn $type() {
                let u: Result<$type, _> = crate::parse($s);
                assert_eq!(Ok($e), u);
            }
        };
    }

    macro_rules! int_parse_err {
        ($type:ident, $s:literal) => {
            int_parse_err!($type, $s, err);
        };
        ($type:ident, $s:literal, $opt:ident) => {
            mod $opt {
                #[test]
                fn $type() {
                    let u: Result<$type, _> = crate::parse($s);
                    assert!(u.is_err(), "expected Err(_), got = {:?}", u);
                }
            }
        };
    }

    mod decimal {
        int_parse!(usize, "42", 42);
        int_parse!(isize, "42", 42);
        int_parse!(u8, "42", 42);
        int_parse!(i8, "42", 42);
        int_parse!(u16, "42", 42);
        int_parse!(i16, "42", 42);
        int_parse!(u32, "42", 42);
        int_parse!(i32, "42", 42);
        int_parse!(u64, "42", 42);
        int_parse!(i64, "42", 42);
        int_parse!(u128, "42", 42);
        int_parse!(i128, "42", 42);
    }

    mod decimal_negative {
        int_parse!(isize, "-42", -42);
        int_parse!(i8, "-42", -42);
    }

    mod hexadecimal {
        int_parse!(usize, "0x42", 66);
        int_parse!(isize, "0x42", 66);
        int_parse!(u8, "0x42", 66);
        int_parse!(i8, "0x42", 66);
        int_parse!(u16, "0x42", 66);
        int_parse!(i16, "0x42", 66);
        int_parse!(u32, "0x42", 66);
        int_parse!(i32, "0x42", 66);
        int_parse!(u64, "0x42", 66);
        int_parse!(i64, "0x42", 66);
        int_parse!(u128, "0x42", 66);
        int_parse!(i128, "0x42", 66);
    }

    mod octal_explicit {
        int_parse!(usize, "0o42", 34);
        int_parse!(isize, "0o42", 34);
        int_parse!(u8, "0o42", 34);
        int_parse!(i8, "0o42", 34);
        int_parse!(u16, "0o42", 34);
        int_parse!(i16, "0o42", 34);
        int_parse!(u32, "0o42", 34);
        int_parse!(i32, "0o42", 34);
        int_parse!(u64, "0o42", 34);
        int_parse!(i64, "0o42", 34);
        int_parse!(u128, "0o42", 34);
        int_parse!(i128, "0o42", 34);
    }

    #[cfg(feature = "implicit-octal")]
    mod octal_implicit {
        use super::*;
        int_parse!(usize, "042", 34);
        int_parse!(isize, "042", 34);
        int_parse!(u8, "042", 34);
        int_parse!(i8, "042", 34);
        int_parse!(u16, "042", 34);
        int_parse!(i16, "042", 34);
        int_parse!(u32, "042", 34);
        int_parse!(i32, "042", 34);
        int_parse!(u64, "042", 34);
        int_parse!(i64, "042", 34);
        int_parse!(u128, "042", 34);
        int_parse!(i128, "042", 34);

        #[test]
        fn issue_nr_0() {
            let s = "0";

            assert_eq!(0, parse::<usize>(s).unwrap());
            assert_eq!(0, parse::<isize>(s).unwrap());
            assert_eq!(0, parse::<i8>(s).unwrap());
            assert_eq!(0, parse::<u8>(s).unwrap());
            assert_eq!(0, parse::<i16>(s).unwrap());
            assert_eq!(0, parse::<u16>(s).unwrap());
            assert_eq!(0, parse::<i32>(s).unwrap());
            assert_eq!(0, parse::<u32>(s).unwrap());
            assert_eq!(0, parse::<i64>(s).unwrap());
            assert_eq!(0, parse::<u64>(s).unwrap());
            assert_eq!(0, parse::<i128>(s).unwrap());
            assert_eq!(0, parse::<u128>(s).unwrap());
        }
    }
    #[cfg(not(feature = "implicit-octal"))]
    mod octal_implicit_disabled {
        use super::*;
        #[test]
        /// maybe this will change in the future
        fn no_implicit_is_int() {
            let s = "042";

            let u = parse::<usize>(s);
            assert_eq!(Ok(42), u, "{:?}", u);
        }
    }

    mod binary {
        int_parse!(usize, "0b0110", 6);
        int_parse!(isize, "0b0110", 6);
        int_parse!(u8, "0b0110", 6);
        int_parse!(i8, "0b0110", 6);
        int_parse!(u16, "0b0110", 6);
        int_parse!(i16, "0b0110", 6);
        int_parse!(u32, "0b0110", 6);
        int_parse!(i32, "0b0110", 6);
        int_parse!(u64, "0b0110", 6);
        int_parse!(i64, "0b0110", 6);
        int_parse!(u128, "0b0110", 6);
        int_parse!(i128, "0b0110", 6);
    }

    mod binary_negative {
        int_parse_err!(i8, "0b1000_0000");
        int_parse!(i8, "0b-0111_1111", -127);
    }

    mod underscore {
        int_parse!(usize, "0b0110_0110", 102);
        int_parse!(isize, "0x0110_0110", 17_826_064);
        int_parse!(u64, "0o0110_0110", 294_984);
        int_parse!(u128, "1_100_110", 1_100_110);

        #[cfg(feature = "implicit-octal")]
        mod implicit_octal {
            int_parse!(i128, "0110_0110", 294_984);
        }
        #[cfg(not(feature = "implicit-octal"))]
        mod implicit_octal {
            int_parse!(i128, "0110_0110", 1_100_110);
        }
    }

    mod underscore_in_prefix {
        #[test]
        fn invalid_underscore_in_prefix() {
            let r = crate::parse::<isize>("_4");
            println!("{:?}", r);
            assert!(r.is_err());
        }
        int_parse_err!(isize, "0_x_4", hex);
        int_parse_err!(isize, "_4", decimal);
        int_parse_err!(isize, "0_o_4", octal);
        int_parse_err!(isize, "0_b_1", binary);
    }
}