diff --git a/src/types/mod.rs b/src/types/mod.rs index 6581bf0..ca10e35 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -78,4 +78,5 @@ pub mod error; pub mod headers; pub mod logging; pub mod provider; +pub mod regex; pub mod validate; diff --git a/src/types/regex/mod.rs b/src/types/regex/mod.rs new file mode 100644 index 0000000..a83c8e8 --- /dev/null +++ b/src/types/regex/mod.rs @@ -0,0 +1,46 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, you can obtain one at https://mozilla.org/MPL/2.0/. + +//! Regex types. + +use regex::Regex; +use serde::{ + de::{Deserialize, Deserializer, Error as SerdeError, Unexpected}, + ser::{Serialize, Serializer}, +}; + +#[cfg(test)] +mod test; + +/// A regex wrapper +/// that can be (de)serialized. +#[derive(Clone, Debug)] +pub struct SerializableRegex(pub Regex); + +impl<'d> Deserialize<'d> for SerializableRegex { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'d>, + { + let value: String = Deserialize::deserialize(deserializer)?; + Regex::new(&value) + .map(SerializableRegex) + .map_err(|_| D::Error::invalid_value(Unexpected::Str(&value), &"regular expression")) + } +} + +impl PartialEq for SerializableRegex { + fn eq(&self, rhs: &Self) -> bool { + self.0.as_str() == rhs.0.as_str() + } +} + +impl Serialize for SerializableRegex { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(self.0.as_str()) + } +} diff --git a/src/types/regex/test.rs b/src/types/regex/test.rs new file mode 100644 index 0000000..038b054 --- /dev/null +++ b/src/types/regex/test.rs @@ -0,0 +1,15 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, you can obtain one at https://mozilla.org/MPL/2.0/. + +use super::*; + +#[test] +fn serialize_deserialize() { + let regex = SerializableRegex(Regex::new("foo").unwrap()); + let serialized = serde_json::to_string(®ex).unwrap(); + assert_eq!(serialized, "\"foo\""); + + let regex: SerializableRegex = serde_json::from_str(&serialized).unwrap(); + assert_eq!(regex.0.as_str(), "foo"); +}