parse-srcset 0.1.1

Parse an HTML img srcset attribute into image candidates (url + density/width/height). A faithful port of the WHATWG-based parse-srcset npm package. Zero dependencies, no_std.
Documentation
  • Coverage
  • 100%
    7 out of 7 items documented2 out of 3 items with examples
  • Size
  • Source code size: 31.96 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 201.92 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 2s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/parse-srcset
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

parse-srcset

All Contributors

Crates.io Documentation CI License

Parse an HTML srcset attribute into its image candidates — each a URL plus an optional density (x), width (w), or height (h) descriptor. A faithful Rust port of the parse-srcset npm package, which implements the WHATWG algorithm. Zero dependencies and #![no_std].

use parse_srcset::parse_srcset;

let candidates = parse_srcset("small.jpg 480w, large.jpg 800w, fallback.jpg");
assert_eq!(candidates[0].url, "small.jpg");
assert_eq!(candidates[0].width, Some(480));
assert_eq!(candidates[2].width, None); // bare fallback URL

let dpr = parse_srcset("img.png 1x, img@2x.png 2x");
assert_eq!(dpr[1].density, Some(2.0));

Why parse-srcset?

Responsive-image tooling — build steps, SSR, image CDNs, linters — needs to read the candidates out of a srcset string. The grammar has corners (commas inside data URLs, descriptor validation, the w/x/h rules) that the canonical JS parser already nails; this ports it faithfully so Rust tooling matches the browser.

[dependencies]
parse-srcset = "0.1"

API

Item Purpose
parse_srcset(input) Vec<ImageCandidate>
ImageCandidate { url, density, width, height } A URL and its optional x/w/h descriptor

Behavior

  • Candidates are separated by commas; surrounding whitespace is ignored and empty candidates are dropped.
  • A URL may contain commas (e.g. a data: URI); a trailing comma just ends the URL.
  • Exactly one of density/width is allowed per candidate (plus an optional height); a candidate with conflicting or malformed descriptors is skipped, matching the reference implementation.
  • A 0x density and 0w/0h are treated as the reference does (density 0 is dropped; 0w/0h are errors).

Contributors ✨

This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.

Thanks goes to these wonderful people:

License

Licensed under either of Apache-2.0 or MIT at your option.