1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-23 16:40:37 +00:00

rename header generator macros

This commit is contained in:
Rob Ede 2021-04-15 22:05:06 +01:00
parent 845c02cb86
commit 8d88a0a9af
No known key found for this signature in database
GPG key ID: 97C636207D3EF933
20 changed files with 395 additions and 397 deletions

View file

@ -5,7 +5,7 @@ use mime::Mime;
use super::{qitem, QualityItem}; use super::{qitem, QualityItem};
use crate::http::header; use crate::http::header;
crate::header! { crate::__define_common_header! {
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2) /// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
/// ///
/// The `Accept` header field can be used by user agents to specify /// The `Accept` header field can be used by user agents to specify
@ -81,14 +81,14 @@ crate::header! {
test_accept { test_accept {
// Tests from the RFC // Tests from the RFC
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"audio/*; q=0.2, audio/basic"], vec![b"audio/*; q=0.2, audio/basic"],
Some(Accept(vec![ Some(Accept(vec![
QualityItem::new("audio/*".parse().unwrap(), q(200)), QualityItem::new("audio/*".parse().unwrap(), q(200)),
qitem("audio/basic".parse().unwrap()), qitem("audio/basic".parse().unwrap()),
]))); ])));
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"], vec![b"text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
Some(Accept(vec![ Some(Accept(vec![
@ -100,13 +100,13 @@ crate::header! {
qitem("text/x-c".parse().unwrap()), qitem("text/x-c".parse().unwrap()),
]))); ])));
// Custom tests // Custom tests
test_header!( crate::__common_header_test!(
test3, test3,
vec![b"text/plain; charset=utf-8"], vec![b"text/plain; charset=utf-8"],
Some(Accept(vec![ Some(Accept(vec![
qitem(mime::TEXT_PLAIN_UTF_8), qitem(mime::TEXT_PLAIN_UTF_8),
]))); ])));
test_header!( crate::__common_header_test!(
test4, test4,
vec![b"text/plain; charset=utf-8; q=0.5"], vec![b"text/plain; charset=utf-8; q=0.5"],
Some(Accept(vec![ Some(Accept(vec![

View file

@ -1,6 +1,6 @@
use super::{Charset, QualityItem, ACCEPT_CHARSET}; use super::{Charset, QualityItem, ACCEPT_CHARSET};
crate::header! { crate::__define_common_header! {
/// `Accept-Charset` header, defined in /// `Accept-Charset` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.3)
/// ///
@ -57,6 +57,6 @@ crate::header! {
test_accept_charset { test_accept_charset {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]); crate::__common_header_test!(test1, vec![b"iso-8859-5, unicode-1-1;q=0.8"]);
} }
} }

View file

@ -64,12 +64,12 @@ header! {
test_accept_encoding { test_accept_encoding {
// From the RFC // From the RFC
test_header!(test1, vec![b"compress, gzip"]); crate::__common_header_test!(test1, vec![b"compress, gzip"]);
test_header!(test2, vec![b""], Some(AcceptEncoding(vec![]))); crate::__common_header_test!(test2, vec![b""], Some(AcceptEncoding(vec![])));
test_header!(test3, vec![b"*"]); crate::__common_header_test!(test3, vec![b"*"]);
// Note: Removed quality 1 from gzip // Note: Removed quality 1 from gzip
test_header!(test4, vec![b"compress;q=0.5, gzip"]); crate::__common_header_test!(test4, vec![b"compress;q=0.5, gzip"]);
// Note: Removed quality 1 from gzip // Note: Removed quality 1 from gzip
test_header!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]); crate::__common_header_test!(test5, vec![b"gzip, identity; q=0.5, *;q=0"]);
} }
} }

View file

@ -1,7 +1,8 @@
use super::{QualityItem, ACCEPT_LANGUAGE};
use language_tags::LanguageTag; use language_tags::LanguageTag;
crate::header! { use super::{QualityItem, ACCEPT_LANGUAGE};
crate::__define_common_header! {
/// `Accept-Language` header, defined in /// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
/// ///
@ -56,9 +57,9 @@ crate::header! {
test_accept_language { test_accept_language {
// From the RFC // From the RFC
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]); crate::__common_header_test!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
// Own test // Own test
test_header!( crate::__common_header_test!(
test2, vec![b"en-US, en; q=0.5, fr"], test2, vec![b"en-US, en; q=0.5, fr"],
Some(AcceptLanguage(vec![ Some(AcceptLanguage(vec![
qitem("en-US".parse().unwrap()), qitem("en-US".parse().unwrap()),

View file

@ -1,7 +1,7 @@
use actix_http::http::Method;
use crate::http::header; use crate::http::header;
use actix_http::http::Method;
crate::header! { crate::__define_common_header! {
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1) /// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
/// ///
/// The `Allow` header field lists the set of methods advertised as /// The `Allow` header field lists the set of methods advertised as
@ -49,12 +49,12 @@ crate::header! {
test_allow { test_allow {
// From the RFC // From the RFC
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"GET, HEAD, PUT"], vec![b"GET, HEAD, PUT"],
Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT]))); Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT])));
// Own tests // Own tests
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"], vec![b"OPTIONS, GET, PUT, POST, DELETE, HEAD, TRACE, CONNECT, PATCH"],
Some(HeaderField(vec![ Some(HeaderField(vec![
@ -67,7 +67,7 @@ crate::header! {
Method::TRACE, Method::TRACE,
Method::CONNECT, Method::CONNECT,
Method::PATCH]))); Method::PATCH])));
test_header!( crate::__common_header_test!(
test3, test3,
vec![b""], vec![b""],
Some(HeaderField(Vec::<Method>::new()))); Some(HeaderField(Vec::<Method>::new())));

View file

@ -51,9 +51,9 @@ use crate::http::header;
#[derive(PartialEq, Clone, Debug)] #[derive(PartialEq, Clone, Debug)]
pub struct CacheControl(pub Vec<CacheDirective>); pub struct CacheControl(pub Vec<CacheDirective>);
__hyper__deref!(CacheControl => Vec<CacheDirective>); crate::__common_header_deref!(CacheControl => Vec<CacheDirective>);
//TODO: this could just be the header! macro // TODO: this could just be the __define_common_header! macro
impl Header for CacheControl { impl Header for CacheControl {
fn name() -> header::HeaderName { fn name() -> header::HeaderName {
header::CACHE_CONTROL header::CACHE_CONTROL
@ -75,7 +75,7 @@ impl Header for CacheControl {
impl fmt::Display for CacheControl { impl fmt::Display for CacheControl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_comma_delimited(f, &self[..]) fmt_comma_delimited(f, &self.0[..])
} }
} }

View file

@ -1,7 +1,7 @@
use super::{QualityItem, CONTENT_LANGUAGE}; use super::{QualityItem, CONTENT_LANGUAGE};
use language_tags::LanguageTag; use language_tags::LanguageTag;
crate::header! { crate::__define_common_header! {
/// `Content-Language` header, defined in /// `Content-Language` header, defined in
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2) /// [RFC7231](https://tools.ietf.org/html/rfc7231#section-3.1.3.2)
/// ///
@ -52,7 +52,7 @@ crate::header! {
(ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+ (ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
test_content_language { test_content_language {
test_header!(test1, vec![b"da"]); crate::__common_header_test!(test1, vec![b"da"]);
test_header!(test2, vec![b"mi, en"]); crate::__common_header_test!(test2, vec![b"mi, en"]);
} }
} }

View file

@ -6,65 +6,65 @@ use super::{
HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE, HeaderValue, IntoHeaderValue, InvalidHeaderValue, Writer, CONTENT_RANGE,
}; };
crate::header! { crate::__define_common_header! {
/// `Content-Range` header, defined in /// `Content-Range` header, defined in
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2) /// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
(ContentRange, CONTENT_RANGE) => [ContentRangeSpec] (ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
test_content_range { test_content_range {
test_header!(test_bytes, crate::__common_header_test!(test_bytes,
vec![b"bytes 0-499/500"], vec![b"bytes 0-499/500"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: Some((0, 499)), range: Some((0, 499)),
instance_length: Some(500) instance_length: Some(500)
}))); })));
test_header!(test_bytes_unknown_len, crate::__common_header_test!(test_bytes_unknown_len,
vec![b"bytes 0-499/*"], vec![b"bytes 0-499/*"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: Some((0, 499)), range: Some((0, 499)),
instance_length: None instance_length: None
}))); })));
test_header!(test_bytes_unknown_range, crate::__common_header_test!(test_bytes_unknown_range,
vec![b"bytes */500"], vec![b"bytes */500"],
Some(ContentRange(ContentRangeSpec::Bytes { Some(ContentRange(ContentRangeSpec::Bytes {
range: None, range: None,
instance_length: Some(500) instance_length: Some(500)
}))); })));
test_header!(test_unregistered, crate::__common_header_test!(test_unregistered,
vec![b"seconds 1-2"], vec![b"seconds 1-2"],
Some(ContentRange(ContentRangeSpec::Unregistered { Some(ContentRange(ContentRangeSpec::Unregistered {
unit: "seconds".to_owned(), unit: "seconds".to_owned(),
resp: "1-2".to_owned() resp: "1-2".to_owned()
}))); })));
test_header!(test_no_len, crate::__common_header_test!(test_no_len,
vec![b"bytes 0-499"], vec![b"bytes 0-499"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_only_unit, crate::__common_header_test!(test_only_unit,
vec![b"bytes"], vec![b"bytes"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_end_less_than_start, crate::__common_header_test!(test_end_less_than_start,
vec![b"bytes 499-0/500"], vec![b"bytes 499-0/500"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_blank, crate::__common_header_test!(test_blank,
vec![b""], vec![b""],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_spaces, crate::__common_header_test!(test_bytes_many_spaces,
vec![b"bytes 1-2/500 3"], vec![b"bytes 1-2/500 3"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_slashes, crate::__common_header_test!(test_bytes_many_slashes,
vec![b"bytes 1-2/500/600"], vec![b"bytes 1-2/500/600"],
None::<ContentRange>); None::<ContentRange>);
test_header!(test_bytes_many_dashes, crate::__common_header_test!(test_bytes_many_dashes,
vec![b"bytes 1-2-3/500"], vec![b"bytes 1-2-3/500"],
None::<ContentRange>); None::<ContentRange>);

View file

@ -1,7 +1,7 @@
use super::CONTENT_TYPE; use super::CONTENT_TYPE;
use mime::Mime; use mime::Mime;
crate::header! { crate::__define_common_header! {
/// `Content-Type` header, defined in /// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5) /// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
/// ///
@ -52,7 +52,7 @@ crate::header! {
(ContentType, CONTENT_TYPE) => [Mime] (ContentType, CONTENT_TYPE) => [Mime]
test_content_type { test_content_type {
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"text/html"], vec![b"text/html"],
Some(HeaderField(mime::TEXT_HTML))); Some(HeaderField(mime::TEXT_HTML)));

View file

@ -1,7 +1,7 @@
use super::{HttpDate, DATE}; use super::{HttpDate, DATE};
use std::time::SystemTime; use std::time::SystemTime;
crate::header! { crate::__define_common_header! {
/// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2) /// `Date` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.1.2)
/// ///
/// The `Date` header field represents the date and time at which the /// The `Date` header field represents the date and time at which the
@ -32,7 +32,7 @@ crate::header! {
(Date, DATE) => [HttpDate] (Date, DATE) => [HttpDate]
test_date { test_date {
test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]); crate::__common_header_test!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]);
} }
} }

View file

@ -1,6 +1,6 @@
use super::{EntityTag, ETAG}; use super::{EntityTag, ETAG};
crate::header! { crate::__define_common_header! {
/// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3) /// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3)
/// ///
/// The `ETag` header field in a response provides the current entity-tag /// The `ETag` header field in a response provides the current entity-tag
@ -50,50 +50,50 @@ crate::header! {
test_etag { test_etag {
// From the RFC // From the RFC
test_header!(test1, crate::__common_header_test!(test1,
vec![b"\"xyzzy\""], vec![b"\"xyzzy\""],
Some(ETag(EntityTag::new(false, "xyzzy".to_owned())))); Some(ETag(EntityTag::new(false, "xyzzy".to_owned()))));
test_header!(test2, crate::__common_header_test!(test2,
vec![b"W/\"xyzzy\""], vec![b"W/\"xyzzy\""],
Some(ETag(EntityTag::new(true, "xyzzy".to_owned())))); Some(ETag(EntityTag::new(true, "xyzzy".to_owned()))));
test_header!(test3, crate::__common_header_test!(test3,
vec![b"\"\""], vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned())))); Some(ETag(EntityTag::new(false, "".to_owned()))));
// Own tests // Own tests
test_header!(test4, crate::__common_header_test!(test4,
vec![b"\"foobar\""], vec![b"\"foobar\""],
Some(ETag(EntityTag::new(false, "foobar".to_owned())))); Some(ETag(EntityTag::new(false, "foobar".to_owned()))));
test_header!(test5, crate::__common_header_test!(test5,
vec![b"\"\""], vec![b"\"\""],
Some(ETag(EntityTag::new(false, "".to_owned())))); Some(ETag(EntityTag::new(false, "".to_owned()))));
test_header!(test6, crate::__common_header_test!(test6,
vec![b"W/\"weak-etag\""], vec![b"W/\"weak-etag\""],
Some(ETag(EntityTag::new(true, "weak-etag".to_owned())))); Some(ETag(EntityTag::new(true, "weak-etag".to_owned()))));
test_header!(test7, crate::__common_header_test!(test7,
vec![b"W/\"\x65\x62\""], vec![b"W/\"\x65\x62\""],
Some(ETag(EntityTag::new(true, "\u{0065}\u{0062}".to_owned())))); Some(ETag(EntityTag::new(true, "\u{0065}\u{0062}".to_owned()))));
test_header!(test8, crate::__common_header_test!(test8,
vec![b"W/\"\""], vec![b"W/\"\""],
Some(ETag(EntityTag::new(true, "".to_owned())))); Some(ETag(EntityTag::new(true, "".to_owned()))));
test_header!(test9, crate::__common_header_test!(test9,
vec![b"no-dquotes"], vec![b"no-dquotes"],
None::<ETag>); None::<ETag>);
test_header!(test10, crate::__common_header_test!(test10,
vec![b"w/\"the-first-w-is-case-sensitive\""], vec![b"w/\"the-first-w-is-case-sensitive\""],
None::<ETag>); None::<ETag>);
test_header!(test11, crate::__common_header_test!(test11,
vec![b""], vec![b""],
None::<ETag>); None::<ETag>);
test_header!(test12, crate::__common_header_test!(test12,
vec![b"\"unmatched-dquotes1"], vec![b"\"unmatched-dquotes1"],
None::<ETag>); None::<ETag>);
test_header!(test13, crate::__common_header_test!(test13,
vec![b"unmatched-dquotes2\""], vec![b"unmatched-dquotes2\""],
None::<ETag>); None::<ETag>);
test_header!(test14, crate::__common_header_test!(test14,
vec![b"matched-\"dquotes\""], vec![b"matched-\"dquotes\""],
None::<ETag>); None::<ETag>);
test_header!(test15, crate::__common_header_test!(test15,
vec![b"\""], vec![b"\""],
None::<ETag>); None::<ETag>);
} }

View file

@ -1,6 +1,6 @@
use super::{HttpDate, EXPIRES}; use super::{HttpDate, EXPIRES};
crate::header! { crate::__define_common_header! {
/// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3) /// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3)
/// ///
/// The `Expires` header field gives the date/time after which the /// The `Expires` header field gives the date/time after which the
@ -36,6 +36,6 @@ crate::header! {
test_expires { test_expires {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Thu, 01 Dec 1994 16:00:00 GMT"]); crate::__common_header_test!(test1, vec![b"Thu, 01 Dec 1994 16:00:00 GMT"]);
} }
} }

View file

@ -1,6 +1,6 @@
use super::{EntityTag, IF_MATCH}; use super::{EntityTag, IF_MATCH};
crate::header! { crate::__define_common_header! {
/// `If-Match` header, defined in /// `If-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1) /// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)
/// ///
@ -53,18 +53,18 @@ crate::header! {
(IfMatch, IF_MATCH) => {Any / (EntityTag)+} (IfMatch, IF_MATCH) => {Any / (EntityTag)+}
test_if_match { test_if_match {
test_header!( crate::__common_header_test!(
test1, test1,
vec![b"\"xyzzy\""], vec![b"\"xyzzy\""],
Some(HeaderField::Items( Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned())]))); vec![EntityTag::new(false, "xyzzy".to_owned())])));
test_header!( crate::__common_header_test!(
test2, test2,
vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""], vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""],
Some(HeaderField::Items( Some(HeaderField::Items(
vec![EntityTag::new(false, "xyzzy".to_owned()), vec![EntityTag::new(false, "xyzzy".to_owned()),
EntityTag::new(false, "r2d2xxxx".to_owned()), EntityTag::new(false, "r2d2xxxx".to_owned()),
EntityTag::new(false, "c3piozzzz".to_owned())]))); EntityTag::new(false, "c3piozzzz".to_owned())])));
test_header!(test3, vec![b"*"], Some(IfMatch::Any)); crate::__common_header_test!(test3, vec![b"*"], Some(IfMatch::Any));
} }
} }

View file

@ -1,6 +1,6 @@
use super::{HttpDate, IF_MODIFIED_SINCE}; use super::{HttpDate, IF_MODIFIED_SINCE};
crate::header! { crate::__define_common_header! {
/// `If-Modified-Since` header, defined in /// `If-Modified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.3)
/// ///
@ -36,6 +36,6 @@ crate::header! {
test_if_modified_since { test_if_modified_since {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
} }
} }

View file

@ -1,6 +1,6 @@
use super::{EntityTag, IF_NONE_MATCH}; use super::{EntityTag, IF_NONE_MATCH};
crate::header! { crate::__define_common_header! {
/// `If-None-Match` header, defined in /// `If-None-Match` header, defined in
/// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2) /// [RFC7232](https://tools.ietf.org/html/rfc7232#section-3.2)
/// ///
@ -55,11 +55,11 @@ crate::header! {
(IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+} (IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+}
test_if_none_match { test_if_none_match {
test_header!(test1, vec![b"\"xyzzy\""]); crate::__common_header_test!(test1, vec![b"\"xyzzy\""]);
test_header!(test2, vec![b"W/\"xyzzy\""]); crate::__common_header_test!(test2, vec![b"W/\"xyzzy\""]);
test_header!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]); crate::__common_header_test!(test3, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]);
test_header!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]); crate::__common_header_test!(test4, vec![b"W/\"xyzzy\", W/\"r2d2xxxx\", W/\"c3piozzzz\""]);
test_header!(test5, vec![b"*"]); crate::__common_header_test!(test5, vec![b"*"]);
} }
} }

View file

@ -115,7 +115,7 @@ mod test_if_range {
use crate::http::header::*; use crate::http::header::*;
use std::str; use std::str;
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
test_header!(test2, vec![b"\"abc\""]); crate::__common_header_test!(test2, vec![b"\"abc\""]);
test_header!(test3, vec![b"this-is-invalid"], None::<IfRange>); crate::__common_header_test!(test3, vec![b"this-is-invalid"], None::<IfRange>);
} }

View file

@ -1,6 +1,6 @@
use super::{HttpDate, IF_UNMODIFIED_SINCE}; use super::{HttpDate, IF_UNMODIFIED_SINCE};
crate::header! { crate::__define_common_header! {
/// `If-Unmodified-Since` header, defined in /// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
/// ///
@ -37,6 +37,6 @@ crate::header! {
test_if_unmodified_since { test_if_unmodified_since {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]); crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
} }
} }

View file

@ -1,6 +1,6 @@
use super::{HttpDate, LAST_MODIFIED}; use super::{HttpDate, LAST_MODIFIED};
crate::header! { crate::__define_common_header! {
/// `Last-Modified` header, defined in /// `Last-Modified` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2) /// [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.2)
/// ///
@ -36,5 +36,6 @@ crate::header! {
test_last_modified { test_last_modified {
// Test case from RFC // Test case from RFC
test_header!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);} crate::__common_header_test!(test1, vec![b"Sat, 29 Oct 1994 19:43:31 GMT"]);
}
} }

300
src/http/header/macros.rs Normal file
View file

@ -0,0 +1,300 @@
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_deref {
($from:ty => $to:ty) => {
impl ::std::ops::Deref for $from {
type Target = $to;
#[inline]
fn deref(&self) -> &$to {
&self.0
}
}
impl ::std::ops::DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut $to {
&mut self.0
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_test_module {
($id:ident, $tm:ident{$($tf:item)*}) => {
#[allow(unused_imports)]
#[cfg(test)]
mod $tm {
use std::str;
use actix_http::http::Method;
use mime::*;
use $crate::http::header::*;
use super::$id as HeaderField;
$($tf)*
}
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! __common_header_test {
($id:ident, $raw:expr) => {
#[test]
fn $id() {
use actix_http::test;
let raw = $raw;
let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req = req.insert_header((HeaderField::name(), item)).take();
}
let req = req.finish();
let value = HeaderField::parse(&req);
let result = format!("{}", value.unwrap());
let expected = String::from_utf8(raw[0].to_vec()).unwrap();
let result_cmp: Vec<String> = result
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
let expected_cmp: Vec<String> = expected
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
assert_eq!(result_cmp.concat(), expected_cmp.concat());
}
};
($id:ident, $raw:expr, $typed:expr) => {
#[test]
fn $id() {
use actix_http::test;
let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req.insert_header((HeaderField::name(), item));
}
let req = req.finish();
let val = HeaderField::parse(&req);
let typed: Option<HeaderField> = $typed;
// Test parsing
assert_eq!(val.ok(), typed);
// Test formatting
if typed.is_some() {
let raw = &($raw)[..];
let mut iter = raw.iter().map(|b| str::from_utf8(&b[..]).unwrap());
let mut joined = String::new();
joined.push_str(iter.next().unwrap());
for s in iter {
joined.push_str(", ");
joined.push_str(s);
}
assert_eq!(format!("{}", typed.unwrap()), joined);
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __define_common_header {
// $a:meta: Attributes associated with the header item (usually docs)
// $id:ident: Identifier of the header
// $n:expr: Lowercase name of the header
// $nn:expr: Nice name of the header
// List header, zero or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)*) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
crate::__common_header_deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// List header, one or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)+) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
crate::__common_header_deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// Single value header
($(#[$a:meta])*($id:ident, $name:expr) => [$value:ty]) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub $value);
crate::__common_header_deref!($id => $value);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_one_raw_str(
msg.headers().get(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
self.0.try_into_value()
}
}
};
// List header, one or more items with "*" option
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub enum $id {
/// Any value is a match
Any,
/// Only the listed items are a match
Items(Vec<$item>),
}
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
let any = msg.headers().get(Self::name()).and_then(|hdr| {
hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
if let Some(true) = any {
Ok($id::Any)
} else {
Ok($id::Items(
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name()))?))
}
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
$id::Any => f.write_str("*"),
$id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(
f, &fields[..])
}
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// optional test module
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $name) => ($item)*
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $n) => ($item)+
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])* ($id, $name) => [$item]
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
crate::__define_common_header! {
$(#[$a])*
($id, $name) => {Any / ($item)+}
}
crate::__common_header_test_module! { $id, $tm { $($tf)* }}
};
}

View file

@ -2,28 +2,26 @@
//! //!
//! ## Mime //! ## Mime
//! //!
//! Several header fields use MIME values for their contents. Keeping with the //! Several header fields use MIME values for their contents. Keeping with the strongly-typed theme,
//! strongly-typed theme, the [mime] crate //! the [mime] crate is used in such headers as [`ContentType`] and [`Accept`].
//! is used, such as `ContentType(pub Mime)`.
#![cfg_attr(rustfmt, rustfmt_skip)]
use bytes::{Bytes, BytesMut};
use std::fmt; use std::fmt;
use bytes::{BytesMut, Bytes};
pub use actix_http::http::header::*;
pub use self::accept_charset::AcceptCharset; pub use self::accept_charset::AcceptCharset;
pub use actix_http::http::header::*;
//pub use self::accept_encoding::AcceptEncoding; //pub use self::accept_encoding::AcceptEncoding;
pub use self::accept::Accept; pub use self::accept::Accept;
pub use self::accept_language::AcceptLanguage; pub use self::accept_language::AcceptLanguage;
pub use self::allow::Allow; pub use self::allow::Allow;
pub use self::cache_control::{CacheControl, CacheDirective}; pub use self::cache_control::{CacheControl, CacheDirective};
pub use self::content_disposition::{ pub use self::content_disposition::{ContentDisposition, DispositionParam, DispositionType};
ContentDisposition, DispositionParam, DispositionType,
};
pub use self::content_language::ContentLanguage; pub use self::content_language::ContentLanguage;
pub use self::content_range::{ContentRange, ContentRangeSpec}; pub use self::content_range::{ContentRange, ContentRangeSpec};
pub use self::content_type::ContentType; pub use self::content_type::ContentType;
pub use self::date::Date; pub use self::date::Date;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
pub use self::etag::ETag; pub use self::etag::ETag;
pub use self::expires::Expires; pub use self::expires::Expires;
pub use self::if_match::IfMatch; pub use self::if_match::IfMatch;
@ -32,10 +30,10 @@ pub use self::if_none_match::IfNoneMatch;
pub use self::if_range::IfRange; pub use self::if_range::IfRange;
pub use self::if_unmodified_since::IfUnmodifiedSince; pub use self::if_unmodified_since::IfUnmodifiedSince;
pub use self::last_modified::LastModified; pub use self::last_modified::LastModified;
pub use self::encoding::Encoding;
pub use self::entity::EntityTag;
//pub use self::range::{Range, ByteRangeSpec}; //pub use self::range::{Range, ByteRangeSpec};
pub(crate) use actix_http::http::header::{fmt_comma_delimited, from_comma_delimited, from_one_raw_str}; pub(crate) use actix_http::http::header::{
fmt_comma_delimited, from_comma_delimited, from_one_raw_str,
};
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct Writer { struct Writer {
@ -65,309 +63,6 @@ impl fmt::Write for Writer {
} }
} }
#[doc(hidden)]
#[macro_export]
macro_rules! __hyper__deref {
($from:ty => $to:ty) => {
impl ::std::ops::Deref for $from {
type Target = $to;
#[inline]
fn deref(&self) -> &$to {
&self.0
}
}
impl ::std::ops::DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut $to {
&mut self.0
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __hyper__tm {
($id:ident, $tm:ident{$($tf:item)*}) => {
#[allow(unused_imports)]
#[cfg(test)]
mod $tm{
use std::str;
use actix_http::http::Method;
use mime::*;
use $crate::http::header::*;
use super::$id as HeaderField;
$($tf)*
}
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! test_header {
($id:ident, $raw:expr) => {
#[test]
fn $id() {
use actix_http::test;
let raw = $raw;
let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req = req.insert_header((HeaderField::name(), item)).take();
}
let req = req.finish();
let value = HeaderField::parse(&req);
let result = format!("{}", value.unwrap());
let expected = String::from_utf8(raw[0].to_vec()).unwrap();
let result_cmp: Vec<String> = result
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
let expected_cmp: Vec<String> = expected
.to_ascii_lowercase()
.split(' ')
.map(|x| x.to_owned())
.collect();
assert_eq!(result_cmp.concat(), expected_cmp.concat());
}
};
($id:ident, $raw:expr, $typed:expr) => {
#[test]
fn $id() {
use actix_http::test;
let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
let mut req = test::TestRequest::default();
for item in a {
req.insert_header((HeaderField::name(), item));
}
let req = req.finish();
let val = HeaderField::parse(&req);
let typed: Option<HeaderField> = $typed;
// Test parsing
assert_eq!(val.ok(), typed);
// Test formatting
if typed.is_some() {
let raw = &($raw)[..];
let mut iter = raw.iter().map(|b| str::from_utf8(&b[..]).unwrap());
let mut joined = String::new();
joined.push_str(iter.next().unwrap());
for s in iter {
joined.push_str(", ");
joined.push_str(s);
}
assert_eq!(format!("{}", typed.unwrap()), joined);
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! header {
// $a:meta: Attributes associated with the header item (usually docs)
// $id:ident: Identifier of the header
// $n:expr: Lowercase name of the header
// $nn:expr: Nice name of the header
// List header, zero or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)*) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
__hyper__deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// List header, one or more items
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)+) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub Vec<$item>);
__hyper__deref!($id => Vec<$item>);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
$crate::http::header::fmt_comma_delimited(f, &self.0[..])
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// Single value header
($(#[$a:meta])*($id:ident, $name:expr) => [$value:ty]) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub struct $id(pub $value);
__hyper__deref!($id => $value);
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
$crate::http::header::from_one_raw_str(
msg.headers().get(Self::name())).map($id)
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
self.0.try_into_value()
}
}
};
// List header, one or more items with "*" option
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
$(#[$a])*
#[derive(Clone, Debug, PartialEq)]
pub enum $id {
/// Any value is a match
Any,
/// Only the listed items are a match
Items(Vec<$item>),
}
impl $crate::http::header::Header for $id {
#[inline]
fn name() -> $crate::http::header::HeaderName {
$name
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::HttpMessage
{
let any = msg.headers().get(Self::name()).and_then(|hdr| {
hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
if let Some(true) = any {
Ok($id::Any)
} else {
Ok($id::Items(
$crate::http::header::from_comma_delimited(
msg.headers().get_all(Self::name()))?))
}
}
}
impl std::fmt::Display for $id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
$id::Any => f.write_str("*"),
$id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(
f, &fields[..])
}
}
}
impl $crate::http::header::IntoHeaderValue for $id {
type Error = $crate::http::header::InvalidHeaderValue;
fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
use std::fmt::Write;
let mut writer = $crate::http::header::Writer::new();
let _ = write!(&mut writer, "{}", self);
$crate::http::header::HeaderValue::from_maybe_shared(writer.take())
}
}
};
// optional test module
($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $name) => ($item)*
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $n) => ($item)+
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])* ($id, $name) => [$item]
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
header! {
$(#[$a])*
($id, $name) => {Any / ($item)+}
}
__hyper__tm! { $id, $tm { $($tf)* }}
};
}
mod accept_charset; mod accept_charset;
// mod accept_encoding; // mod accept_encoding;
mod accept; mod accept;
@ -379,6 +74,8 @@ mod content_language;
mod content_range; mod content_range;
mod content_type; mod content_type;
mod date; mod date;
mod encoding;
mod entity;
mod etag; mod etag;
mod expires; mod expires;
mod if_match; mod if_match;
@ -387,5 +84,4 @@ mod if_none_match;
mod if_range; mod if_range;
mod if_unmodified_since; mod if_unmodified_since;
mod last_modified; mod last_modified;
mod encoding; mod macros;
mod entity;