|
| 1 | +//! Rust implementation of C library function `strtoul` |
| 2 | +//! |
| 3 | +//! Copyright (c) Jonathan 'theJPster' Pallant 2019 |
| 4 | +//! Licensed under the Blue Oak Model Licence 1.0.0 |
| 5 | +
|
| 6 | +use crate::{CChar, CULong, CStringIter}; |
| 7 | + |
| 8 | +/// Rust implementation of C library function `strtoul`. |
| 9 | +/// |
| 10 | +/// Takes a null-terminated string and interprets it as a decimal integer. |
| 11 | +/// This integer is returned as a `CULong`. Parsing stops when the first |
| 12 | +/// non-digit ASCII byte is seen. If no valid ASCII digit bytes are seen, this |
| 13 | +/// function returns zero. |
| 14 | +#[no_mangle] |
| 15 | +pub unsafe extern "C" fn strtoul(s: *const CChar) -> CULong { |
| 16 | + let mut result: CULong = 0; |
| 17 | + for c in CStringIter::new(s) { |
| 18 | + if c >= b'0' && c <= b'9' { |
| 19 | + result *= 10; |
| 20 | + result += (c - b'0') as CULong; |
| 21 | + } else { |
| 22 | + break; |
| 23 | + } |
| 24 | + } |
| 25 | + result |
| 26 | +} |
| 27 | + |
| 28 | +#[cfg(test)] |
| 29 | +mod test { |
| 30 | + use super::strtoul; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn empty() { |
| 34 | + let result = unsafe { strtoul(b"\0".as_ptr()) }; |
| 35 | + assert_eq!(result, 0); |
| 36 | + } |
| 37 | + |
| 38 | + #[test] |
| 39 | + fn non_digit() { |
| 40 | + let result = unsafe { strtoul(b"1234x\0".as_ptr()) }; |
| 41 | + assert_eq!(result, 1234); |
| 42 | + } |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn bad_number() { |
| 46 | + let result = unsafe { strtoul(b"x\0".as_ptr()) }; |
| 47 | + assert_eq!(result, 0); |
| 48 | + } |
| 49 | + |
| 50 | + #[test] |
| 51 | + fn one() { |
| 52 | + let result = unsafe { strtoul(b"1\0".as_ptr()) }; |
| 53 | + assert_eq!(result, 1); |
| 54 | + } |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn hundredish() { |
| 58 | + let result = unsafe { strtoul(b"123\0".as_ptr()) }; |
| 59 | + assert_eq!(result, 123); |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn big_long() { |
| 64 | + let result = unsafe { strtoul(b"2147483647\0".as_ptr()) }; |
| 65 | + assert_eq!(result, 2147483647); |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments