mirror of
https://github.com/darwincereska/envkit.git
synced 2026-06-11 10:23:23 -05:00
feat: updated bool parsing and added tests
This commit is contained in:
@@ -3,6 +3,7 @@ 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 {}
|
||||
@@ -20,11 +21,14 @@ 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),
|
||||
@@ -32,6 +36,7 @@ pub fn parse_bool(value: &str) -> Result<bool, EnvError> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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),
|
||||
|
||||
Reference in New Issue
Block a user