Function figment::util::bool_from_str_or_int
source · pub fn bool_from_str_or_int<'de, D: Deserializer<'de>>(
de: D
) -> Result<bool, D::Error>
Expand description
A helper to deserialize 0/false
as false
and 1/true
as true
.
Serde’s default deserializer for bool
only parses the strings "true"
and
"false"
as the booleans true
and false
, respectively. By contract,
this function case-insensitively parses both the strings "true"/"false"
and the integers 1/0
as the booleans true/false
, respectively.
Example
use figment::Figment;
#[derive(serde::Deserialize)]
struct Config {
#[serde(deserialize_with = "figment::util::bool_from_str_or_int")]
cli_colors: bool,
}
let c0: Config = Figment::from(("cli_colors", "true")).extract().unwrap();
let c1: Config = Figment::from(("cli_colors", "TRUE")).extract().unwrap();
let c2: Config = Figment::from(("cli_colors", 1)).extract().unwrap();
assert_eq!(c0.cli_colors, true);
assert_eq!(c1.cli_colors, true);
assert_eq!(c2.cli_colors, true);
let c0: Config = Figment::from(("cli_colors", "false")).extract().unwrap();
let c1: Config = Figment::from(("cli_colors", "fAlSe")).extract().unwrap();
let c2: Config = Figment::from(("cli_colors", 0)).extract().unwrap();
assert_eq!(c0.cli_colors, false);
assert_eq!(c1.cli_colors, false);
assert_eq!(c2.cli_colors, false);