diff options
Diffstat (limited to 'src/skaldpress/metadata_parser.rs')
-rw-r--r-- | src/skaldpress/metadata_parser.rs | 56 |
1 files changed, 51 insertions, 5 deletions
diff --git a/src/skaldpress/metadata_parser.rs b/src/skaldpress/metadata_parser.rs index 4d6e352..a2abcc2 100644 --- a/src/skaldpress/metadata_parser.rs +++ b/src/skaldpress/metadata_parser.rs @@ -1,9 +1,14 @@ +#[cfg(feature = "time")] +use chrono::DateTime; +use std::cmp::Ordering; use std::collections::HashMap; use std::fmt; -#[derive(Debug)] +#[derive(Eq, PartialEq, Debug)] pub enum YamlValue { Scalar(String), + Integer(i64), + Date(String, i64), List(Vec<String>), } @@ -11,6 +16,8 @@ impl fmt::Display for YamlValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { YamlValue::Scalar(x) => write!(f, "{}", x), + YamlValue::Integer(x) => write!(f, "{}", x), + YamlValue::Date(x, _) => write!(f, "{}", x), YamlValue::List(_l) => write!(f, "List<String>"), } } @@ -22,11 +29,53 @@ impl TryFrom<&YamlValue> for String { fn try_from(s: &YamlValue) -> Result<String, String> { match s { YamlValue::Scalar(s) => Ok(String::from(s)), + YamlValue::Integer(s) => Ok(s.to_string()), + YamlValue::Date(s, _) => Ok(s.to_string()), YamlValue::List(_) => Err(String::from("List value cannot be turned into string")), } } } +impl PartialOrd for YamlValue { + fn partial_cmp(&self, other: &YamlValue) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for YamlValue { + fn cmp(&self, other: &YamlValue) -> Ordering { + if let YamlValue::Integer(a_int) = self { + if let YamlValue::Integer(b_int) = other { + return a_int.cmp(b_int); + } + } + if let YamlValue::Scalar(a_str) = self { + if let YamlValue::Scalar(b_str) = other { + return a_str.cmp(b_str); + } + } + if let YamlValue::Date(_, a_timestamp) = self { + if let YamlValue::Date(_, b_timestamp) = other { + return a_timestamp.cmp(b_timestamp); + } + } + self.to_string().cmp(&other.to_string()) + } +} + +fn str_to_yaml_value(in_str: &str) -> YamlValue { + let in_str = in_str.trim(); + if let Ok(int) = in_str.parse::<i64>() { + return YamlValue::Integer(int); + } + #[cfg(feature = "time")] + if let Ok(dt) = DateTime::parse_from_rfc3339(in_str) { + return YamlValue::Date(in_str.to_string(), dt.timestamp()); + } + + YamlValue::Scalar(in_str.to_string()) +} + /// Extract a beginning YAML block of a input-string into a HashMap pub fn extract_parse_yaml_metadata<'a>( markdown: &'a str, @@ -64,10 +113,7 @@ pub fn extract_parse_yaml_metadata<'a>( } current_key = Some(key.trim().to_string()); if !value.trim().is_empty() { - yaml_map.insert( - current_key.clone().unwrap(), - YamlValue::Scalar(value.trim().to_string()), - ); + yaml_map.insert(current_key.clone().unwrap(), str_to_yaml_value(value)); current_key = None; } } |