Make Scopes deserializable

master
Ondřej Hruška 5 years ago committed by Paul Woolcock
parent acb87aba9c
commit 98932ac5d6
  1. 30
      src/scopes.rs

@ -9,6 +9,8 @@ use std::{
use serde::ser::{Serialize, Serializer}; use serde::ser::{Serialize, Serializer};
use errors::Error; use errors::Error;
use serde::{Deserialize, Deserializer};
use serde::de::{self, Visitor};
/// Represents a set of OAuth scopes /// Represents a set of OAuth scopes
/// ///
@ -52,6 +54,29 @@ impl Serialize for Scopes {
} }
} }
struct DeserializeScopesVisitor;
impl<'de> Visitor<'de> for DeserializeScopesVisitor {
type Value = Scopes;
fn expecting(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(formatter, "space separated scopes")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error
{
Scopes::from_str(v).map_err(de::Error::custom)
}
}
impl<'de> Deserialize<'de> for Scopes {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de> {
deserializer.deserialize_str(DeserializeScopesVisitor)
}
}
impl Scopes { impl Scopes {
/// Represents all available oauth scopes: "read write follow push" /// Represents all available oauth scopes: "read write follow push"
/// ///
@ -725,7 +750,7 @@ mod tests {
} }
#[test] #[test]
fn test_scopes_serialize() { fn test_scopes_serialize_deserialize() {
let tests = [ let tests = [
( (
Scopes::read_all() | Scopes::write(Write::Notifications) | Scopes::follow(), Scopes::read_all() | Scopes::write(Write::Notifications) | Scopes::follow(),
@ -738,6 +763,9 @@ mod tests {
let ser = serde_json::to_string(&a).expect("Couldn't serialize Scopes"); let ser = serde_json::to_string(&a).expect("Couldn't serialize Scopes");
let expected = format!("\"{}\"", b); let expected = format!("\"{}\"", b);
assert_eq!(&ser, &expected); assert_eq!(&ser, &expected);
let des : Scopes = serde_json::from_str(&ser).expect("Couldn't deserialize Scopes");
assert_eq!(&des, a);
} }
} }

Loading…
Cancel
Save