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
use crate::string;

use super::{ErrorKind, ParseDirection, ParseValueResult, Parser};

impl<'a> Parser<'a> {
    /// Parses a `u128` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_u128`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `u128`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::{
    ///     parsing::{Parser, ParseValueResult},
    ///     unwrap_ctx, try_,
    /// };
    ///
    /// {
    ///     let parser = Parser::new("12345");
    ///     let (num, parser) = unwrap_ctx!(parser.parse_u128());
    ///     assert_eq!(num, 12345);
    ///     assert!(parser.is_empty());
    /// }
    ///
    /// /// Parses a `[u128; 2]` from a parser starting with `"<number>;<number>", eg: `"100;400"`.
    /// const fn parse_pair(mut parser: Parser<'_>) -> ParseValueResult<'_, [u128; 2]> {
    ///     let mut ret = [0; 2];
    ///     
    ///     (ret[0], parser) = try_!(parser.parse_u128());
    ///     
    ///     // parsing the `;``between the integers.
    ///     //
    ///     // Note that because we don't use `.trim_start()` afterwards,
    ///     // this can't be followed by spaces.
    ///     parser = try_!(parser.strip_prefix(";"));
    ///     
    ///     (ret[1], parser) = try_!(parser.parse_u128());
    ///     
    ///     Ok((ret, parser))
    /// }
    /// const PAIR: ([u128; 2], Parser<'_>) = {
    ///     let parser = Parser::new("1365;6789");
    ///     unwrap_ctx!(parse_pair(parser))
    /// };
    ///
    /// assert_eq!(PAIR.0[0], 1365);
    /// assert_eq!(PAIR.0[1], 6789);
    ///
    /// assert!(PAIR.1.is_empty());
    ///
    /// ```
    ///
    /// [`primitive::parse_u128`]: ../primitive/fn.parse_u128.html
    pub const fn parse_u128(mut self) -> ParseValueResult<'a, u128> {
        parse_integer! {unsigned, (u128, u128), self}
    }
    /// Parses a `i128` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_i128`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `i128`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::{Parser, unwrap_ctx, rebind_if_ok};
    ///
    /// {
    ///     let parser = Parser::new("12345");
    ///     let (num, parser) = unwrap_ctx!(parser.parse_i128());
    ///     assert_eq!(num, 12345);
    ///     assert!(parser.is_empty());
    /// }
    /// {
    ///     let mut num = 0;
    ///     let mut parser = Parser::new("-54321;6789");
    ///     
    ///     // `rebind_if_ok` stores the return value of `.parse_i128()` in `num` and `parser`,
    ///     // if `.parse_i128()` returned an `Ok((u128, Parser))`.
    ///     rebind_if_ok!{(num, parser) = parser.parse_i128()}
    ///     assert_eq!(num, -54321);
    ///     assert_eq!(parser.remainder(), ";6789");
    ///
    ///     rebind_if_ok!{parser = parser.strip_prefix(";")}
    ///     assert_eq!(parser.remainder(), "6789");
    ///
    ///     rebind_if_ok!{(num, parser) = parser.parse_i128()}
    ///     assert_eq!(num, 6789);
    ///     assert!(parser.is_empty());
    /// }
    ///
    /// ```
    ///
    /// [`primitive::parse_i128`]: ../primitive/fn.parse_i128.html
    pub const fn parse_i128(mut self) -> ParseValueResult<'a, i128> {
        parse_integer! {signed, (i128, u128), self}
    }
    /// Parses a `u64` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_u64`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `u64`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_u128`](#method.parse_u128) method.
    ///
    /// [`primitive::parse_u64`]: ../primitive/fn.parse_u64.html
    pub const fn parse_u64(mut self) -> ParseValueResult<'a, u64> {
        parse_integer! {unsigned, (u64, u64), self}
    }
    /// Parses a `i64` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_i64`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `i64`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_i128`](#method.parse_i128) method.
    ///
    /// [`primitive::parse_i64`]: ../primitive/fn.parse_i64.html
    pub const fn parse_i64(mut self) -> ParseValueResult<'a, i64> {
        parse_integer! {signed, (i64, u64), self}
    }
    /// Parses a `u32` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_u32`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `u32`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_u128`](#method.parse_u128) method.
    ///
    /// [`primitive::parse_u32`]: ../primitive/fn.parse_u32.html
    pub const fn parse_u32(mut self) -> ParseValueResult<'a, u32> {
        parse_integer! {unsigned, (u32, u32), self}
    }
    /// Parses a `i32` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_i32`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `i32`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_i128`](#method.parse_i128) method.
    ///
    /// [`primitive::parse_i32`]: ../primitive/fn.parse_i32.html
    pub const fn parse_i32(mut self) -> ParseValueResult<'a, i32> {
        parse_integer! {signed, (i32, u32), self}
    }
    /// Parses a `u16` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_u16`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `u16`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_u128`](#method.parse_u128) method.
    ///
    /// [`primitive::parse_u16`]: ../primitive/fn.parse_u16.html
    pub const fn parse_u16(mut self) -> ParseValueResult<'a, u16> {
        parse_integer! {unsigned, (u16, u16), self}
    }
    /// Parses a `i16` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_i16`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `i16`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_i128`](#method.parse_i128) method.
    ///
    /// [`primitive::parse_i16`]: ../primitive/fn.parse_i16.html
    pub const fn parse_i16(mut self) -> ParseValueResult<'a, i16> {
        parse_integer! {signed, (i16, u16), self}
    }
    /// Parses a `u8` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_u8`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `u8`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_u128`](#method.parse_u128) method.
    ///
    /// [`primitive::parse_u8`]: ../primitive/fn.parse_u8.html
    pub const fn parse_u8(mut self) -> ParseValueResult<'a, u8> {
        parse_integer! {unsigned, (u8, u8), self}
    }
    /// Parses a `i8` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_i8`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `i8`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_i128`](#method.parse_i128) method.
    ///
    /// [`primitive::parse_i8`]: ../primitive/fn.parse_i8.html
    pub const fn parse_i8(mut self) -> ParseValueResult<'a, i8> {
        parse_integer! {signed, (i8, u8), self}
    }
    /// Parses a `usize` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_usize`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `usize`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// [`primitive::parse_usize`]: ../primitive/fn.parse_usize.html
    pub const fn parse_usize(mut self) -> ParseValueResult<'a, usize> {
        parse_integer! {unsigned, (usize, usize), self}
    }
    /// Parses a `isize` until a non-digit is reached.
    ///
    /// To parse an integer from an entire string (erroring on non-digit bytes),
    /// you can use [`primitive::parse_isize`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `isize`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// For an example for how to use this method,
    /// you can look at the docs for the [`Parser::parse_i128`](#method.parse_i128) method.
    ///
    /// [`primitive::parse_isize`]: ../primitive/fn.parse_isize.html
    pub const fn parse_isize(mut self) -> ParseValueResult<'a, isize> {
        parse_integer! {signed, (isize, usize), self}
    }
}

macro_rules! parse_integer {
    ($signedness:ident, ($type:ty, $uns:ty), $parser:ident) => (try_parsing! {
        $parser, FromStart, ret;{
            let mut num: $uns;

            let mut bytes = $parser.str.as_bytes();

            parse_integer! {@parse_signed $signedness, ($type, $uns), bytes, num, sign}

            while let [byte @ b'0'..=b'9', rem @ ..] = bytes {
                bytes = rem;

                let (next_mul, overflowed_mul) = num.overflowing_mul(10);
                let (next_add, overflowed_add) = next_mul.overflowing_add((*byte - b'0') as $uns);

                if overflowed_mul | overflowed_add {
                    throw!(ErrorKind::ParseInteger)
                }

                num = next_add;
            }

            parse_integer! {@apply_sign $signedness, ($type, $uns), num, sign}

            $parser.str = string::str_from($parser.str, $parser.str.len() - bytes.len());

            num
        }
    });
    (@parse_signed signed, ($type:ty, $uns:ty), $bytes:ident, $num:ident, $isneg:ident) => {
        let $isneg = if let [b'-', rem @ ..] = $bytes {
            $bytes = rem;
            true
        } else {
            false
        };

        parse_integer!(@parse_signed unsigned, ($type, $uns), $bytes, $num, $isneg)
    };
    (@parse_signed unsigned, ($type:ty, $uns:ty), $bytes:ident, $num:ident, $isneg:ident) => {
        $num = if let [byte @ b'0'..=b'9', rem @ ..] = $bytes {
            $bytes = rem;
            (*byte - b'0') as $uns
        } else {
            throw!(ErrorKind::ParseInteger)
        };
    };
    (@apply_sign signed, ($type:ty, $uns:ty), $num:ident, $isneg:ident) => {
        const MAX_POS: $uns = <$type>::MAX as $uns;
        const MAX_NEG: $uns = <$type>::MIN as $uns;

        let $num = if $isneg {
            if $num <= MAX_NEG {
                ($num as $type).wrapping_neg()
            } else {
                throw!(ErrorKind::ParseInteger)
            }
        } else {
            if $num <= MAX_POS {
                $num as $type
            } else {
                throw!(ErrorKind::ParseInteger)
            }
        };
    };
    (@apply_sign unsigned, ($type:ty, $uns:ty), $num:ident, $isneg:ident) => {};
}
use parse_integer;

////////////////////////////////////////////////////////////////////////////////

impl<'a> Parser<'a> {
    /// Parses a `bool`.
    ///
    /// To parse a bool from an entire string
    /// (erroring if the string isn't exactly `"true"` or `"false"`),
    /// you can use [`primitive::parse_bool`]
    ///
    /// You also can use the [`parse_with`](../macro.parse_with.html)
    /// macro to parse a `bool`, and other [`HasParser`](./trait.HasParser.html) types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use konst::{Parser, unwrap_ctx};
    ///
    /// {
    ///     let parser = Parser::new("falsemorestring");
    ///     let (boolean, parser) = unwrap_ctx!(parser.parse_bool());
    ///     assert_eq!(boolean, false);
    ///     assert_eq!(parser.remainder(), "morestring");
    /// }
    /// {
    ///     let parser = Parser::new("truefoo");
    ///     let (boolean, parser) = unwrap_ctx!(parser.parse_bool());
    ///     assert_eq!(boolean, true);
    ///     assert_eq!(parser.remainder(), "foo");
    /// }
    ///
    /// ```
    ///
    /// [`primitive::parse_bool`]: ../primitive/fn.parse_bool.html
    pub const fn parse_bool(mut self) -> ParseValueResult<'a, bool> {
        try_parsing! {self, FromStart, ret;
            match self.str.as_bytes() {
                [b't', b'r', b'u', b'e', ..] => {
                    self.str = string::str_from(self.str, 4);
                    true
                }
                [b'f', b'a', b'l', b's', b'e', ..] => {
                    self.str = string::str_from(self.str, 5);
                    false
                }
                _ => throw!(ErrorKind::ParseBool),
            }
        }
    }
}