wick_component/serde_util/
enum_repr.rs

1#[derive(Debug, ::serde::Serialize, ::serde::Deserialize, PartialEq)]
2#[serde(untagged)]
3/// A string or number to attempt deserializing from.
4#[allow(missing_docs, clippy::exhaustive_enums)]
5pub enum StringOrNum {
6  String(String),
7  Int(i64),
8  Float(f64),
9}
10
11/// Serialize a value as a string using its [std::fmt::Display] implementation.
12pub fn serialize<T, S>(val: &T, serializer: S) -> Result<S::Ok, S::Error>
13where
14  S: serde::Serializer,
15  T: std::fmt::Display,
16{
17  let s = val.to_string();
18  serializer.serialize_str(&s)
19}
20
21/// Deserialize a value from a number or string using its [std::str::FromStr] implementation.
22pub fn deserialize<'de, S, D>(deserializer: D) -> Result<S, D::Error>
23where
24  S: std::str::FromStr,
25  S::Err: std::fmt::Display,
26  D: serde::Deserializer<'de>,
27{
28  let s: StringOrNum = serde::Deserialize::deserialize(deserializer)?;
29  let s = match s {
30    StringOrNum::String(s) => s,
31    StringOrNum::Int(i) => i.to_string(),
32    StringOrNum::Float(i) => i.to_string(),
33  };
34  S::from_str(&s).map_err(serde::de::Error::custom)
35}