Files
envkit/src/parser.rs
T
2026-06-08 03:04:17 -04:00

46 lines
1.3 KiB
Rust

use std::fmt::Display;
use std::any::type_name;
use crate::error::EnvError;
use std::str::FromStr;
/// A trait for types that can be parsed from a string as a number.
pub trait Number: FromStr<Err: Display> {}
impl Number for i8 {}
impl Number for i16 {}
impl Number for i32 {}
impl Number for i64 {}
impl Number for i128 {}
impl Number for isize {}
impl Number for u8 {}
impl Number for u16 {}
impl Number for u32 {}
impl Number for u64 {}
impl Number for u128 {}
impl Number for usize {}
impl Number for f32 {}
impl Number for f64 {}
/// Parses a string as a boolean value.
pub fn parse_bool(value: &str) -> Result<bool, EnvError> {
if value.to_lowercase() == "t" { return Ok(true) }
if value.to_lowercase() == "f" { return Ok(false) }
if value == "1" { return Ok(true) }
if value == "0" { return Ok(false) }
if value == "yes" { return Ok(true) }
if value == "no" { return Ok(false) }
match value.parse::<bool>() {
Ok(value) => Ok(value),
Err(e) => Err(EnvError::invalid("bool", value, &e.to_string()))
}
}
/// Parses a string as a number of the specified type.
pub fn parse_number<T: Number>(value: &str) -> Result<T, EnvError> {
match value.parse::<T>() {
Ok(value) => Ok(value),
Err(e) => Err(EnvError::invalid(type_name::<T>(), value, &e.to_string()))
}
}