use std::collections::HashMap;
use std::default::Default;
use {Patch, Username, UserGroupId};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
#[serde(rename = "viewer")]
Viewer,
#[serde(rename = "editor")]
Editor,
}
fromstr_deserialize!(Role);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sharing<R> {
#[serde(skip_serializing_if="Option::is_none")]
pub anyone: Option<R>,
#[serde(default = "HashMap::default", skip_serializing_if="HashMap::is_empty")]
pub users: HashMap<Username, R>,
#[serde(default = "HashMap::default", skip_serializing_if="HashMap::is_empty")]
pub groups: HashMap<UserGroupId, R>,
}
pub type SharingState = Sharing<Role>;
pub type SharingPatch = Sharing<Option<Role>>;
impl Default for Sharing<Option<Role>> {
fn default() -> Self {
Sharing {
anyone: None,
users: HashMap::new(),
groups: HashMap::new(),
}
}
}
impl Patch for Sharing<Option<Role>> {}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::iter::{self, FromIterator};
use serde_json;
use super::{SharingPatch, SharingState, Role};
use {Username, UserGroupId};
static SAMPLE_1: &'static str = r#"{
"anyone": "viewer",
"users": {
"abirmingham": "editor",
"botha": "editor",
"dave": "editor",
"ehd": "editor",
"green": "editor",
"mikelly": "editor",
"mikem": "editor"
},
"groups": {}
}"#;
#[test]
fn deserialize_sharing() {
let parsed: SharingState = serde_json::from_str(SAMPLE_1).unwrap();
assert_eq!(Some(&Role::Editor),
parsed.users.get(&Username::new("ehd".to_string())));
}
#[test]
fn serialize_full_patch() {
let change = SharingPatch {
anyone: Some(None),
users: HashMap::from_iter(vec![(Username::new("ehd"), None),
(Username::new("mikelly"), Some(Role::Viewer))]),
groups: HashMap::from_iter(iter::once((UserGroupId::new("remote.pm-team"),
Some(Role::Editor)))),
};
println!("{}", serde_json::to_string_pretty(&change).unwrap());
}
#[test]
fn serialize_targeted() {
let change = SharingPatch {
users: HashMap::from_iter(iter::once((Username::new("ehd"), Some(Role::Editor)))),
..SharingPatch::default()
};
println!("{}", serde_json::to_string_pretty(&change).unwrap());
}
#[test]
fn noop_patch() {
assert_eq!("{}",
&serde_json::to_string(&SharingPatch::default()).unwrap());
assert_eq!(SharingPatch::default(),
serde_json::from_str::<SharingPatch>("{}").unwrap());
}
}