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
use header::WebSocketKey;
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::WebSocketAccept as WebSocketAcceptLL;
#[derive(PartialEq, Clone, Copy)]
pub struct WebSocketAccept(WebSocketAcceptLL);
impl Debug for WebSocketAccept {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for WebSocketAccept {
type Err = WebSocketError;
fn from_str(accept: &str) -> WebSocketResult<WebSocketAccept> {
Ok(WebSocketAccept(WebSocketAcceptLL::from_str(accept)?))
}
}
impl WebSocketAccept {
pub fn new(key: &WebSocketKey) -> WebSocketAccept {
WebSocketAccept(WebSocketAcceptLL::new(&key.0))
}
pub fn serialize(&self) -> String {
self.0.serialize()
}
}
impl Header for WebSocketAccept {
fn header_name() -> &'static str {
"Sec-WebSocket-Accept"
}
fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<WebSocketAccept> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for WebSocketAccept {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.serialize())
}
}
#[cfg(all(feature = "nightly", test))]
mod tests {
use super::*;
use header::{Headers, WebSocketKey};
use hyper::header::Header;
use std::str::FromStr;
use test;
#[test]
fn test_header_accept() {
let key = FromStr::from_str("dGhlIHNhbXBsZSBub25jZQ==").unwrap();
let accept = WebSocketAccept::new(&key);
let mut headers = Headers::new();
headers.set(accept);
assert_eq!(
&headers.to_string()[..],
"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n"
);
}
#[test]
fn test_header_from_str() {
let accept = WebSocketAccept::from_str("YSBzaW1wbGUgc2FtcGwgbm9uY2U=");
assert!(accept.is_ok());
let accept = WebSocketAccept::from_str("YSBzaG9ydCBub25jZQ==");
assert!(accept.is_err());
let accept = WebSocketAccept::from_str("YSByZWFsbHkgbWFsaWNpb3VzIG5vbmNl");
assert!(accept.is_err());
}
#[bench]
fn bench_header_accept_new(b: &mut test::Bencher) {
let key = WebSocketKey::new();
b.iter(|| {
let mut accept = WebSocketAccept::new(&key);
test::black_box(&mut accept);
});
}
#[bench]
fn bench_header_accept_parse(b: &mut test::Bencher) {
let value = vec![b"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=".to_vec()];
b.iter(|| {
let mut accept: WebSocketAccept = Header::parse_header(&value[..]).unwrap();
test::black_box(&mut accept);
});
}
#[bench]
fn bench_header_accept_format(b: &mut test::Bencher) {
let value = vec![b"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=".to_vec()];
let val: WebSocketAccept = Header::parse_header(&value[..]).unwrap();
b.iter(|| {
format!("{}", val.serialize());
});
}
}