cmd_args/option/
value.rs

1use std::fmt;
2use crate::option;
3
4/// Possible values for a CLI option.
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 option value from string.
14    pub fn parse(option_type: &option::Type, input: &str) -> crate::parser::Result<Value> {
15        match option_type {
16            option::Type::Bool { default: _ } => Ok(Value::Bool {
17                value: input.parse()?
18            }),
19            option::Type::Str { default: _ } => Ok(Value::Str {
20                value: String::from(input)
21            }),
22            option::Type::Int { default: _ } => Ok(Value::Int {
23                value: input.parse()?
24            }),
25            option::Type::Float { default: _ } => Ok(Value::Float {
26                value: input.parse()?
27            }),
28        }
29    }
30
31    /// Create option value from default option value.
32    pub fn from_default(option_type: &option::Type) -> Value {
33        match option_type {
34            option::Type::Bool { default } => Value::Bool {
35                value: *default
36            },
37            option::Type::Str { default } => Value::Str {
38                value: default.clone()
39            },
40            option::Type::Int { default } => Value::Int {
41                value: *default
42            },
43            option::Type::Float { default } => Value::Float {
44                value: *default
45            },
46        }
47    }
48
49    /// Get the boolean typed value.
50    pub fn bool(&self) -> Option<bool> {
51        match self {
52            Value::Bool { value } => Some(*value),
53            _ => None,
54        }
55    }
56
57    /// Get the string typed value.
58    pub fn str(&self) -> Option<&String> {
59        match self {
60            Value::Str { value } => Some(value),
61            _ => None,
62        }
63    }
64
65    /// Get the integer typed value.
66    pub fn int(&self) -> Option<i32> {
67        match self {
68            Value::Int { value } => Some(*value),
69            _ => None,
70        }
71    }
72
73    /// Get the float typed value.
74    pub fn float(&self) -> Option<f64> {
75        match self {
76            Value::Float { value } => Some(*value),
77            _ => None,
78        }
79    }
80}
81
82impl fmt::Display for Value {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "{}", match self {
85            Value::Bool { value } => value.to_string(),
86            Value::Str { value } => value.to_string(),
87            Value::Int { value } => value.to_string(),
88            Value::Float { value } => value.to_string(),
89        })
90    }
91}