parse-srcset
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;
let candidates = parse_srcset;
assert_eq!;
assert_eq!;
assert_eq!; // bare fallback URL
let dpr = parse_srcset;
assert_eq!;
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.
[]
= "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
0xdensity and0w/0hare treated as the reference does (density0is dropped;0w/0hare 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.