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
use hyper;
use hyper::header::parsing::from_one_raw_str;
use hyper::header::{Header, HeaderFormat};
use result::{WebSocketError, WebSocketResult};
use std::fmt::{self, Debug};
use std::str::FromStr;
use websocket_base::header::WebSocketKey as WebSocketKeyLL;
#[derive(PartialEq, Clone, Copy, Default)]
pub struct WebSocketKey(pub WebSocketKeyLL);
impl Debug for WebSocketKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for WebSocketKey {
type Err = WebSocketError;
fn from_str(key: &str) -> WebSocketResult<WebSocketKey> {
Ok(WebSocketKey(WebSocketKeyLL::from_str(key)?))
}
}
impl WebSocketKey {
pub fn new() -> WebSocketKey {
WebSocketKey(WebSocketKeyLL::new())
}
pub fn serialize(&self) -> String {
self.0.serialize()
}
pub fn from_array(a: [u8; 16]) -> WebSocketKey {
WebSocketKey(WebSocketKeyLL(a))
}
}
impl Header for WebSocketKey {
fn header_name() -> &'static str {
"Sec-WebSocket-Key"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<WebSocketKey> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for WebSocketKey {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.serialize())
}
}
#[cfg(all(feature = "nightly", test))]
mod tests {
use super::*;
use hyper::header::Header;
use test;
#[test]
fn test_header_key() {
use header::Headers;
let extensions = WebSocketKey::from_array([65; 16]);
let mut headers = Headers::new();
headers.set(extensions);
assert_eq!(
&headers.to_string()[..],
"Sec-WebSocket-Key: QUFBQUFBQUFBQUFBQUFBQQ==\r\n"
);
}
#[test]
fn test_header_from_str() {
let key = WebSocketKey::from_str("YSByZWFsbCBnb29kIGtleQ==");
assert!(key.is_ok());
let key = WebSocketKey::from_str("YSBzaG9ydCBrZXk=");
assert!(key.is_err());
let key = WebSocketKey::from_str("YSB2ZXJ5IHZlcnkgbG9uZyBrZXk=");
assert!(key.is_err());
}
#[bench]
fn bench_header_key_new(b: &mut test::Bencher) {
b.iter(|| {
let mut key = WebSocketKey::new();
test::black_box(&mut key);
});
}
#[bench]
fn bench_header_key_parse(b: &mut test::Bencher) {
let value = vec![b"QUFBQUFBQUFBQUFBQUFBQQ==".to_vec()];
b.iter(|| {
let mut key: WebSocketKey = Header::parse_header(&value[..]).unwrap();
test::black_box(&mut key);
});
}
#[bench]
fn bench_header_key_format(b: &mut test::Bencher) {
let value = vec![b"QUFBQUFBQUFBQUFBQUFBQQ==".to_vec()];
let val: WebSocketKey = Header::parse_header(&value[..]).unwrap();
b.iter(|| {
format!("{}", val.serialize());
});
}
}