Made Url serde-compatible

This commit is contained in:
daladim 2021-02-24 17:23:20 +01:00
parent 5e6eb6863c
commit 61784a9c55
2 changed files with 29 additions and 1 deletions

View file

@ -2,6 +2,7 @@ use std::convert::TryFrom;
use std::error::Error; use std::error::Error;
use url::Url; use url::Url;
use serde::{Deserialize, Serialize};
use crate::task::Task; use crate::task::Task;
use crate::task::TaskId; use crate::task::TaskId;
@ -9,6 +10,7 @@ use crate::task::TaskId;
use bitflags::bitflags; use bitflags::bitflags;
bitflags! { bitflags! {
#[derive(Serialize, Deserialize)]
pub struct SupportedComponents: u8 { pub struct SupportedComponents: u8 {
/// An event, such as a calendar meeting /// An event, such as a calendar meeting
const EVENT = 1; const EVENT = 1;
@ -45,9 +47,10 @@ impl TryFrom<minidom::Element> for SupportedComponents {
/// A Caldav Calendar /// A Caldav Calendar
#[derive(Clone, Debug)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Calendar { pub struct Calendar {
name: String, name: String,
#[serde(with="crate::utils::url_serde")]
url: Url, url: Url,
supported_components: SupportedComponents, supported_components: SupportedComponents,

View file

@ -1,6 +1,7 @@
///! Some utility functions ///! Some utility functions
use minidom::Element; use minidom::Element;
use serde::Deserialize;
/// Walks an XML tree and returns every element that has the given name /// Walks an XML tree and returns every element that has the given name
pub fn find_elems<S: AsRef<str>>(root: &Element, searched_name: S) -> Vec<&Element> { pub fn find_elems<S: AsRef<str>>(root: &Element, searched_name: S) -> Vec<&Element> {
@ -50,3 +51,27 @@ pub fn print_xml(element: &Element) {
writer.write(&[0x0a]); writer.write(&[0x0a]);
} }
/// Used to (de)serialize url::Url
pub mod url_serde{
use super::*;
pub fn deserialize<'de, D>(deserializer: D) -> Result<url::Url, D::Error>
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<S>(u: &url::Url, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str( u.as_str() )
}
}