cmd_args/arg/
value.rs

1use std::fmt;
2use crate::arg;
3
4/// Possible argument values.
5pub enum Value {
6    Bool { value: bool },
7    Str { value: String },
8    Int { value: i32 },
9    Float { value: f64 },
10}
11
12impl Value {
13    /// Parse argument value from string.
14    pub fn parse(arg_type: &arg::Type, input: &str) -> crate::parser::Result<Value> {
15        match arg_type {
16            arg::Type::Bool => Ok(Value::Bool {
17                value: input.parse()?
18            }),
19            arg::Type::Str => Ok(Value::Str {
20                value: String::from(input)
21            }),
22            arg::Type::Int => Ok(Value::Int {
23                value: input.parse()?
24            }),
25            arg::Type::Float => Ok(Value::Float {
26                value: input.parse()?
27            }),
28        }
29    }
30
31    /// Get the boolean typed value.
32    pub fn bool(&self) -> Option<bool> {
33        match self {
34            Value::Bool { value } => Some(*value),
35            _ => None,
36        }
37    }
38
39    /// Get the string typed value.
40    pub fn str(&self) -> Option<&String> {
41        match self {
42            Value::Str { value } => Some(value),
43            _ => None,
44        }
45    }
46
47    /// Get the integer typed value.
48    pub fn int(&self) -> Option<i32> {
49        match self {
50            Value::Int { value } => Some(*value),
51            _ => None,
52        }
53    }
54
55    /// Get the float typed value.
56    pub fn float(&self) -> Option<f64> {
57        match self {
58            Value::Float { value } => Some(*value),
59            _ => None,
60        }
61    }
62}
63
64impl fmt::Display for Value {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "{}", match self {
67            Value::Bool { value } => value.to_string(),
68            Value::Str { value } => value.to_string(),
69            Value::Int { value } => value.to_string(),
70            Value::Float { value } => value.to_string(),
71        })
72    }
73}