use std::net::IpAddr;
use super::{ConvertError, IpText, Width, int_error, widen};
pub fn parse_int(text: &str) -> Result<i64, ConvertError> {
let (negative, hex) = match (text.strip_prefix("0x"), text.strip_prefix("-0x")) {
(Some(hex), _) => (false, hex),
(_, Some(hex)) => (true, hex),
_ => {
return text
.parse::<i64>()
.map_err(|error| int_error(&error, text, 10));
}
};
if hex.starts_with(['+', '-']) {
return Err(ConvertError::NotInteger);
}
let magnitude = u64::from_str_radix(hex, 16).map_err(|error| int_error(&error, hex, 16))?;
if negative {
0_i64.checked_sub_unsigned(magnitude)
} else {
i64::try_from(magnitude).ok()
}
.ok_or(ConvertError::OutOfRange)
}
pub fn parse_float(text: &str, width: Width) -> Result<f64, ConvertError> {
let text = text.trim_matches(|c: char| c <= ' ');
let body = text.strip_prefix(['+', '-']).unwrap_or(text);
let infinity = if text.starts_with('-') {
f64::NEG_INFINITY
} else {
f64::INFINITY
};
match body {
"NaN" => Ok(f64::NAN),
"Infinity" => Ok(infinity),
_ if body.starts_with(|c: char| c.is_ascii_alphabetic()) => Err(ConvertError::NotFloat),
_ => {
let number = text.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(text);
match width {
Width::Double => number.parse::<f64>(),
Width::Single => number.parse::<f32>().map(widen),
}
.map_err(|_| ConvertError::NotFloat)
}
}
}
pub fn parse_ip(text: &str) -> Result<IpText<'_>, ConvertError> {
let address = match text.split_once('%') {
Some((address, zone)) if address.contains(':') && !zone.is_empty() => address,
Some(_) => return Err(ConvertError::NotIp),
None => text,
};
let addr: IpAddr = address.parse().map_err(|_| ConvertError::NotIp)?;
Ok(IpText { text, addr })
}