websocket/header/
protocol.rs

1use hyper;
2use hyper::header::parsing::{fmt_comma_delimited, from_comma_delimited};
3use hyper::header::{Header, HeaderFormat};
4use std::fmt;
5use std::ops::Deref;
6
7// TODO: only allow valid protocol names to be added
8
9/// Represents a Sec-WebSocket-Protocol header
10#[derive(PartialEq, Clone, Debug)]
11pub struct WebSocketProtocol(pub Vec<String>);
12
13impl Deref for WebSocketProtocol {
14	type Target = Vec<String>;
15	fn deref(&self) -> &Vec<String> {
16		&self.0
17	}
18}
19
20impl Header for WebSocketProtocol {
21	fn header_name() -> &'static str {
22		"Sec-WebSocket-Protocol"
23	}
24
25	fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<WebSocketProtocol> {
26		from_comma_delimited(raw).map(WebSocketProtocol)
27	}
28}
29
30impl HeaderFormat for WebSocketProtocol {
31	fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
32		let WebSocketProtocol(ref value) = *self;
33		fmt_comma_delimited(fmt, &value[..])
34	}
35}
36
37impl fmt::Display for WebSocketProtocol {
38	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
39		self.fmt_header(fmt)
40	}
41}
42
43#[cfg(all(feature = "nightly", test))]
44mod tests {
45	use super::*;
46	use hyper::header::Header;
47	use test;
48
49	#[test]
50	fn test_header_protocol() {
51		use crate::header::Headers;
52
53		let protocol = WebSocketProtocol(vec!["foo".to_string(), "bar".to_string()]);
54		let mut headers = Headers::new();
55		headers.set(protocol);
56
57		assert_eq!(
58			&headers.to_string()[..],
59			"Sec-WebSocket-Protocol: foo, bar\r\n"
60		);
61	}
62
63	#[bench]
64	fn bench_header_protocol_parse(b: &mut test::Bencher) {
65		let value = vec![b"foo, bar".to_vec()];
66		b.iter(|| {
67			let mut protocol: WebSocketProtocol = Header::parse_header(&value[..]).unwrap();
68			test::black_box(&mut protocol);
69		});
70	}
71
72	#[bench]
73	fn bench_header_protocol_format(b: &mut test::Bencher) {
74		let value = vec![b"foo, bar".to_vec()];
75		let val: WebSocketProtocol = Header::parse_header(&value[..]).unwrap();
76		b.iter(|| {
77			format!("{}", val);
78		});
79	}
80}