use std::fmt::Write as _;
use std::net::IpAddr;
use std::num::IntErrorKind;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ConvertError {
#[error("not an integer")]
NotInteger,
#[error("outside the 64-bit integer range")]
OutOfRange,
#[error("not a number")]
NotFloat,
#[error("not true or false")]
NotBoolean,
#[error("not an IP address")]
NotIp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
Single,
Double,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IpText<'a> {
pub text: &'a str,
pub addr: IpAddr,
}
pub fn parse_int(text: &str) -> Result<i64, ConvertError> {
let text = text.trim();
let read = match text.strip_prefix("0x") {
Some(hex) if hex.starts_with(['+', '-']) => return Err(ConvertError::NotInteger),
Some(hex) => i64::from_str_radix(hex, 16),
None => text.parse::<i64>(),
};
read.map_err(|error| match error.kind() {
IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => ConvertError::OutOfRange,
_ => ConvertError::NotInteger,
})
}
pub fn parse_float(text: &str, width: Width) -> Result<f64, ConvertError> {
let text = text.trim();
match width {
Width::Double => text.parse::<f64>().map_err(|_| ConvertError::NotFloat),
Width::Single => text
.parse::<f32>()
.map(widen)
.map_err(|_| ConvertError::NotFloat),
}
}
#[must_use]
pub fn narrow(value: f64, width: Width) -> f64 {
match width {
Width::Double => value,
#[allow(
clippy::cast_possible_truncation,
reason = "rounding to f32 is the point"
)]
Width::Single => widen(value as f32),
}
}
pub const fn parse_bool(text: &str) -> Result<bool, ConvertError> {
if text.eq_ignore_ascii_case("true") {
Ok(true)
} else if text.eq_ignore_ascii_case("false") {
Ok(false)
} else {
Err(ConvertError::NotBoolean)
}
}
pub fn parse_ip(text: &str) -> Result<IpText<'_>, ConvertError> {
let text = text.trim();
let addr: IpAddr = text.parse().map_err(|_| ConvertError::NotIp)?;
Ok(IpText { text, addr })
}
pub fn truncate(value: f64) -> Result<i64, ConvertError> {
const BOUND: f64 = 9_223_372_036_854_775_808.0;
if value.is_nan() {
return Err(ConvertError::NotInteger);
}
if !(-BOUND..BOUND).contains(&value) {
return Err(ConvertError::OutOfRange);
}
#[allow(clippy::cast_possible_truncation, reason = "range checked above")]
Ok(value as i64)
}
fn widen(single: f32) -> f64 {
const EXACT: f32 = 16_777_216.0;
if !single.is_finite() || (single.abs() < EXACT && single.fract() == 0.0) {
return f64::from(single);
}
let mut digits = Digits::default();
if write!(digits, "{single:e}").is_err() {
return f64::from(single);
}
std::str::from_utf8(digits.as_bytes())
.ok()
.and_then(|text| text.parse::<f64>().ok())
.unwrap_or_else(|| f64::from(single))
}
#[derive(Default)]
struct Digits {
bytes: [u8; 32],
len: usize,
}
impl Digits {
fn as_bytes(&self) -> &[u8] {
self.bytes.get(..self.len).unwrap_or_default()
}
}
impl std::fmt::Write for Digits {
fn write_str(&mut self, text: &str) -> std::fmt::Result {
let end = self.len + text.len();
let slot = self.bytes.get_mut(self.len..end).ok_or(std::fmt::Error)?;
slot.copy_from_slice(text.as_bytes());
self.len = end;
Ok(())
}
}
#[cfg(test)]
mod tests;