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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use std::str::FromStr;
use std::fmt::{self, Display};
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
pub weak: bool,
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[..];
if slice.is_empty() || !slice.ends_with("\"") {
return Err(());
}
if slice.char_at(0) == '"' {
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}