pub fn dn_atoi(line: &[u8]) -> Option<i32> {
if line.is_empty() {
return None;
}
let mut value: i32 = 0;
for &b in line {
if !b.is_ascii_digit() {
return None;
}
value = value.wrapping_mul(10).wrapping_add(i32::from(b - b'0'));
}
if value < 0 {
None
} else {
Some(value)
}
}
pub fn dn_atoui(line: &[u8]) -> Option<u32> {
if line.is_empty() {
return None;
}
let mut value: u32 = 0;
for &b in line {
if !b.is_ascii_digit() {
return None;
}
value = value.wrapping_mul(10).wrapping_add(u32::from(b - b'0'));
}
Some(value)
}
pub fn valid_port(n: i32) -> bool {
(1..=65535).contains(&n)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn atoi_rejects_empty_and_non_digit() {
assert_eq!(dn_atoi(b""), None);
assert_eq!(dn_atoi(b" 12"), None);
assert_eq!(dn_atoi(b"-3"), None);
assert_eq!(dn_atoi(b"1.0"), None);
}
#[test]
fn atoi_handles_typical_input() {
assert_eq!(dn_atoi(b"0"), Some(0));
assert_eq!(dn_atoi(b"123"), Some(123));
assert_eq!(dn_atoi(b"2147483647"), Some(i32::MAX));
}
#[test]
fn atoui_handles_typical_input() {
assert_eq!(dn_atoui(b"0"), Some(0));
assert_eq!(dn_atoui(b"4294967295"), Some(u32::MAX));
}
}