feat(headers): adds Accept
Moved utils to shared/. Added quality_value.
This commit is contained in:
50
src/header/shared/encoding.rs
Normal file
50
src/header/shared/encoding.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
//! Provides an Encoding enum.
|
||||
|
||||
use std::fmt;
|
||||
use std::str;
|
||||
|
||||
pub use self::Encoding::{Chunked, Gzip, Deflate, Compress, Identity, EncodingExt};
|
||||
|
||||
/// A value to represent an encoding used in `Transfer-Encoding`
|
||||
/// or `Accept-Encoding` header.
|
||||
#[deriving(Clone, PartialEq)]
|
||||
pub enum Encoding {
|
||||
/// The `chunked` encoding.
|
||||
Chunked,
|
||||
/// The `gzip` encoding.
|
||||
Gzip,
|
||||
/// The `deflate` encoding.
|
||||
Deflate,
|
||||
/// The `compress` encoding.
|
||||
Compress,
|
||||
/// The `identity` encoding.
|
||||
Identity,
|
||||
/// Some other encoding that is less common, can be any String.
|
||||
EncodingExt(String)
|
||||
}
|
||||
|
||||
impl fmt::Show for Encoding {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
Chunked => "chunked",
|
||||
Gzip => "gzip",
|
||||
Deflate => "deflate",
|
||||
Compress => "compress",
|
||||
Identity => "identity",
|
||||
EncodingExt(ref s) => s.as_slice()
|
||||
}.fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
impl str::FromStr for Encoding {
|
||||
fn from_str(s: &str) -> Option<Encoding> {
|
||||
match s {
|
||||
"chunked" => Some(Chunked),
|
||||
"deflate" => Some(Deflate),
|
||||
"gzip" => Some(Gzip),
|
||||
"compress" => Some(Compress),
|
||||
"identity" => Some(Identity),
|
||||
_ => Some(EncodingExt(s.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
26
src/header/shared/mod.rs
Normal file
26
src/header/shared/mod.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Various functions, structs and enums useful for many headers.
|
||||
|
||||
pub use self::encoding::Encoding;
|
||||
pub use self::encoding::Encoding::{
|
||||
Chunked,
|
||||
Gzip,
|
||||
Deflate,
|
||||
Compress,
|
||||
Identity,
|
||||
EncodingExt};
|
||||
|
||||
pub use self::quality_item::QualityItem;
|
||||
pub use self::quality_item::qitem;
|
||||
|
||||
pub use self::time::tm_from_str;
|
||||
|
||||
pub use self::util::{
|
||||
from_one_raw_str,
|
||||
from_comma_delimited,
|
||||
from_one_comma_delimited,
|
||||
fmt_comma_delimited};
|
||||
|
||||
pub mod encoding;
|
||||
pub mod quality_item;
|
||||
pub mod time;
|
||||
pub mod util;
|
||||
123
src/header/shared/quality_item.rs
Normal file
123
src/header/shared/quality_item.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
//! Provides a struct for quality values.
|
||||
//!
|
||||
//! [RFC7231 Section 5.3.1](https://tools.ietf.org/html/rfc7231#section-5.3.1)
|
||||
//! gives more information on quality values in HTTP header fields.
|
||||
|
||||
use std::fmt;
|
||||
use std::str;
|
||||
#[cfg(test)] use super::encoding::*;
|
||||
|
||||
/// Represents an item with a quality value as defined in
|
||||
/// [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.1).
|
||||
#[deriving(Clone, PartialEq)]
|
||||
pub struct QualityItem<T> {
|
||||
/// The actual contents of the field.
|
||||
pub item: T,
|
||||
/// The quality (client or server preference) for the value.
|
||||
pub quality: f32,
|
||||
}
|
||||
|
||||
impl<T> QualityItem<T> {
|
||||
/// Creates a new `QualityItem` from an item and a quality.
|
||||
/// The item can be of any type.
|
||||
/// The quality should be a value in the range [0, 1].
|
||||
pub fn new(item: T, quality: f32) -> QualityItem<T> {
|
||||
QualityItem{item: item, quality: quality}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Show> fmt::Show for QualityItem<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: str::FromStr> str::FromStr for QualityItem<T> {
|
||||
fn from_str(s: &str) -> Option<Self> {
|
||||
// Set defaults used if parsing fails.
|
||||
let mut raw_item = s;
|
||||
let mut quality = 1f32;
|
||||
|
||||
let parts: Vec<&str> = s.rsplitn(1, ';').map(|x| x.trim()).collect();
|
||||
if parts.len() == 2 {
|
||||
let start = parts[0].slice(0, 2);
|
||||
if start == "q=" || start == "Q=" {
|
||||
let q_part = parts[0].slice(2, parts[0].len());
|
||||
if q_part.len() > 5 {
|
||||
return None;
|
||||
}
|
||||
let x: Option<f32> = q_part.parse();
|
||||
match x {
|
||||
Some(q_value) => {
|
||||
if 0f32 <= q_value && q_value <= 1f32 {
|
||||
quality = q_value;
|
||||
raw_item = parts[1];
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
},
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
let x: Option<T> = raw_item.parse();
|
||||
match x {
|
||||
Some(item) => {
|
||||
Some(QualityItem{ item: item, quality: quality, })
|
||||
},
|
||||
None => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Convinience function to wrap a value in a `QualityItem`
|
||||
/// Sets `q` to the default 1.0
|
||||
pub fn qitem<T>(item: T) -> QualityItem<T> {
|
||||
QualityItem::new(item, 1.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_quality_item_show1() {
|
||||
let x = qitem(Chunked);
|
||||
assert_eq!(format!("{}", x), "chunked; q=1.000");
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_show2() {
|
||||
let x = QualityItem::new(Chunked, 0.001);
|
||||
assert_eq!(format!("{}", x), "chunked; q=0.001");
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_show3() {
|
||||
// Custom value
|
||||
let x = QualityItem{
|
||||
item: EncodingExt("identity".to_string()),
|
||||
quality: 0.5f32,
|
||||
};
|
||||
assert_eq!(format!("{}", x), "identity; q=0.500");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_quality_item_from_str1() {
|
||||
let x: Option<QualityItem<Encoding>> = "chunked".parse();
|
||||
assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_from_str2() {
|
||||
let x: Option<QualityItem<Encoding>> = "chunked; q=1".parse();
|
||||
assert_eq!(x.unwrap(), QualityItem{ item: Chunked, quality: 1f32, });
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_from_str3() {
|
||||
let x: Option<QualityItem<Encoding>> = "gzip; q=0.5".parse();
|
||||
assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.5f32, });
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_from_str4() {
|
||||
let x: Option<QualityItem<Encoding>> = "gzip; q=0.273".parse();
|
||||
assert_eq!(x.unwrap(), QualityItem{ item: Gzip, quality: 0.273f32, });
|
||||
}
|
||||
#[test]
|
||||
fn test_quality_item_from_str5() {
|
||||
let x: Option<QualityItem<Encoding>> = "gzip; q=0.2739999".parse();
|
||||
assert_eq!(x, None);
|
||||
}
|
||||
34
src/header/shared/time.rs
Normal file
34
src/header/shared/time.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
//! Provides utility function to parse HTTP header value time.
|
||||
|
||||
extern crate time;
|
||||
|
||||
/// 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<time::Tm> {
|
||||
time::strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
|
||||
time::strptime(s, "%A, %d-%b-%y %T %Z")
|
||||
}).or_else(|_| {
|
||||
time::strptime(s, "%c")
|
||||
}).ok()
|
||||
}
|
||||
52
src/header/shared/util.rs
Normal file
52
src/header/shared/util.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
//! Utility functions for Header implementations.
|
||||
|
||||
use std::str;
|
||||
use std::fmt;
|
||||
|
||||
/// Reads a single raw string when parsing a header
|
||||
pub fn from_one_raw_str<T: str::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 str::from_utf8(unsafe { raw[].unsafe_get(0)[] }) {
|
||||
Ok(s) => str::FromStr::from_str(s),
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a comma-delimited raw header into a Vec.
|
||||
#[inline]
|
||||
pub fn from_comma_delimited<T: str::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().unsafe_get(0).as_slice() })
|
||||
}
|
||||
|
||||
/// Reads a comma-delimited raw string into a Vec.
|
||||
pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> {
|
||||
match str::from_utf8(raw) {
|
||||
Ok(s) => {
|
||||
Some(s.as_slice()
|
||||
.split(',')
|
||||
.map(|x| x.trim())
|
||||
.filter_map(str::FromStr::from_str)
|
||||
.collect())
|
||||
}
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
|
||||
/// Format an array into a comma-delimited string.
|
||||
pub fn fmt_comma_delimited<T: fmt::Show>(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
|
||||
let last = parts.len() - 1;
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
try!(write!(fmt, "{}", part));
|
||||
if i < last {
|
||||
try!(write!(fmt, ", "));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user