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
146
147
148
149
150
use std::collections::HashMap;
use std::fmt;
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use uuid::Uuid;
use regex::Regex;
const ID_REGEXP: &'static str =
r"^((?i)[A-F0-9]{8}\-[A-F0-9]{4}\-4[A-F0-9]{3}\-[89AB][A-F0-9]{3}\-[A-F0-9]{12})$";
#[derive(PartialEq, Debug, Eq, Hash, Clone)]
pub struct Id(String);
impl Id {
pub fn random() -> Id {
Id(Uuid::new_v4().to_string())
}
pub fn value(&self) -> &str {
&*self.0
}
}
pub struct IdExtractor(Regex);
impl IdExtractor {
pub fn new() -> IdExtractor {
match Regex::new(ID_REGEXP) {
Ok(regex) => IdExtractor(regex),
_ => unreachable!(),
}
}
pub fn parse(&self, s: &str) -> Option<Id> {
let caps = self.0.captures(s);
caps.and_then(|c| c.get(1).map(|r| Id(r.as_str().to_owned())))
}
}
impl Encodable for Id {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_str(&*self.0)
}
}
impl Decodable for Id {
fn decode<S: Decoder>(s: &mut S) -> Result<Id, S::Error> {
s.read_str().map(|s| Id(s.to_owned()))
}
}
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(PartialEq, Debug, Eq, RustcDecodable, RustcEncodable)]
pub struct Request {
pub content_length: Option<u64>,
pub content_type: Option<String>,
pub time: i64,
pub method: String,
pub path: String,
pub body: Option<String>,
pub headers: HashMap<String, Vec<String>>,
pub query_string: HashMap<String, Vec<String>>,
}
#[derive(PartialEq, Debug, Eq, RustcDecodable, RustcEncodable)]
pub struct BinSummary {
pub id: Id,
pub request_count: usize,
}
#[cfg(test)]
mod tests {
use super::*;
use rustc_serialize::json;
#[test]
fn test_idextractor_instantiation() {
let _ = IdExtractor::new();
}
#[test]
fn test_id_json_encoding_decoding() {
let id = Id::random();
let encoded = json::encode(&id).unwrap();
let decoded: Id = json::decode(&*encoded).unwrap();
assert_eq!(decoded, id);
assert_eq!(format!("\"{}\"", id), encoded);
}
}