use encoding_rs::Encoding;
use super::error::HttpError;
use super::header::{CONTENT_ENCODING, CONTENT_TYPE, HeaderVec};
use super::mimetype;
use super::response_decoding::ContentEncoding;
impl HeaderVec {
pub fn content_type(&self) -> Option<&str> {
self.get(CONTENT_TYPE).map(|h| h.value.as_str())
}
pub fn character_encoding(&self) -> Result<&'static Encoding, HttpError> {
match self.content_type() {
Some(content_type) => match mimetype::charset(content_type) {
Some(charset) => match Encoding::for_label(charset.as_bytes()) {
None => Err(HttpError::InvalidCharset { charset }),
Some(enc) => Ok(enc),
},
None => Ok(encoding_rs::UTF_8),
},
None => Ok(encoding_rs::UTF_8),
}
}
pub fn content_encoding(&self) -> Result<Vec<ContentEncoding>, HttpError> {
for header in self {
if header.name_eq(CONTENT_ENCODING) {
let mut encodings = vec![];
for value in header.value.split(',') {
let encoding = ContentEncoding::parse(value.trim())?;
encodings.push(encoding);
}
return Ok(encodings);
}
}
Ok(vec![])
}
}
#[cfg(test)]
mod tests {
use crate::http::response_decoding::ContentEncoding;
use crate::http::{Header, HeaderVec};
#[test]
fn content_type_basic() {
let mut headers = HeaderVec::new();
headers.push(Header::new("Host", "localhost:8000"));
headers.push(Header::new("Accept", "*/*"));
headers.push(Header::new("User-Agent", "hurl/1.0"));
headers.push(Header::new("content-type", "application/json"));
assert_eq!(headers.content_type(), Some("application/json"));
let mut headers = HeaderVec::new();
headers.push(Header::new("foo", "bar"));
assert_eq!(headers.content_type(), None);
}
#[test]
fn content_encoding() {
let mut headers = HeaderVec::new();
headers.push(Header::new("Content-Encoding", "deflate, gzip"));
assert_eq!(
headers.content_encoding(),
Ok(vec![ContentEncoding::Deflate, ContentEncoding::Gzip])
);
}
#[test]
fn character_encoding() {
let mut headers = HeaderVec::new();
headers.push(Header::new("Content-Type", "text/html; charset=utf-8"));
assert_eq!(headers.character_encoding().unwrap(), encoding_rs::UTF_8);
let mut headers = HeaderVec::new();
headers.push(Header::new("content-type", "text/plain; charset=us-ascii"));
assert_eq!(
headers.character_encoding().unwrap(),
encoding_rs::WINDOWS_1252
);
let mut headers = HeaderVec::new();
headers.push(Header::new("content-type", "text/plain"));
assert_eq!(headers.character_encoding().unwrap(), encoding_rs::UTF_8);
}
}