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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use std::any::Any;
use std::borrow::Cow::{Borrowed, Owned};
use std::fmt;
use std::intrinsics::TypeId;
use std::raw::TraitObject;
use std::str::from_utf8;
use std::string::CowString;
use std::collections::HashMap;
use std::collections::hash_map::{Iter, Entry};
use std::iter::FromIterator;
use std::borrow::IntoCow;
use std::{mem, raw};
use mucell::MuCell;
use uany::{UnsafeAnyExt};
use unicase::UniCase;
use {http, HttpResult};
pub use self::common::*;
pub use self::shared::*;
pub mod common;
pub mod shared;
type HeaderName = UniCase<CowString<'static>>;
pub trait Header: Clone + Any + Send + Sync {
fn header_name(marker: Option<Self>) -> &'static str;
fn parse_header(raw: &[Vec<u8>]) -> Option<Self>;
}
pub trait HeaderFormat: HeaderClone + Any + Send + Sync {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result;
}
#[doc(hidden)]
pub trait HeaderClone {
fn clone_box(&self) -> Box<HeaderFormat + Sync + Send>;
}
impl<T: HeaderFormat + Send + Sync + Clone> HeaderClone for T {
#[inline]
fn clone_box(&self) -> Box<HeaderFormat + Sync + Send> {
Box::new(self.clone())
}
}
impl HeaderFormat {
#[inline]
fn is<T: 'static>(&self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
}
impl UnsafeAnyExt for HeaderFormat {
#[inline]
unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
mem::transmute(mem::transmute::<&HeaderFormat, raw::TraitObject>(self).data)
}
#[inline]
unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T {
mem::transmute(mem::transmute::<&mut HeaderFormat, raw::TraitObject>(self).data)
}
#[inline]
unsafe fn downcast_unchecked<T: 'static>(self: Box<HeaderFormat>) -> Box<T> {
mem::transmute(mem::transmute::<Box<HeaderFormat>, raw::TraitObject>(self).data)
}
}
impl Clone for Box<HeaderFormat + Send + Sync> {
#[inline]
fn clone(&self) -> Box<HeaderFormat + Send + Sync> {
self.clone_box()
}
}
fn header_name<T: Header>() -> &'static str {
let name = Header::header_name(None::<T>);
name
}
#[derive(Clone)]
pub struct Headers {
data: HashMap<HeaderName, MuCell<Item>>
}
impl Headers {
pub fn new() -> Headers {
Headers {
data: HashMap::new()
}
}
#[doc(hidden)]
pub fn from_raw<R: Reader>(rdr: &mut R) -> HttpResult<Headers> {
let mut headers = Headers::new();
loop {
match try!(http::read_header(rdr)) {
Some((name, value)) => {
debug!("raw header: {:?}={:?}", name, &value[]);
let name = UniCase(Owned(name));
let mut item = match headers.data.entry(name) {
Entry::Vacant(entry) => entry.insert(MuCell::new(Item::raw(vec![]))),
Entry::Occupied(entry) => entry.into_mut()
};
match &mut item.borrow_mut().raw {
&mut Some(ref mut raw) => raw.push(value),
_ => {}
};
},
None => break,
}
}
Ok(headers)
}
pub fn set<H: Header + HeaderFormat>(&mut self, value: H) {
self.data.insert(UniCase(Borrowed(header_name::<H>())),
MuCell::new(Item::typed(Box::new(value))));
}
pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> {
self.data
.get(&UniCase(Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))
.and_then(|item| {
if let Some(ref raw) = item.borrow().raw {
return unsafe { mem::transmute(Some(&raw[])) };
}
let worked = item.try_mutate(|item| {
let raw = vec![item.typed.as_ref().unwrap().to_string().into_bytes()];
item.raw = Some(raw);
});
debug_assert!(worked, "item.try_mutate should return true");
let item = item.borrow();
let raw = item.raw.as_ref().unwrap();
unsafe { mem::transmute(Some(&raw[])) }
})
}
pub fn set_raw<K: IntoCow<'static, String, str>>(&mut self, name: K, value: Vec<Vec<u8>>) {
self.data.insert(UniCase(name.into_cow()), MuCell::new(Item::raw(value)));
}
pub fn get<H: Header + HeaderFormat>(&self) -> Option<&H> {
self.get_or_parse::<H>().map(|item| {
unsafe {
mem::transmute::<&H, &H>(downcast(&*item.borrow()))
}
})
}
pub fn get_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> {
self.get_or_parse_mut::<H>().map(|item| {
unsafe { downcast_mut(item.borrow_mut()) }
})
}
fn get_or_parse<H: Header + HeaderFormat>(&self) -> Option<&MuCell<Item>> {
self.data.get(&UniCase(Borrowed(header_name::<H>()))).and_then(get_or_parse::<H>)
}
fn get_or_parse_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut MuCell<Item>> {
self.data.get_mut(&UniCase(Borrowed(header_name::<H>()))).and_then(get_or_parse_mut::<H>)
}
pub fn has<H: Header + HeaderFormat>(&self) -> bool {
self.data.contains_key(&UniCase(Borrowed(header_name::<H>())))
}
pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool {
self.data.remove(&UniCase(Borrowed(Header::header_name(None::<H>)))).is_some()
}
pub fn iter<'a>(&'a self) -> HeadersItems<'a> {
HeadersItems {
inner: self.data.iter()
}
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn clear(&mut self) {
self.data.clear()
}
}
impl fmt::String for Headers {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for header in self.iter() {
try!(write!(fmt, "{}\r\n", header));
}
Ok(())
}
}
impl fmt::Show for Headers {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str("Headers {{ "));
for header in self.iter() {
try!(write!(fmt, "{:?}, ", header));
}
try!(fmt.write_str("}}"));
Ok(())
}
}
pub struct HeadersItems<'a> {
inner: Iter<'a, HeaderName, MuCell<Item>>
}
impl<'a> Iterator for HeadersItems<'a> {
type Item = HeaderView<'a>;
fn next(&mut self) -> Option<HeaderView<'a>> {
match self.inner.next() {
Some((k, v)) => Some(HeaderView(k, v)),
None => None
}
}
}
pub struct HeaderView<'a>(&'a HeaderName, &'a MuCell<Item>);
impl<'a> HeaderView<'a> {
#[inline]
pub fn is<H: Header>(&self) -> bool {
UniCase(header_name::<H>().into_cow()) == *self.0
}
#[inline]
pub fn name(&self) -> &'a str {
self.0.as_slice()
}
#[inline]
pub fn value<H: Header + HeaderFormat>(&self) -> Option<&'a H> {
get_or_parse::<H>(self.1).map(|item| {
unsafe {
mem::transmute::<&H, &H>(downcast(&*item.borrow()))
}
})
}
#[inline]
pub fn value_string(&self) -> String {
(*self.1.borrow()).to_string()
}
}
impl<'a> fmt::String for HeaderView<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", self.0, *self.1.borrow())
}
}
impl<'a> fmt::Show for HeaderView<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.to_string().fmt(fmt)
}
}
impl<'a> Extend<HeaderView<'a>> for Headers {
fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, mut iter: I) {
for header in iter {
self.data.insert((*header.0).clone(), (*header.1).clone());
}
}
}
impl<'a> FromIterator<HeaderView<'a>> for Headers {
fn from_iter<I: Iterator<Item=HeaderView<'a>>>(iter: I) -> Headers {
let mut headers = Headers::new();
headers.extend(iter);
headers
}
}
#[derive(Clone)]
struct Item {
raw: Option<Vec<Vec<u8>>>,
typed: Option<Box<HeaderFormat + Send + Sync>>
}
impl Item {
fn raw(data: Vec<Vec<u8>>) -> Item {
Item {
raw: Some(data),
typed: None,
}
}
fn typed(ty: Box<HeaderFormat + Send + Sync>) -> Item {
Item {
raw: None,
typed: Some(ty),
}
}
}
fn get_or_parse<H: Header + HeaderFormat>(item: &MuCell<Item>) -> Option<&MuCell<Item>> {
match item.borrow().typed {
Some(ref typed) if typed.is::<H>() => return Some(item),
Some(ref typed) => {
warn!("attempted to access {:?} as wrong type", typed);
return None;
}
_ => ()
}
let worked = item.try_mutate(parse::<H>);
debug_assert!(worked, "item.try_mutate should return true");
if item.borrow().typed.is_some() {
Some(item)
} else {
None
}
}
fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut MuCell<Item>) -> Option<&mut MuCell<Item>> {
let is_correct_type = match item.borrow().typed {
Some(ref typed) if typed.is::<H>() => Some(true),
Some(ref typed) => {
warn!("attempted to access {:?} as wrong type", typed);
Some(false)
}
_ => None
};
match is_correct_type {
Some(true) => return Some(item),
Some(false) => return None,
None => ()
}
parse::<H>(item.borrow_mut());
if item.borrow().typed.is_some() {
Some(item)
} else {
None
}
}
fn parse<H: Header + HeaderFormat>(item: &mut Item) {
item.typed = match item.raw {
Some(ref raw) => match Header::parse_header(&raw[]) {
Some::<H>(h) => Some(box h as Box<HeaderFormat + Send + Sync>),
None => None
},
None => unreachable!()
};
}
unsafe fn downcast<H: Header + HeaderFormat>(item: &Item) -> &H {
item.typed.as_ref().expect("item.typed must be set").downcast_ref_unchecked()
}
unsafe fn downcast_mut<H: Header + HeaderFormat>(item: &mut Item) -> &mut H {
item.typed.as_mut().expect("item.typed must be set").downcast_mut_unchecked()
}
impl fmt::String for Item {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.typed {
Some(ref h) => h.fmt_header(fmt),
None => match self.raw {
Some(ref raw) => {
for part in raw.iter() {
match from_utf8(&part[]) {
Ok(s) => try!(fmt.write_str(s)),
Err(e) => {
error!("raw header value is not utf8. header={:?}, error={:?}", part, e);
return Err(fmt::Error);
}
}
}
Ok(())
},
None => unreachable!()
}
}
}
}
impl fmt::Show for Box<HeaderFormat + Send + Sync> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt_header(fmt)
}
}
impl fmt::String for Box<HeaderFormat + Send + Sync> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt_header(fmt)
}
}
pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H);
impl<'a, H: HeaderFormat> fmt::String for HeaderFormatter<'a, H> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt_header(f)
}
}
impl<'a, H: HeaderFormat> fmt::Show for HeaderFormatter<'a, H> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt_header(f)
}
}
#[cfg(test)]
mod tests {
use std::io::MemReader;
use std::fmt;
use std::borrow::Cow::Borrowed;
use std::hash::{SipHasher, hash};
use mime::Mime;
use mime::TopLevel::Text;
use mime::SubLevel::Plain;
use unicase::UniCase;
use super::{Headers, Header, HeaderFormat};
use super::common::{ContentLength, ContentType, Accept, Host};
use super::shared::{QualityItem};
use test::Bencher;
fn mem(s: &str) -> MemReader {
MemReader::new(s.as_bytes().to_vec())
}
#[test]
fn test_case_insensitive() {
let a = UniCase(Borrowed("foobar"));
let b = UniCase(Borrowed("FOOBAR"));
assert_eq!(a, b);
assert_eq!(hash::<_, SipHasher>(&a), hash::<_, SipHasher>(&b));
}
#[test]
fn test_from_raw() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
assert_eq!(headers.get(), Some(&ContentLength(10)));
}
#[test]
fn test_content_type() {
let content_type = Header::parse_header([b"text/plain".to_vec()].as_slice());
assert_eq!(content_type, Some(ContentType(Mime(Text, Plain, vec![]))));
}
#[test]
fn test_accept() {
let text_plain = QualityItem{item: Mime(Text, Plain, vec![]), quality: 1f32};
let application_vendor = "application/vnd.github.v3.full+json; q=0.5".parse().unwrap();
let accept = Header::parse_header([b"text/plain".to_vec()].as_slice());
assert_eq!(accept, Some(Accept(vec![text_plain.clone()])));
let accept = Header::parse_header([b"application/vnd.github.v3.full+json; q=0.5, text/plain".to_vec()].as_slice());
assert_eq!(accept, Some(Accept(vec![application_vendor, text_plain])));
}
#[derive(Clone, Show)]
struct CrazyLength(Option<bool>, usize);
impl Header for CrazyLength {
fn header_name(_: Option<CrazyLength>) -> &'static str {
"content-length"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<CrazyLength> {
use std::str::from_utf8;
use std::str::FromStr;
if raw.len() != 1 {
return None;
}
match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) {
Ok(s) => FromStr::from_str(s),
Err(_) => None
}.map(|u| CrazyLength(Some(false), u))
}
}
impl HeaderFormat for CrazyLength {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let CrazyLength(ref opt, ref value) = *self;
write!(fmt, "{:?}, {:?}", opt, value)
}
}
#[test]
fn test_different_structs_for_same_header() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
let ContentLength(_) = *headers.get::<ContentLength>().unwrap();
assert!(headers.get::<CrazyLength>().is_none());
}
#[test]
fn test_trailing_whitespace() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10 \r\n\r\n")).unwrap();
let ContentLength(_) = *headers.get::<ContentLength>().unwrap();
assert!(headers.get::<CrazyLength>().is_none());
}
#[test]
fn test_multiple_reads() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
let ContentLength(one) = *headers.get::<ContentLength>().unwrap();
let ContentLength(two) = *headers.get::<ContentLength>().unwrap();
assert_eq!(one, two);
}
#[test]
fn test_different_reads() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap();
let ContentLength(_) = *headers.get::<ContentLength>().unwrap();
let ContentType(_) = *headers.get::<ContentType>().unwrap();
}
#[test]
fn test_get_mutable() {
let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap();
*headers.get_mut::<ContentLength>().unwrap() = ContentLength(20);
assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20));
}
#[test]
fn test_headers_show() {
let mut headers = Headers::new();
headers.set(ContentLength(15));
headers.set(Host { hostname: "foo.bar".to_string(), port: None });
let s = headers.to_string();
let mut pieces = s.split_str("\r\n").collect::<Vec<&str>>();
pieces.sort();
let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n");
assert_eq!(s, "Host: foo.bar\r\nContent-Length: 15\r\n");
}
#[test]
fn test_headers_show_raw() {
let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
let s = headers.to_string();
assert_eq!(s, "Content-Length: 10\r\n");
}
#[test]
fn test_set_raw() {
let mut headers = Headers::new();
headers.set(ContentLength(10));
headers.set_raw("content-LENGTH", vec![b"20".to_vec()]);
assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][]);
assert_eq!(headers.get(), Some(&ContentLength(20)));
}
#[test]
fn test_len() {
let mut headers = Headers::new();
headers.set(ContentLength(10));
assert_eq!(headers.len(), 1);
headers.set(ContentType(Mime(Text, Plain, vec![])));
assert_eq!(headers.len(), 2);
headers.set(ContentLength(20));
assert_eq!(headers.len(), 2);
}
#[test]
fn test_clear() {
let mut headers = Headers::new();
headers.set(ContentLength(10));
headers.set(ContentType(Mime(Text, Plain, vec![])));
assert_eq!(headers.len(), 2);
headers.clear();
assert_eq!(headers.len(), 0);
}
#[test]
fn test_iter() {
let mut headers = Headers::new();
headers.set(ContentLength(11));
for header in headers.iter() {
assert!(header.is::<ContentLength>());
assert_eq!(header.name(), Header::header_name(None::<ContentLength>));
assert_eq!(header.value(), Some(&ContentLength(11)));
assert_eq!(header.value_string(), "11".to_string());
}
}
#[bench]
fn bench_header_get(b: &mut Bencher) {
let mut headers = Headers::new();
headers.set(ContentLength(11));
b.iter(|| assert_eq!(headers.get::<ContentLength>(), Some(&ContentLength(11))))
}
#[bench]
fn bench_header_get_miss(b: &mut Bencher) {
let headers = Headers::new();
b.iter(|| assert!(headers.get::<ContentLength>().is_none()))
}
#[bench]
fn bench_header_set(b: &mut Bencher) {
let mut headers = Headers::new();
b.iter(|| headers.set(ContentLength(12)))
}
#[bench]
fn bench_header_has(b: &mut Bencher) {
let mut headers = Headers::new();
headers.set(ContentLength(11));
b.iter(|| assert!(headers.has::<ContentLength>()))
}
#[bench]
fn bench_header_view_is(b: &mut Bencher) {
let mut headers = Headers::new();
headers.set(ContentLength(11));
let mut iter = headers.iter();
let view = iter.next().unwrap();
b.iter(|| assert!(view.is::<ContentLength>()))
}
}