From 61784a9c5567335df99f5d7c59e54c5f356d5240 Mon Sep 17 00:00:00 2001 From: daladim Date: Wed, 24 Feb 2021 17:23:20 +0100 Subject: [PATCH] Made Url serde-compatible --- src/calendar.rs | 5 ++++- src/utils.rs | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/calendar.rs b/src/calendar.rs index 251cbe7..51e72ed 100644 --- a/src/calendar.rs +++ b/src/calendar.rs @@ -2,6 +2,7 @@ use std::convert::TryFrom; use std::error::Error; use url::Url; +use serde::{Deserialize, Serialize}; use crate::task::Task; use crate::task::TaskId; @@ -9,6 +10,7 @@ use crate::task::TaskId; use bitflags::bitflags; bitflags! { + #[derive(Serialize, Deserialize)] pub struct SupportedComponents: u8 { /// An event, such as a calendar meeting const EVENT = 1; @@ -45,9 +47,10 @@ impl TryFrom for SupportedComponents { /// A Caldav Calendar -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Calendar { name: String, + #[serde(with="crate::utils::url_serde")] url: Url, supported_components: SupportedComponents, diff --git a/src/utils.rs b/src/utils.rs index fa80b76..7f54b35 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,6 +1,7 @@ ///! Some utility functions use minidom::Element; +use serde::Deserialize; /// Walks an XML tree and returns every element that has the given name pub fn find_elems>(root: &Element, searched_name: S) -> Vec<&Element> { @@ -50,3 +51,27 @@ pub fn print_xml(element: &Element) { writer.write(&[0x0a]); } + + +/// Used to (de)serialize url::Url +pub mod url_serde{ + use super::*; + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de> + { + let s = String::deserialize(deserializer)?; + match url::Url::parse(&s) { + Ok(u) => Ok(u), + Err(_) => { return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&s), &"Expected an url")); } + } + } + + pub fn serialize(u: &url::Url, serializer: S) -> Result + where + S: serde::ser::Serializer, + { + serializer.serialize_str( u.as_str() ) + } +}