diff --git a/src/schema.rs b/src/schema.rs index 6e9c6af..b64e769 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use crate::*; use indexmap::IndexMap; use serde::{Deserialize, Serialize}; @@ -228,6 +230,18 @@ pub enum NumberFormat { Double, } +impl FromStr for NumberFormat { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "float" => Ok(Self::Float), + "double" => Ok(Self::Double), + _ => Err(()), + } + } +} + #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum IntegerFormat { @@ -235,17 +249,43 @@ pub enum IntegerFormat { Int64, } +impl FromStr for IntegerFormat { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "int32" => Ok(Self::Int32), + "int64" => Ok(Self::Int64), + _ => Err(()), + } + } +} + #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum StringFormat { Date, - #[serde(rename = "date-time")] DateTime, Password, Byte, Binary, } +impl FromStr for StringFormat { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "date" => Ok(Self::Date), + "date-time" => Ok(Self::DateTime), + "password" => Ok(Self::Password), + "byte" => Ok(Self::Byte), + "binary" => Ok(Self::Binary), + _ => Err(()), + } + } +} + #[cfg(test)] mod tests { use serde_json::json; diff --git a/src/variant_or.rs b/src/variant_or.rs index 9b2fdbc..a7f80dd 100644 --- a/src/variant_or.rs +++ b/src/variant_or.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] @@ -7,6 +9,18 @@ pub enum VariantOrUnknown { Unknown(String), } +impl From for VariantOrUnknown +where + T: FromStr, +{ + fn from(s: String) -> Self { + match T::from_str(&s) { + Ok(t) => Self::Item(t), + Err(_) => Self::Unknown(s), + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum VariantOrUnknownOrEmpty { @@ -29,3 +43,39 @@ impl Default for VariantOrUnknownOrEmpty { VariantOrUnknownOrEmpty::Empty } } + +impl From> for VariantOrUnknownOrEmpty +where + T: FromStr, +{ + fn from(v: Option) -> Self { + match v { + Some(s) => match T::from_str(&s) { + Ok(t) => VariantOrUnknownOrEmpty::Item(t), + Err(_) => VariantOrUnknownOrEmpty::Unknown(s), + }, + None => VariantOrUnknownOrEmpty::Empty, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{StringFormat, VariantOrUnknownOrEmpty}; + + #[test] + fn test_variant_from() { + assert_eq!( + VariantOrUnknownOrEmpty::::from(None), + VariantOrUnknownOrEmpty::Empty, + ); + assert_eq!( + VariantOrUnknownOrEmpty::::from(Some("date".to_string())), + VariantOrUnknownOrEmpty::Item(StringFormat::Date), + ); + assert_eq!( + VariantOrUnknownOrEmpty::::from(Some("yolo".to_string())), + VariantOrUnknownOrEmpty::Unknown("yolo".to_string()), + ); + } +}