diff --git a/crates/tor-config/semver.md b/crates/tor-config/semver.md new file mode 100644 index 000000000..f84bc0424 --- /dev/null +++ b/crates/tor-config/semver.md @@ -0,0 +1 @@ +ADDED: `ItemOrBool` diff --git a/crates/tor-config/src/misc.rs b/crates/tor-config/src/misc.rs index 2464e96de..a54f71623 100644 --- a/crates/tor-config/src/misc.rs +++ b/crates/tor-config/src/misc.rs @@ -383,6 +383,31 @@ impl TryFrom for ListenItem { } } +/// A deserializable value or bool. +#[derive(Serialize, Deserialize, Debug)] +#[allow(clippy::exhaustive_enums)] // we will add variants very rarely if ever +#[serde(untagged, bound = "T: Serialize, for<'de2> T: Deserialize<'de2>")] +pub enum ItemOrBool +where + T: std::fmt::Debug + Serialize, + for<'de2> T: Deserialize<'de2>, +{ + /// A `T` item. + Item(T), + /// A boolean value + Bool(bool), +} + +impl Default for ItemOrBool +where + T: std::fmt::Debug + Serialize, + for<'de2> T: Deserialize<'de2>, +{ + fn default() -> Self { + Self::Bool(true) + } +} + #[cfg(test)] mod test { // @@ begin test lint list maintained by maint/add_warning @@ @@ -407,6 +432,9 @@ mod test { #[serde(default)] listen: Option, + + #[serde(default)] + enabled_or_string: ItemOrBool, } #[test] @@ -555,4 +583,35 @@ mod test { chk_err_1("need actual addr/port", "did not match any variant", "true"); chk_err("did not match any variant", r#"listen = [ [] ]"#); } + + #[test] + fn enabled_or_string() { + use ItemOrBool as IOB; + + let chk = |iob: IOB, s| { + let tc: TestConfigFile = toml::from_str(s).expect(s); + assert_eq!( + format!("{:?}", iob), + format!("{:?}", tc.enabled_or_string), + "{:?}", + s + ); + }; + + chk(IOB::Bool(false), r#"enabled_or_string = false"#); + chk(IOB::Bool(true), r#"enabled_or_string = true"#); + chk( + IOB::Item("not a bool".into()), + r#"enabled_or_string = "not a bool""#, + ); + + let chk_e = |s| { + let tc: Result = toml::from_str(s); + let _ = tc.expect_err(s); + }; + + chk_e(r#"enabled_or_string = 1"#); + chk_e(r#"enabled_or_string = []"#); + chk_e(r#"enabled_or_string = {}"#); + } }