1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::{cmp, fmt, str};
use std::collections::HashSet;
#[derive(PartialEq, Eq, Clone)]
pub struct Scope {
tokens: HashSet<String>,
}
impl Scope {
fn invalid_scope_char(ch: char) -> bool {
match ch {
'\x21' => false,
ch if ch >= '\x23' && ch <= '\x5b' => false,
ch if ch >= '\x5d' && ch <= '\x7e' => false,
' ' => false,
_ => true,
}
}
pub fn privileged_to(&self, rhs: &Scope) -> bool {
self.tokens.is_subset(&rhs.tokens)
}
}
#[derive(Debug)]
pub struct ParseScopeErr;
impl str::FromStr for Scope {
type Err = ParseScopeErr;
fn from_str(string: &str) -> Result<Scope, ParseScopeErr> {
if string.find(Scope::invalid_scope_char).is_some() {
return Err(ParseScopeErr)
}
let tokens = string.split(' ').filter(|s| s.len() > 0);
Ok(Scope{ tokens: tokens.map(|r| r.to_string()).collect() })
}
}
impl fmt::Display for Scope {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let output = self.tokens.iter()
.map(|s| s.as_str())
.collect::<Vec<&str>>()
.join(" ");
fmt.write_str(&output)
}
}
impl cmp::PartialOrd for Scope {
fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
let intersect_count = self.tokens.intersection(&rhs.tokens).count();
if intersect_count == self.tokens.len() && intersect_count == rhs.tokens.len() {
Some(cmp::Ordering::Equal)
} else if intersect_count == self.tokens.len() {
Some(cmp::Ordering::Less)
} else if intersect_count == rhs.tokens.len() {
Some(cmp::Ordering::Greater)
} else {
None
}
}
}