mediatype 0.17.0

MIME Media-type parsing
Documentation

MediaType

MIME Media-type parsing for Rust

Crates.io GitHub license Rustdoc Rust

Parsing

let text = "text/plain; charset=UTF-8";
let text_plain = MediaType::parse(text).unwrap();

Construction

MediaType is const-construtible: it can be defained as a constant.

Predefind names and values are defined in names and values modules.

use mediatype::{names::*, values::*, MediaType};

const TEXT_PLAIN: MediaType = MediaType::new(TEXT, PLAIN);
const IMAGE_SVG: MediaType = MediaType::from_parts(TEXT, PLAIN, Some(XML), &[(CHARSET, UTF_8)]);

Parameters

Case Sensitivity

Comparisons are case-insensitive except parameter values.

let text_plain_lower = MediaType::parse("text/plain; charset=UTF-8").unwrap();
let text_plain_upper = MediaType::parse("TEXT/PLAIN; CHARSET=UTF-8").unwrap();

assert_eq!(text_plain_lower, text_plain_upper);
assert_eq!(text_plain_lower.ty(), "Text");
assert_eq!(text_plain_upper.subty(), "Plain");
assert!(text_plain_lower != MediaType::parse("text/plain; charset=utf-8").unwrap());

Duplicate Parameter Names

The parser does not report duplicate parameter names as an error, but recognizes only the last value.

let text_plain = MediaType::parse("text/plain; charset=US-ASCII; charset=UTF-8").unwrap();

assert_eq!(text_plain.to_stirng(), "text/plain; charset=US-ASCII; charset=UTF-8");
assert_eq!(text_plain.get(CHARSET), Some(UTF_8));
assert_eq!(text_plain, MediaType::parse("text/plain; charset=UTF-8").unwrap());

Quoted String

let text_plain = MediaType::parse("text/plain; message=\"Hello world!\"").unwrap();
let message = text_plain.get_param(Name::new("message").unwrap()).unwrap();

assert_eq!(message, "Hello world!");
assert_eq!(message.as_str(), "\"Hello world!\"");
assert_eq!(message.unquoted_str(), "Hello world!");
let mut text_plain = MediaType::parse("text/plain").unwrap();

let quoted = Value::quote("Hello world!");
let value = Value::new(&quoted).unwrap();
text_plain.set_param(Name::new("message").unwrap(), value);

assert_eq!(text_plain.to_string(), "text/plain; message=\"Hello world!\"");

Mutation

let mut multipart = MediaType::new(MULTIPART, FORM_DATA);

let boundary = Value::new("dyEV84n7XNJ").unwrap();
multipart.set_param(BOUNDARY, boundary);
assert_eq!(
     multipart.to_string(),
     "multipart/form-data; boundary=dyEV84n7XNJ"
);

multipart.subty = RELATED;
assert_eq!(
    multipart.to_string(),
    "multipart/related; boundary=dyEV84n7XNJ"
);

Owned Type

MediaTypeBuf is an owned and immutable version of MediaType.

use mediatype::{names::*, values::*, MediaType, MediaTypeBuf};

let text_plain: MediaTypeBuf = "text/plain; charset=UTF-8".parse().unwrap();
assert_eq!(text_plain.get_param(CHARSET).unwrap(), UTF_8);

let mut text_markdown: MediaType = text_plain.to_ref();
text_markdown.subty = MARKDOWN;
assert_eq!(text_markdown.to_string(), "text/markdown; charset=UTF-8");