Skip to main content

Crate dataurl

Crate dataurl 

Source
Expand description

Parsing and generating data: URLs.

Parsing follows the data: URL processor from the WHATWG Fetch Standard, which is what browsers implement (RFC 2397 describes the scheme, but it’s not what the web runs on). The implementation is checked against the Web Platform Tests suites for data URLs, forgiving base64, and MIME type parsing.

use dataurl::{DataEncoding, DataUrl, Escaping};

let data_url: DataUrl = "data:,Hello,%20World!".parse()?;
assert_eq!(data_url.media_type(), "text/plain");
assert_eq!(data_url.mime_type().to_string(), "text/plain;charset=US-ASCII");
assert_eq!(data_url.charset(), "US-ASCII");
assert_eq!(data_url.data(), b"Hello, World!");
assert_eq!(data_url.text(), "Hello, World!");

let mut data_url = DataUrl::new();
data_url.set_media_type(Some("image/png"))?;
data_url.set_data_encoding(DataEncoding::Base64);
data_url.set_data([0x89, 0x50, 0x4E, 0x47]);
assert_eq!(data_url.to_string(), "data:image/png;base64,iVBORw==");

// For text, percent-encoding with minimal escaping is often much shorter than base64
let mut data_url = DataUrl::new();
data_url.set_media_type(Some("image/svg+xml"))?;
data_url.set_data_encoding(DataEncoding::Shortest);
data_url.set_escaping(Escaping::Minimal);
data_url.set_data(b"<svg xmlns='http://www.w3.org/2000/svg'><circle r='4'/></svg>");
assert_eq!(
    data_url.to_string(),
    "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle r='4'/%3E%3C/svg%3E"
);

If you only need to read data URLs, especially in no_std code, the data-url crate from the Servo project is a leaner alternative; this crate is for creating and modifying them, decoding text in other charsets, and detecting media types (see the comparison).

Re-exports§

pub use mime::MimeType;

Modules§

mime
MIME type parsing and serialization, as defined by the WHATWG MIME Sniffing Standard (https://mimesniff.spec.whatwg.org/#parsing-a-mime-type).

Structs§

DataUrl
A parsed (or under construction) data URL.

Enums§

DataEncoding
How the data part of a data URL gets encoded when serializing.
Error
Errors returned when parsing or modifying a DataUrl.
Escaping
How much of the data gets escaped when it’s percent-encoded.

Functions§

detect_media_type
Guesses the media type of data, e.g. "image/png".
extension_for_media_type
Suggests a file extension (without the dot) for a media type, e.g. "png" for "image/png".