Skip to main content

proctor_libc/stdlib/
mod.rs

1//! Safe equivalents of functions declared in C's `stdlib.h` header.
2
3use num_bigint::BigUint;
4
5/// An integer conversion error.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum StrtoIntError {
8    /// The requested base is not supported.
9    InvalidBase,
10    /// The converted value is outside the range of the return type.
11    OutOfRange,
12}
13
14/// A floating-point conversion error.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum StrtoFloatError {
17    /// The converted value overflowed or underflowed the return type.
18    OutOfRange,
19}
20
21const F32_FORMAT: FloatFormat = FloatFormat {
22    precision: 24,
23    fraction_bits: 23,
24    exponent_bits: 8,
25    exponent_bias: 127,
26    minimum_exponent: -126,
27    maximum_exponent: 127,
28    minimum_decimal_order: -45,
29    maximum_decimal_order: 38,
30};
31const F64_FORMAT: FloatFormat = FloatFormat {
32    precision: 53,
33    fraction_bits: 52,
34    exponent_bits: 11,
35    exponent_bias: 1023,
36    minimum_exponent: -1022,
37    maximum_exponent: 1023,
38    minimum_decimal_order: -324,
39    maximum_decimal_order: 308,
40};
41const F128_FORMAT: FloatFormat = FloatFormat {
42    precision: 113,
43    fraction_bits: 112,
44    exponent_bits: 15,
45    exponent_bias: 16383,
46    minimum_exponent: -16382,
47    maximum_exponent: 16383,
48    minimum_decimal_order: -4966,
49    maximum_decimal_order: 4932,
50};
51
52#[derive(Clone, Copy)]
53struct FloatFormat {
54    precision: u32,
55    fraction_bits: u32,
56    exponent_bits: u32,
57    exponent_bias: i32,
58    minimum_exponent: i64,
59    maximum_exponent: i64,
60    minimum_decimal_order: i64,
61    maximum_decimal_order: i64,
62}
63
64enum FloatSubject {
65    None,
66    Infinity {
67        negative: bool,
68        end: usize,
69    },
70    Nan {
71        negative: bool,
72        end: usize,
73    },
74    Finite {
75        negative: bool,
76        digits: Vec<u8>,
77        scale: FloatScale,
78        end: usize,
79    },
80}
81
82enum FloatScale {
83    Decimal(i64),
84    Binary(i64),
85}
86
87struct Mantissa {
88    digits: Vec<u8>,
89    saw_digit: bool,
90    fraction_digits: usize,
91    trailing_zeros: usize,
92    end: usize,
93}
94
95/// Converts the initial floating-point number in `buf` to an `f64`.
96pub fn atof(buf: &[i8]) -> f64 {
97    strtod(buf).0.0
98}
99
100/// Converts the initial floating-point number in `buf` to an `f64`.
101///
102/// Returns the converted value, the unconsumed suffix, and the conversion
103/// status. `StrtoFloatError::OutOfRange` is the only error variant and reports
104/// overflow or inexact underflow.
105pub fn strtod(buf: &[i8]) -> ((f64, &[i8]), Result<(), StrtoFloatError>) {
106    let ((bits, suffix), status) = strto_float_bits(buf, F64_FORMAT);
107    ((f64::from_bits(bits as u64), suffix), status)
108}
109
110/// Converts the initial floating-point number in `buf` to an `f64`.
111///
112/// Returns the converted value, the mutable unconsumed suffix, and the
113/// conversion status. `StrtoFloatError::OutOfRange` is the only error variant
114/// and reports overflow or inexact underflow.
115pub fn strtod_mut(buf: &mut [i8]) -> ((f64, &mut [i8]), Result<(), StrtoFloatError>) {
116    let buf_len = buf.len();
117    let ((value, suffix), status) = strtod(buf);
118    let suffix_start = buf_len - suffix.len();
119    ((value, &mut buf[suffix_start..]), status)
120}
121
122/// Converts the initial floating-point number in `buf` to an `f32`.
123///
124/// Returns the converted value, the unconsumed suffix, and the conversion
125/// status. `StrtoFloatError::OutOfRange` is the only error variant and reports
126/// overflow or inexact underflow.
127pub fn strtof(buf: &[i8]) -> ((f32, &[i8]), Result<(), StrtoFloatError>) {
128    let ((bits, suffix), status) = strto_float_bits(buf, F32_FORMAT);
129    ((f32::from_bits(bits as u32), suffix), status)
130}
131
132/// Converts the initial floating-point number in `buf` to an `f32`.
133///
134/// Returns the converted value, the mutable unconsumed suffix, and the
135/// conversion status. `StrtoFloatError::OutOfRange` is the only error variant
136/// and reports overflow or inexact underflow.
137pub fn strtof_mut(buf: &mut [i8]) -> ((f32, &mut [i8]), Result<(), StrtoFloatError>) {
138    let buf_len = buf.len();
139    let ((value, suffix), status) = strtof(buf);
140    let suffix_start = buf_len - suffix.len();
141    ((value, &mut buf[suffix_start..]), status)
142}
143
144/// Converts the initial floating-point number in `buf` to [`struct@f128::f128`].
145///
146/// Returns the converted value, the unconsumed suffix, and the conversion
147/// status. `StrtoFloatError::OutOfRange` is the only error variant and reports
148/// overflow or inexact underflow.
149pub fn strtold(buf: &[i8]) -> ((f128::f128, &[i8]), Result<(), StrtoFloatError>) {
150    let ((bits, suffix), status) = strto_float_bits(buf, F128_FORMAT);
151    ((f128_from_bits(bits), suffix), status)
152}
153
154/// Converts the initial floating-point number in `buf` to [`struct@f128::f128`].
155///
156/// Returns the converted value, the mutable unconsumed suffix, and the
157/// conversion status. `StrtoFloatError::OutOfRange` is the only error variant
158/// and reports overflow or inexact underflow.
159pub fn strtold_mut(buf: &mut [i8]) -> ((f128::f128, &mut [i8]), Result<(), StrtoFloatError>) {
160    let buf_len = buf.len();
161    let ((value, suffix), status) = strtold(buf);
162    let suffix_start = buf_len - suffix.len();
163    ((value, &mut buf[suffix_start..]), status)
164}
165
166fn strto_float_bits(
167    buf: &[i8],
168    format: FloatFormat,
169) -> ((u128, &[i8]), Result<(), StrtoFloatError>) {
170    match scan_float_subject(buf) {
171        FloatSubject::None => ((0, buf), Ok(())),
172        FloatSubject::Infinity { negative, end } => {
173            ((infinity_bits(format, negative), &buf[end..]), Ok(()))
174        }
175        FloatSubject::Nan { negative, end } => ((nan_bits(format, negative), &buf[end..]), Ok(())),
176        FloatSubject::Finite {
177            negative,
178            digits,
179            scale,
180            end,
181        } => {
182            if digits.is_empty() {
183                return ((zero_bits(format, negative), &buf[end..]), Ok(()));
184            }
185
186            let (bits, out_of_range) = convert_finite_float(negative, &digits, scale, format);
187            let status = if out_of_range {
188                Err(StrtoFloatError::OutOfRange)
189            } else {
190                Ok(())
191            };
192            ((bits, &buf[end..]), status)
193        }
194    }
195}
196
197fn scan_float_subject(buf: &[i8]) -> FloatSubject {
198    let limit = buf.iter().position(|&byte| byte == 0).unwrap_or(buf.len());
199    let mut index = 0;
200    while index < limit && is_c_whitespace(buf[index]) {
201        index += 1;
202    }
203
204    let negative = match buf.get(index).copied() {
205        Some(byte) if byte == b'-' as i8 => {
206            index += 1;
207            true
208        }
209        Some(byte) if byte == b'+' as i8 => {
210            index += 1;
211            false
212        }
213        _ => false,
214    };
215    let number_start = index;
216
217    if starts_ignore_ascii_case(buf, index, limit, b"inf") {
218        index += 3;
219        if starts_ignore_ascii_case(buf, index, limit, b"inity") {
220            index += 5;
221        }
222        return FloatSubject::Infinity {
223            negative,
224            end: index,
225        };
226    }
227
228    if starts_ignore_ascii_case(buf, index, limit, b"nan") {
229        index += 3;
230        if buf.get(index).copied() == Some(b'(' as i8) {
231            let mut payload_end = index + 1;
232            while payload_end < limit && is_nan_character(buf[payload_end]) {
233                payload_end += 1;
234            }
235            if buf.get(payload_end).copied() == Some(b')' as i8) {
236                index = payload_end + 1;
237            }
238        }
239        return FloatSubject::Nan {
240            negative,
241            end: index,
242        };
243    }
244
245    if index + 2 <= limit
246        && buf.get(index).copied() == Some(b'0' as i8)
247        && matches!(buf.get(index + 1).copied(), Some(byte) if byte == b'x' as i8 || byte == b'X' as i8)
248    {
249        let mantissa = scan_mantissa(buf, index + 2, limit, 16);
250        if mantissa.saw_digit {
251            let (end, exponent) = scan_float_exponent(buf, mantissa.end, limit, b'p', b'P');
252            let scale = adjust_scale(
253                exponent,
254                mantissa.fraction_digits,
255                mantissa.trailing_zeros,
256                4,
257            );
258            return FloatSubject::Finite {
259                negative,
260                digits: mantissa.digits,
261                scale: FloatScale::Binary(scale),
262                end,
263            };
264        }
265    }
266
267    let mantissa = scan_mantissa(buf, number_start, limit, 10);
268    if !mantissa.saw_digit {
269        return FloatSubject::None;
270    }
271    let (end, exponent) = scan_float_exponent(buf, mantissa.end, limit, b'e', b'E');
272    FloatSubject::Finite {
273        negative,
274        digits: mantissa.digits,
275        scale: FloatScale::Decimal(adjust_scale(
276            exponent,
277            mantissa.fraction_digits,
278            mantissa.trailing_zeros,
279            1,
280        )),
281        end,
282    }
283}
284
285fn scan_mantissa(buf: &[i8], start: usize, limit: usize, radix: u32) -> Mantissa {
286    let mut digits = Vec::new();
287    let mut saw_digit = false;
288    let mut fraction_digits = 0;
289    let mut pending_zeros = 0;
290    let mut index = start;
291    let mut after_point = false;
292
293    while index < limit {
294        if !after_point && buf[index] == b'.' as i8 {
295            after_point = true;
296            index += 1;
297            continue;
298        }
299        let Some(digit) = digit_value(buf[index]).filter(|&digit| digit < radix) else {
300            break;
301        };
302        saw_digit = true;
303        if digit == 0 {
304            if !digits.is_empty() {
305                pending_zeros += 1;
306            }
307        } else {
308            digits.extend(std::iter::repeat_n(0, pending_zeros));
309            pending_zeros = 0;
310            digits.push(digit as u8);
311        }
312        if after_point {
313            fraction_digits += 1;
314        }
315        index += 1;
316    }
317
318    Mantissa {
319        digits,
320        saw_digit,
321        fraction_digits,
322        trailing_zeros: pending_zeros,
323        end: index,
324    }
325}
326
327fn scan_float_exponent(
328    buf: &[i8],
329    marker: usize,
330    limit: usize,
331    lower: u8,
332    upper: u8,
333) -> (usize, i64) {
334    if marker >= limit || !matches!(buf[marker] as u8, byte if byte == lower || byte == upper) {
335        return (marker, 0);
336    }
337
338    let mut index = marker + 1;
339    let negative = match buf.get(index).copied() {
340        Some(byte) if byte == b'-' as i8 => {
341            index += 1;
342            true
343        }
344        Some(byte) if byte == b'+' as i8 => {
345            index += 1;
346            false
347        }
348        _ => false,
349    };
350    let first_digit = index;
351    let mut exponent = 0_i64;
352    while index < limit {
353        let byte = buf[index] as u8;
354        if !byte.is_ascii_digit() {
355            break;
356        }
357        exponent = exponent
358            .saturating_mul(10)
359            .saturating_add(i64::from(byte - b'0'));
360        index += 1;
361    }
362    if index == first_digit {
363        return (marker, 0);
364    }
365    if negative {
366        exponent = -exponent;
367    }
368    (index, exponent)
369}
370
371fn convert_finite_float(
372    negative: bool,
373    digits: &[u8],
374    scale: FloatScale,
375    format: FloatFormat,
376) -> (u128, bool) {
377    let (numerator, denominator, binary_exponent) = match scale {
378        FloatScale::Decimal(decimal_exponent) => {
379            let decimal_order = usize_to_i64(digits.len())
380                .saturating_sub(1)
381                .saturating_add(decimal_exponent);
382            if decimal_order > format.maximum_decimal_order {
383                return (infinity_bits(format, negative), true);
384            }
385            if decimal_order < format.minimum_decimal_order.saturating_sub(1) {
386                return (zero_bits(format, negative), true);
387            }
388
389            let significand = BigUint::from_radix_be(digits, 10).expect("decimal digits are valid");
390            if decimal_exponent >= 0 {
391                let five = BigUint::from(5_u8).pow(decimal_exponent as u32);
392                (significand * five, BigUint::from(1_u8), decimal_exponent)
393            } else {
394                let magnitude = decimal_exponent.unsigned_abs() as u32;
395                (
396                    significand,
397                    BigUint::from(5_u8).pow(magnitude),
398                    decimal_exponent,
399                )
400            }
401        }
402        FloatScale::Binary(binary_exponent) => {
403            let leading_digit_exponent = i64::from(7 - digits[0].leading_zeros());
404            let exponent = usize_to_i64(digits.len().saturating_sub(1))
405                .saturating_mul(4)
406                .saturating_add(leading_digit_exponent)
407                .saturating_add(binary_exponent);
408            let minimum_subnormal_exponent =
409                format.minimum_exponent - i64::from(format.precision - 1);
410            if exponent > format.maximum_exponent {
411                return (infinity_bits(format, negative), true);
412            }
413            if exponent < minimum_subnormal_exponent - 1 {
414                return (zero_bits(format, negative), true);
415            }
416
417            (
418                BigUint::from_radix_be(digits, 16).expect("hexadecimal digits are valid"),
419                BigUint::from(1_u8),
420                binary_exponent,
421            )
422        }
423    };
424
425    encode_ratio(negative, &numerator, &denominator, binary_exponent, format)
426}
427
428fn encode_ratio(
429    negative: bool,
430    numerator: &BigUint,
431    denominator: &BigUint,
432    binary_exponent: i64,
433    format: FloatFormat,
434) -> (u128, bool) {
435    let ratio_exponent = floor_log2_ratio(numerator, denominator);
436    let mut exponent = ratio_exponent.saturating_add(binary_exponent);
437    let minimum_subnormal_exponent = format.minimum_exponent - i64::from(format.precision - 1);
438
439    if exponent >= format.minimum_exponent {
440        let shift = i64::from(format.precision - 1) - ratio_exponent;
441        let (mut significand, _) = round_ratio(numerator, denominator, shift);
442        if significand.bits() > u64::from(format.precision) {
443            significand >>= 1_usize;
444            exponent += 1;
445        }
446        if exponent > format.maximum_exponent {
447            return (infinity_bits(format, negative), true);
448        }
449
450        let significand = biguint_to_u128(&significand);
451        let implicit_bit = 1_u128 << (format.precision - 1);
452        let exponent_field = (exponent + i64::from(format.exponent_bias)) as u128;
453        let bits = sign_bits(format, negative)
454            | (exponent_field << format.fraction_bits)
455            | (significand - implicit_bit);
456        return (bits, false);
457    }
458
459    let shift = binary_exponent.saturating_sub(minimum_subnormal_exponent);
460    let (significand, inexact) = round_ratio(numerator, denominator, shift);
461    let significand = biguint_to_u128(&significand);
462    let minimum_normal_significand = 1_u128 << (format.precision - 1);
463    if significand >= minimum_normal_significand {
464        let bits = sign_bits(format, negative) | (1_u128 << format.fraction_bits);
465        return (bits, inexact);
466    }
467
468    (sign_bits(format, negative) | significand, inexact)
469}
470
471fn floor_log2_ratio(numerator: &BigUint, denominator: &BigUint) -> i64 {
472    let exponent = (numerator.bits() as i64) - (denominator.bits() as i64);
473    let below_power = if exponent >= 0 {
474        numerator < &(denominator << exponent as usize)
475    } else {
476        &(numerator << exponent.unsigned_abs() as usize) < denominator
477    };
478    if below_power { exponent - 1 } else { exponent }
479}
480
481fn round_ratio(numerator: &BigUint, denominator: &BigUint, shift: i64) -> (BigUint, bool) {
482    let (scaled_numerator, scaled_denominator) = if shift >= 0 {
483        (numerator << shift as usize, denominator.clone())
484    } else {
485        (
486            numerator.clone(),
487            denominator << shift.unsigned_abs() as usize,
488        )
489    };
490    let mut quotient = &scaled_numerator / &scaled_denominator;
491    let remainder = &scaled_numerator % &scaled_denominator;
492    let inexact = remainder.bits() != 0;
493    let doubled_remainder = &remainder << 1_usize;
494    if doubled_remainder > scaled_denominator
495        || (doubled_remainder == scaled_denominator && quotient.bit(0))
496    {
497        quotient += 1_u8;
498    }
499    (quotient, inexact)
500}
501
502fn biguint_to_u128(value: &BigUint) -> u128 {
503    let digits = value.to_u64_digits();
504    u128::from(digits.first().copied().unwrap_or(0))
505        | (u128::from(digits.get(1).copied().unwrap_or(0)) << 64)
506}
507
508fn zero_bits(format: FloatFormat, negative: bool) -> u128 {
509    sign_bits(format, negative)
510}
511
512fn infinity_bits(format: FloatFormat, negative: bool) -> u128 {
513    sign_bits(format, negative) | (maximum_exponent_field(format) << format.fraction_bits)
514}
515
516fn nan_bits(format: FloatFormat, negative: bool) -> u128 {
517    infinity_bits(format, negative) | (1_u128 << (format.fraction_bits - 1))
518}
519
520fn sign_bits(format: FloatFormat, negative: bool) -> u128 {
521    u128::from(negative) << (format.fraction_bits + format.exponent_bits)
522}
523
524fn maximum_exponent_field(format: FloatFormat) -> u128 {
525    (1_u128 << format.exponent_bits) - 1
526}
527
528fn f128_from_bits(bits: u128) -> f128::f128 {
529    // SAFETY: `f128::f128` is a `repr(C)` wrapper around `[u8; 16]`, and all
530    // IEEE binary128 bit patterns are valid values of that type.
531    unsafe { std::mem::transmute(bits.to_ne_bytes()) }
532}
533
534fn starts_ignore_ascii_case(buf: &[i8], start: usize, limit: usize, expected: &[u8]) -> bool {
535    start + expected.len() <= limit
536        && buf[start..start + expected.len()]
537            .iter()
538            .zip(expected)
539            .all(|(&actual, &expected)| (actual as u8).eq_ignore_ascii_case(&expected))
540}
541
542fn is_nan_character(byte: i8) -> bool {
543    matches!(byte as u8, b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'_')
544}
545
546fn usize_to_i64(value: usize) -> i64 {
547    i64::try_from(value).unwrap_or(i64::MAX)
548}
549
550fn adjust_scale(
551    exponent: i64,
552    fractional_digits: usize,
553    trailing_zeros: usize,
554    radix_bits: i64,
555) -> i64 {
556    if fractional_digits >= trailing_zeros {
557        let adjustment =
558            usize_to_i64(fractional_digits - trailing_zeros).saturating_mul(radix_bits);
559        exponent.saturating_sub(adjustment)
560    } else {
561        let adjustment =
562            usize_to_i64(trailing_zeros - fractional_digits).saturating_mul(radix_bits);
563        exponent.saturating_add(adjustment)
564    }
565}
566
567enum IntegerSubject {
568    None,
569    Digits {
570        negative: bool,
571        radix: u32,
572        start: usize,
573    },
574}
575
576struct IntegerMagnitude {
577    magnitude: u64,
578    end: usize,
579    out_of_range: bool,
580}
581
582/// Converts the initial decimal integer in `buf` to an `i32`.
583pub fn atoi(buf: &[i8]) -> i32 {
584    strtol(buf, 10).0.0 as i32
585}
586
587/// Converts the initial decimal integer in `buf` to an `i64`.
588pub fn atol(buf: &[i8]) -> i64 {
589    strtol(buf, 10).0.0
590}
591
592/// Converts the initial integer in `buf` using `base`.
593///
594/// Returns the converted value, the unconsumed suffix, and the conversion
595/// status. `StrtoIntError::InvalidBase` and `StrtoIntError::OutOfRange` are the
596/// only error variants; they report an unsupported base and overflow,
597/// respectively.
598pub fn strtol(buf: &[i8], base: i32) -> ((i64, &[i8]), Result<(), StrtoIntError>) {
599    let subject = match scan_integer_subject(buf, base) {
600        Ok(subject) => subject,
601        Err(error) => return ((0, buf), Err(error)),
602    };
603    let IntegerSubject::Digits {
604        negative,
605        radix,
606        start,
607    } = subject
608    else {
609        return ((0, buf), Ok(()));
610    };
611    let limit = if negative {
612        i64::MAX as u64 + 1
613    } else {
614        i64::MAX as u64
615    };
616    let conversion = convert_integer_magnitude(buf, start, radix, limit);
617
618    if conversion.out_of_range {
619        let value = if negative { i64::MIN } else { i64::MAX };
620        return (
621            (value, &buf[conversion.end..]),
622            Err(StrtoIntError::OutOfRange),
623        );
624    }
625
626    let value = if negative {
627        if conversion.magnitude == i64::MAX as u64 + 1 {
628            i64::MIN
629        } else {
630            -(conversion.magnitude as i64)
631        }
632    } else {
633        conversion.magnitude as i64
634    };
635
636    ((value, &buf[conversion.end..]), Ok(()))
637}
638
639/// Converts the initial integer in `buf` using `base`.
640///
641/// Returns the converted value, the mutable unconsumed suffix, and the
642/// conversion status. `StrtoIntError::InvalidBase` and
643/// `StrtoIntError::OutOfRange` are the only error variants; they report an
644/// unsupported base and overflow, respectively.
645pub fn strtol_mut(buf: &mut [i8], base: i32) -> ((i64, &mut [i8]), Result<(), StrtoIntError>) {
646    let buf_len = buf.len();
647    let ((value, suffix), status) = strtol(buf, base);
648    let suffix_start = buf_len - suffix.len();
649    ((value, &mut buf[suffix_start..]), status)
650}
651
652/// Converts the initial unsigned integer in `buf` using `base`.
653///
654/// Returns the converted value, the unconsumed suffix, and the conversion
655/// status. `StrtoIntError::InvalidBase` and `StrtoIntError::OutOfRange` are the
656/// only error variants; they report an unsupported base and overflow,
657/// respectively.
658pub fn strtoul(buf: &[i8], base: i32) -> ((u64, &[i8]), Result<(), StrtoIntError>) {
659    let subject = match scan_integer_subject(buf, base) {
660        Ok(subject) => subject,
661        Err(error) => return ((0, buf), Err(error)),
662    };
663    let IntegerSubject::Digits {
664        negative,
665        radix,
666        start,
667    } = subject
668    else {
669        return ((0, buf), Ok(()));
670    };
671    let conversion = convert_integer_magnitude(buf, start, radix, u64::MAX);
672
673    if conversion.out_of_range {
674        return (
675            (u64::MAX, &buf[conversion.end..]),
676            Err(StrtoIntError::OutOfRange),
677        );
678    }
679
680    let value = if negative {
681        0_u64.wrapping_sub(conversion.magnitude)
682    } else {
683        conversion.magnitude
684    };
685
686    ((value, &buf[conversion.end..]), Ok(()))
687}
688
689/// Converts the initial unsigned integer in `buf` using `base`.
690///
691/// Returns the converted value, the mutable unconsumed suffix, and the
692/// conversion status. `StrtoIntError::InvalidBase` and
693/// `StrtoIntError::OutOfRange` are the only error variants; they report an
694/// unsupported base and overflow, respectively.
695pub fn strtoul_mut(buf: &mut [i8], base: i32) -> ((u64, &mut [i8]), Result<(), StrtoIntError>) {
696    let buf_len = buf.len();
697    let ((value, suffix), status) = strtoul(buf, base);
698    let suffix_start = buf_len - suffix.len();
699    ((value, &mut buf[suffix_start..]), status)
700}
701
702fn scan_integer_subject(buf: &[i8], base: i32) -> Result<IntegerSubject, StrtoIntError> {
703    if base != 0 && !(2..=36).contains(&base) {
704        return Err(StrtoIntError::InvalidBase);
705    }
706
707    let mut index = 0;
708    while index < buf.len() && is_c_whitespace(buf[index]) {
709        index += 1;
710    }
711
712    let negative = match buf.get(index).copied() {
713        Some(byte) if byte == b'-' as i8 => {
714            index += 1;
715            true
716        }
717        Some(byte) if byte == b'+' as i8 => {
718            index += 1;
719            false
720        }
721        _ => false,
722    };
723
724    let radix = if base == 0 {
725        if has_hex_prefix(buf, index) {
726            index += 2;
727            16
728        } else if buf.get(index).copied() == Some(b'0' as i8) {
729            8
730        } else {
731            10
732        }
733    } else {
734        let radix = base as u32;
735        if radix == 16 && has_hex_prefix(buf, index) {
736            index += 2;
737        }
738        radix
739    };
740
741    if !matches!(buf.get(index).copied().and_then(digit_value), Some(digit) if digit < radix) {
742        return Ok(IntegerSubject::None);
743    }
744
745    Ok(IntegerSubject::Digits {
746        negative,
747        radix,
748        start: index,
749    })
750}
751
752fn convert_integer_magnitude(buf: &[i8], start: usize, radix: u32, limit: u64) -> IntegerMagnitude {
753    let cutoff = limit / u64::from(radix);
754    let cutlim = limit % u64::from(radix);
755    let mut magnitude = 0_u64;
756    let mut out_of_range = false;
757    let mut index = start;
758
759    while let Some(digit) = buf.get(index).copied().and_then(digit_value) {
760        if digit >= radix {
761            break;
762        }
763
764        if !out_of_range {
765            let digit = u64::from(digit);
766            if magnitude > cutoff || (magnitude == cutoff && digit > cutlim) {
767                out_of_range = true;
768            } else {
769                magnitude = magnitude * u64::from(radix) + digit;
770            }
771        }
772        index += 1;
773    }
774
775    IntegerMagnitude {
776        magnitude,
777        end: index,
778        out_of_range,
779    }
780}
781
782fn is_c_whitespace(byte: i8) -> bool {
783    matches!(byte as u8, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')
784}
785
786fn has_hex_prefix(buf: &[i8], index: usize) -> bool {
787    buf.get(index).copied() == Some(b'0' as i8)
788        && matches!(buf.get(index + 1).copied(), Some(byte) if byte == b'x' as i8 || byte == b'X' as i8)
789        && matches!(
790            buf.get(index + 2).copied().and_then(digit_value),
791            Some(0..=15)
792        )
793}
794
795fn digit_value(byte: i8) -> Option<u32> {
796    match byte as u8 {
797        byte @ b'0'..=b'9' => Some(u32::from(byte - b'0')),
798        byte @ b'a'..=b'z' => Some(u32::from(byte - b'a') + 10),
799        byte @ b'A'..=b'Z' => Some(u32::from(byte - b'A') + 10),
800        _ => None,
801    }
802}
803
804#[cfg(test)]
805mod tests;