use std::fmt::Display;
#[derive(Debug, PartialEq)]
pub enum Value {
F32(f32),
F64(f64),
}
impl Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::F32(val) => write!(f, "{val}"),
Self::F64(val) => write!(f, "{val}"),
}
}
}
impl From<f32> for Value {
fn from(value: f32) -> Self {
Self::F32(value)
}
}
impl From<f64> for Value {
fn from(value: f64) -> Self {
Self::F64(value)
}
}
impl Value {
pub fn parse(val: &str, double: bool) -> color_eyre::Result<Self> {
if double {
let f64: f64 = val.parse()?;
Ok(f64.into())
} else {
let f32: f32 = val.parse()?;
Ok(f32.into())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use claim::{assert_err, assert_ok_eq};
use rstest::rstest;
#[rstest]
#[case("10.0", 10.0)]
#[case("69.420", 69.42)]
#[case("420.69", 420.69)]
#[case("147258", 147258.0)]
#[case("963852", 963852.0)]
fn parse_returns_ok_on_valid_input(#[case] val: &str, #[case] expected: f32) {
assert_ok_eq!(Value::parse(val, false), Value::F32(expected));
}
#[rstest]
#[case("1O.O")]
#[case("69.42O")]
#[case("42O.69")]
#[case("I47258")]
#[case("96E852X")]
fn parse_returns_err_on_invalid_input(#[case] val: &str) {
let _ = assert_err!(Value::parse(val, true));
}
}