feat(types): implement a serializable regex type

This commit is contained in:
Phil Booth 2018-12-06 18:40:34 +00:00
Родитель 5eeb3b3a6b
Коммит 83d46aecd6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 36FBB106F9C32516
3 изменённых файлов: 62 добавлений и 0 удалений

Просмотреть файл

@ -78,4 +78,5 @@ pub mod error;
pub mod headers;
pub mod logging;
pub mod provider;
pub mod regex;
pub mod validate;

46
src/types/regex/mod.rs Normal file
Просмотреть файл

@ -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<D>(deserializer: D) -> Result<Self, D::Error>
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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.0.as_str())
}
}

15
src/types/regex/test.rs Normal file
Просмотреть файл

@ -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(&regex).unwrap();
assert_eq!(serialized, "\"foo\"");
let regex: SerializableRegex = serde_json::from_str(&serialized).unwrap();
assert_eq!(regex.0.as_str(), "foo");
}