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
use hyper;
use hyper::header::parsing::from_one_raw_str;
use hyper::header::{Header, HeaderFormat};
use std::fmt;
use std::ops::Deref;

/// Represents an Origin header
#[derive(PartialEq, Clone, Debug)]
pub struct Origin(pub String);

impl Deref for Origin {
	type Target = String;
	fn deref(&self) -> &String {
		&self.0
	}
}

impl Header for Origin {
	fn header_name() -> &'static str {
		"Origin"
	}

	fn parse_header(raw: &[Vec<u8>]) -> hyper::Result<Origin> {
		from_one_raw_str(raw).map(Origin)
	}
}

impl HeaderFormat for Origin {
	fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		let Origin(ref value) = *self;
		write!(fmt, "{}", value)
	}
}

impl fmt::Display for Origin {
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		self.fmt_header(fmt)
	}
}

#[cfg(all(feature = "nightly", test))]
mod tests {
	use super::*;
	use hyper::header::Header;
	use test;

	#[test]
	fn test_header_origin() {
		use header::Headers;

		let origin = Origin("foo bar".to_string());
		let mut headers = Headers::new();
		headers.set(origin);

		assert_eq!(&headers.to_string()[..], "Origin: foo bar\r\n");
	}

	#[bench]
	fn bench_header_origin_parse(b: &mut test::Bencher) {
		let value = vec![b"foobar".to_vec()];
		b.iter(|| {
			let mut origin: Origin = Header::parse_header(&value[..]).unwrap();
			test::black_box(&mut origin);
		});
	}

	#[bench]
	fn bench_header_origin_format(b: &mut test::Bencher) {
		let value = vec![b"foobar".to_vec()];
		let val: Origin = Header::parse_header(&value[..]).unwrap();
		b.iter(|| {
			format!("{}", val);
		});
	}
}