Skip to content

Commit 79883ff

Browse files
Merge pull request #137 from joelgallant/parse-env-numbers
Adds 'try_parsing' option for Environment
2 parents 73721d3 + cfd385e commit 79883ff

File tree

2 files changed

+372
-5
lines changed

2 files changed

+372
-5
lines changed

src/env.rs

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ pub struct Environment {
2323

2424
/// Ignore empty env values (treat as unset).
2525
ignore_empty: bool,
26+
27+
/// Parses booleans, integers and floats if they're detected (can be safely parsed).
28+
try_parsing: bool,
2629
}
2730

2831
impl Environment {
@@ -51,6 +54,13 @@ impl Environment {
5154
self.ignore_empty = ignore;
5255
self
5356
}
57+
58+
/// Note: enabling `try_parsing` can reduce performance it will try and parse
59+
/// each environment variable 3 times (bool, i64, f64)
60+
pub fn try_parsing(mut self, try_parsing: bool) -> Self {
61+
self.try_parsing = try_parsing;
62+
self
63+
}
5464
}
5565

5666
impl Default for Environment {
@@ -59,6 +69,7 @@ impl Default for Environment {
5969
prefix: None,
6070
separator: None,
6171
ignore_empty: false,
72+
try_parsing: false,
6273
}
6374
}
6475
}
@@ -115,10 +126,22 @@ impl Source for Environment {
115126
key = key.replace(separator, ".");
116127
}
117128

118-
m.insert(
119-
key.to_lowercase(),
120-
Value::new(Some(&uri), ValueKind::String(value)),
121-
);
129+
let value = if self.try_parsing {
130+
// convert to lowercase because bool parsing expects all lowercase
131+
if let Ok(parsed) = value.to_lowercase().parse::<bool>() {
132+
ValueKind::Boolean(parsed)
133+
} else if let Ok(parsed) = value.parse::<i64>() {
134+
ValueKind::Integer(parsed)
135+
} else if let Ok(parsed) = value.parse::<f64>() {
136+
ValueKind::Float(parsed)
137+
} else {
138+
ValueKind::String(value)
139+
}
140+
} else {
141+
ValueKind::String(value)
142+
};
143+
144+
m.insert(key.to_lowercase(), Value::new(Some(&uri), value));
122145
}
123146

124147
Ok(m)

0 commit comments

Comments
 (0)