[pve-devel] [PATCH proxmox 1/1] serde: add string_as_bool module for boolean string parsing
Gabriel Goller
g.goller at proxmox.com
Fri Mar 28 18:12:49 CET 2025
Add new module to proxmox-serde that parses boolean values from various
string formats. Provides parse_bool function supporting common
representations (0/1, true/false, on/off, yes/no) along with
serializer/deserializer for these formats.
Note: this was copied over from proxmox-ve-config/firewall.
Signed-off-by: Gabriel Goller <g.goller at proxmox.com>
Co-authored-by: Stefan Hanreich <s.hanreich at proxmox.com>
---
proxmox-serde/src/lib.rs | 84 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 84 insertions(+)
diff --git a/proxmox-serde/src/lib.rs b/proxmox-serde/src/lib.rs
index c162834905c2..705ad430c953 100644
--- a/proxmox-serde/src/lib.rs
+++ b/proxmox-serde/src/lib.rs
@@ -260,3 +260,87 @@ pub mod string_as_base64url_nopad {
String::from_utf8(bytes).map_err(|err| Error::custom(err.to_string()))
}
}
+
+/// Parse a bool from a string
+pub mod string_as_bool {
+ use std::fmt;
+
+ use serde::{
+ de::{Deserializer, Error, Visitor},
+ ser::Serializer,
+ };
+
+ /// Parse a boolean.
+ ///
+ /// values that parse as [`false`]: 0, false, off, no
+ /// values that parse as [`true`]: 1, true, on, yes
+ ///
+ /// # Examples
+ /// ```ignore
+ /// assert_eq!(parse_bool("false"), Ok(false));
+ /// assert_eq!(parse_bool("on"), Ok(true));
+ /// assert!(parse_bool("proxmox").is_err());
+ /// ```
+ pub fn parse_bool(value: &str) -> Result<bool, anyhow::Error> {
+ Ok(
+ if value == "0"
+ || value.eq_ignore_ascii_case("false")
+ || value.eq_ignore_ascii_case("off")
+ || value.eq_ignore_ascii_case("no")
+ {
+ false
+ } else if value == "1"
+ || value.eq_ignore_ascii_case("true")
+ || value.eq_ignore_ascii_case("on")
+ || value.eq_ignore_ascii_case("yes")
+ {
+ true
+ } else {
+ anyhow::bail!("not a boolean: {value:?}");
+ },
+ )
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(
+ deserializer: D,
+ ) -> Result<Option<bool>, D::Error> {
+ struct V;
+
+ impl<'de> Visitor<'de> for V {
+ type Value = Option<bool>;
+
+ fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str("a boolean-like value")
+ }
+
+ fn visit_bool<E: Error>(self, v: bool) -> Result<Self::Value, E> {
+ Ok(Some(v))
+ }
+
+ fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
+ parse_bool(v).map_err(E::custom).map(Some)
+ }
+
+ fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
+ Ok(None)
+ }
+
+ fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_any(self)
+ }
+ }
+
+ deserializer.deserialize_any(V)
+ }
+
+ pub fn serialize<S: Serializer>(from: &Option<bool>, serializer: S) -> Result<S::Ok, S::Error> {
+ if *from == Some(true) {
+ serializer.serialize_str("1")
+ } else {
+ serializer.serialize_str("0")
+ }
+ }
+}
--
2.39.5
More information about the pve-devel
mailing list