feat(headers): adds Accept

Moved utils to shared/. Added quality_value.
This commit is contained in:
Pyfisch
2014-12-29 17:43:41 -08:00
committed by Sean McArthur
parent 08cc8aadcb
commit 76126fc6c7
29 changed files with 393 additions and 155 deletions

View File

@@ -1,7 +1,9 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use std::str::from_utf8;
use mime::Mime;
use std::fmt;
use header;
use header::shared;
use mime;
/// The `Accept` header.
///
@@ -14,60 +16,53 @@ use mime::Mime;
/// ```
/// # use hyper::header::Headers;
/// # use hyper::header::common::Accept;
/// # use hyper::header::shared::qitem;
/// use hyper::mime::Mime;
/// use hyper::mime::TopLevel::Text;
/// use hyper::mime::SubLevel::{Html, Xml};
/// # let mut headers = Headers::new();
/// headers.set(Accept(vec![ Mime(Text, Html, vec![]), Mime(Text, Xml, vec![]) ]));
/// headers.set(Accept(vec![
/// qitem(Mime(Text, Html, vec![])),
/// qitem(Mime(Text, Xml, vec![])) ]));
/// ```
#[deriving(Clone, PartialEq, Show)]
pub struct Accept(pub Vec<Mime>);
pub struct Accept(pub Vec<shared::QualityItem<mime::Mime>>);
deref!(Accept -> Vec<Mime>);
deref!(Accept -> Vec<shared::QualityItem<mime::Mime>>);
impl Header for Accept {
impl header::Header for Accept {
fn header_name(_: Option<Accept>) -> &'static str {
"Accept"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Accept> {
let mut mimes: Vec<Mime> = vec![];
for mimes_raw in raw.iter() {
match from_utf8(mimes_raw.as_slice()) {
Ok(mimes_str) => {
for mime_str in mimes_str.split(',') {
match mime_str.trim().parse() {
Some(mime) => mimes.push(mime),
None => return None
}
}
},
Err(_) => return None
};
}
if !mimes.is_empty() {
Some(Accept(mimes))
} else {
// Currently is just a None, but later it can be Accept for */*
None
}
// TODO: Return */* if no value is given.
shared::from_comma_delimited(raw).map(Accept)
}
}
impl HeaderFormat for Accept {
impl header::HeaderFormat for Accept {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Accept(ref value) = *self;
let last = value.len() - 1;
for (i, mime) in value.iter().enumerate() {
try!(mime.fmt(fmt));
if i < last {
try!(", ".fmt(fmt));
}
}
Ok(())
shared::fmt_comma_delimited(fmt, self[])
}
}
bench_header!(bench, Accept, { vec![b"text/plain; q=0.5, text/html".to_vec()] });
#[test]
fn test_parse_header_no_quality() {
let a: Accept = header::Header::parse_header([b"text/plain; charset=utf-8".to_vec()].as_slice()).unwrap();
let b = Accept(vec![
shared::QualityItem{item: mime::Mime(mime::TopLevel::Text, mime::SubLevel::Plain, vec![(mime::Attr::Charset, mime::Value::Utf8)]), quality: 1f32},
]);
assert_eq!(a, b);
}
#[test]
fn test_parse_header_with_quality() {
let a: Accept = header::Header::parse_header([b"text/plain; charset=utf-8; q=0.5".to_vec()].as_slice()).unwrap();
let b = Accept(vec![
shared::QualityItem{item: mime::Mime(mime::TopLevel::Text, mime::SubLevel::Plain, vec![(mime::Attr::Charset, mime::Value::Utf8)]), quality: 0.5f32},
]);
assert_eq!(a, b);
}

View File

@@ -0,0 +1,39 @@
use std::fmt;
use header;
use header::shared;
/// The `Accept-Encoding` header
///
/// The `Accept-Encoding` header can be used by clients to indicate what
/// response encodings they accept.
#[deriving(Clone, PartialEq, Show)]
pub struct AcceptEncoding(pub Vec<shared::QualityItem<shared::Encoding>>);
deref!(AcceptEncoding -> Vec<shared::QualityItem<shared::Encoding>>);
impl header::Header for AcceptEncoding {
fn header_name(_: Option<AcceptEncoding>) -> &'static str {
"AcceptEncoding"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<AcceptEncoding> {
shared::from_comma_delimited(raw).map(AcceptEncoding)
}
}
impl header::HeaderFormat for AcceptEncoding {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
shared::fmt_comma_delimited(fmt, self[])
}
}
#[test]
fn test_parse_header() {
let a: AcceptEncoding = header::Header::parse_header([b"gzip;q=1.0, identity; q=0.5".to_vec()].as_slice()).unwrap();
let b = AcceptEncoding(vec![
shared::QualityItem{item: shared::Gzip, quality: 1f32},
shared::QualityItem{item: shared::Identity, quality: 0.5f32},
]);
assert_eq!(a, b);
}

View File

@@ -1,7 +1,7 @@
use header::{Header, HeaderFormat};
use method::Method;
use std::fmt::{mod};
use super::util::{from_comma_delimited, fmt_comma_delimited};
use header::shared::util::{from_comma_delimited, fmt_comma_delimited};
/// The `Allow` header.
/// See also https://tools.ietf.org/html/rfc7231#section-7.4.1
@@ -46,4 +46,3 @@ mod tests {
}
bench_header!(bench, Allow, { vec![b"OPTIONS,GET,PUT,POST,DELETE,HEAD,TRACE,CONNECT,PATCH,fOObAr".to_vec()] });

View File

@@ -1,7 +1,7 @@
use std::fmt;
use std::str::FromStr;
use header::{Header, HeaderFormat};
use super::util::{from_one_comma_delimited, fmt_comma_delimited};
use header::shared::util::{from_one_comma_delimited, fmt_comma_delimited};
/// The Cache-Control header.
#[deriving(PartialEq, Clone, Show)]

View File

@@ -1,7 +1,7 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};
use header::shared::util::{from_comma_delimited, fmt_comma_delimited};
pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};

View File

@@ -1,7 +1,7 @@
use std::fmt::{mod, Show};
use header::{Header, HeaderFormat};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `Content-Length` header.
///

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
use mime::Mime;
/// The `Content-Type` header.

View File

@@ -2,7 +2,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
@@ -41,4 +42,3 @@ impl FromStr for Date {
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Date, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `Etag` header.
///

View File

@@ -2,7 +2,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
/// The `Expires` header field.
#[deriving(Copy, PartialEq, Clone)]
@@ -40,4 +41,3 @@ impl FromStr for Expires {
bench_header!(imf_fixdate, Expires, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Expires, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Expires, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });

View File

@@ -1,7 +1,7 @@
use header::{Header, HeaderFormat};
use Port;
use std::fmt::{mod, Show};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `Host` header.
///

View File

@@ -2,7 +2,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
/// The `If-Modified-Since` header field.
#[deriving(Copy, PartialEq, Clone)]
@@ -40,4 +41,3 @@ impl FromStr for IfModifiedSince {
bench_header!(imf_fixdate, IfModifiedSince, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, IfModifiedSince, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, IfModifiedSince, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });

View File

@@ -2,7 +2,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
use header::shared::util::from_one_raw_str;
use header::shared::time::tm_from_str;
/// The `LastModified` header field.
#[deriving(Copy, PartialEq, Clone)]
@@ -40,4 +41,3 @@ impl FromStr for LastModified {
bench_header!(imf_fixdate, LastModified, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, LastModified, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, LastModified, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `Location` header.
///

View File

@@ -7,6 +7,7 @@
//! is used, such as `ContentType(pub Mime)`.
pub use self::accept::Accept;
pub use self::accept_encoding::AcceptEncoding;
pub use self::allow::Allow;
pub use self::authorization::Authorization;
pub use self::cache_control::CacheControl;
@@ -76,6 +77,9 @@ macro_rules! deref(
/// Exposes the Accept header.
pub mod accept;
/// Exposes the AcceptEncoding header.
pub mod accept_encoding;
/// Exposes the Allow header.
pub mod allow;
@@ -135,5 +139,3 @@ pub mod user_agent;
/// Exposes the Vary header.
pub mod vary;
pub mod util;

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `Server` header field.
///
@@ -28,4 +28,3 @@ impl HeaderFormat for Server {
}
bench_header!(bench, Server, { vec![b"Some String".to_vec()] });

View File

@@ -103,16 +103,15 @@ fn test_fmt() {
#[test]
fn cookie_jar() {
let jar = CookieJar::new("secret".as_bytes());
let jar = CookieJar::new(b"secret");
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
jar.encrypted().add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new("secret".as_bytes());
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
}

View File

@@ -1,7 +1,7 @@
use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};
use header::shared::util::{from_comma_delimited, fmt_comma_delimited};
use self::Encoding::{Chunked, Gzip, Deflate, Compress, EncodingExt};

View File

@@ -1,7 +1,7 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};
use header::shared::util::{from_comma_delimited, fmt_comma_delimited};
use self::Protocol::{WebSocket, ProtocolExt};

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
use super::util::from_one_raw_str;
use header::shared::util::from_one_raw_str;
/// The `User-Agent` header field.
///

View File

@@ -1,84 +0,0 @@
//! Utility functions for Header implementations.
use std::str::{FromStr, from_utf8};
use std::fmt::{mod, Show};
use time::{Tm, strptime};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
match from_utf8(unsafe { raw[].get_unchecked(0)[] }) {
Ok(s) => FromStr::from_str(s),
Err(_) => None
}
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
from_one_comma_delimited(unsafe { raw.as_slice().get_unchecked(0).as_slice() })
}
/// Reads a comma-delimited raw string into a Vec.
pub fn from_one_comma_delimited<T: FromStr>(raw: &[u8]) -> Option<Vec<T>> {
match from_utf8(raw) {
Ok(s) => {
Some(s.as_slice()
.split(',')
.map(|x| x.trim())
.filter_map(FromStr::from_str)
.collect())
}
Err(_) => None
}
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Show>(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
let last = parts.len() - 1;
for (i, part) in parts.iter().enumerate() {
try!(part.fmt(fmt));
if i < last {
try!(", ".fmt(fmt));
}
}
Ok(())
}
/// Get a Tm from HTTP date formats.
// Prior to 1995, there were three different formats commonly used by
// servers to communicate timestamps. For compatibility with old
// implementations, all three are defined here. The preferred format is
// a fixed-length and single-zone subset of the date and time
// specification used by the Internet Message Format [RFC5322].
//
// HTTP-date = IMF-fixdate / obs-date
//
// An example of the preferred format is
//
// Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
//
// Examples of the two obsolete formats are
//
// Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
//
// A recipient that parses a timestamp value in an HTTP header field
// MUST accept all three HTTP-date formats. When a sender generates a
// header field that contains one or more timestamps defined as
// HTTP-date, the sender MUST generate those timestamps in the
// IMF-fixdate format.
pub fn tm_from_str(s: &str) -> Option<Tm> {
strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
strptime(s, "%A, %d-%b-%y %T %Z")
}).or_else(|_| {
strptime(s, "%c")
}).ok()
}

View File

@@ -1,6 +1,6 @@
use header::{Header, HeaderFormat, CaseInsensitive};
use std::fmt::{mod};
use super::util::{from_comma_delimited, fmt_comma_delimited, from_one_raw_str};
use header::shared::util::{from_comma_delimited, fmt_comma_delimited, from_one_raw_str};
/// The `Allow` header.
/// See also https://tools.ietf.org/html/rfc7231#section-7.1.4