#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ProtectionFlag {
#[default]
Inherit,
Protected,
Unprotected,
}
impl ProtectionFlag {
pub fn as_attr(self) -> Option<&'static str> {
match self {
ProtectionFlag::Inherit => None,
ProtectionFlag::Protected => Some("1"),
ProtectionFlag::Unprotected => Some("0"),
}
}
pub fn from_py(value: &str) -> Self {
match value {
"inherit" => ProtectionFlag::Inherit,
v => match v.parse::<i64>() {
Ok(0) => ProtectionFlag::Unprotected,
_ => ProtectionFlag::Protected,
},
}
}
pub fn from_xml(value: Option<&str>) -> Self {
match value {
None => ProtectionFlag::Unprotected,
Some("") => ProtectionFlag::Protected,
Some("0") | Some("false") | Some("False") => ProtectionFlag::Unprotected,
Some(_) => ProtectionFlag::Protected,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Protection {
pub locked: ProtectionFlag,
pub hidden: ProtectionFlag,
}
impl Protection {
pub const PROTECTION_INHERIT: &'static str = "inherit";
pub fn new() -> Self {
Protection::default()
}
pub fn is_default(&self) -> bool {
self.locked == ProtectionFlag::Inherit && self.hidden == ProtectionFlag::Inherit
}
pub fn attributes(&self) -> Vec<(String, String)> {
let mut attrs = Vec::new();
if let Some(v) = self.locked.as_attr() {
attrs.push(("locked".to_string(), v.to_string()));
}
if let Some(v) = self.hidden.as_attr() {
attrs.push(("hidden".to_string(), v.to_string()));
}
attrs
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_inherit() {
let p = Protection::new();
assert_eq!(p.locked, ProtectionFlag::Inherit);
assert_eq!(p.hidden, ProtectionFlag::Inherit);
assert!(p.is_default());
assert!(p.attributes().is_empty());
}
#[test]
fn explicit_values_serialise() {
let p = Protection {
locked: ProtectionFlag::Protected,
hidden: ProtectionFlag::Unprotected,
};
let attrs = p.attributes();
assert!(attrs.contains(&("locked".to_string(), "1".to_string())));
assert!(attrs.contains(&("hidden".to_string(), "0".to_string())));
assert!(!p.is_default());
}
#[test]
fn xml_truthiness_matches_bool() {
assert_eq!(ProtectionFlag::from_xml(None), ProtectionFlag::Unprotected);
assert_eq!(
ProtectionFlag::from_xml(Some("")),
ProtectionFlag::Protected
);
assert_eq!(
ProtectionFlag::from_xml(Some("0")),
ProtectionFlag::Unprotected
);
assert_eq!(
ProtectionFlag::from_xml(Some("1")),
ProtectionFlag::Protected
);
assert_eq!(ProtectionFlag::from_py("inherit"), ProtectionFlag::Inherit);
}
}