nth-check
Parse the CSS An+B microsyntax and test positions — the notation behind
:nth-child(2n+1), :nth-of-type(odd), and :nth-last-child(-n+3). The Rust
counterpart of the nth-check npm package
(behind css-select / cheerio). Zero dependencies and #![no_std] (no alloc).
use parse;
let odd = parse.unwrap; // also: parse("odd")
assert!;
assert!;
let first_three = parse.unwrap;
assert!;
assert!;
let n = parse.unwrap;
assert_eq!; // the a·n + b coefficients
Why nth-check?
Implementing a CSS selector engine, scraper, or linter means evaluating
:nth-child(...). The An+B grammar (odd, even, 2n, -n+3, signed b,
whitespace around the sign) is small but fiddly to parse correctly. Rust had this
only buried inside heavyweight CSS stacks; this is the focused, dependency-free
piece.
[]
= "0.1"
API
| Item | Purpose |
|---|---|
parse(s) |
Parse an An+B string into an [Nth] (Result<Nth, ParseError>) |
Nth::new(a, b) |
Build from coefficients directly |
Nth::a() / Nth::b() |
The a (step) and b (offset) coefficients |
Nth::matches(index) |
Whether the 1-based index matches a·n + b |
Nth also implements FromStr and Display |
"2n+1".parse() / round-trips to canonical form |
Behavior
- Positions are 1-based, matching CSS
:nth-child(the first element is 1). matches(index)istruewhenindex == a·n + bfor some non-negative integern; it never panics (computed in 64-bit internally).- Accepts
odd,even(case-insensitive), a signed integer, and theAn+Bforms with optional whitespace around the middle sign. Follows the CSS grammar strictly: the offset needs an explicit sign (2n+7, not2n7), as browsers require — so malformed input like2 n,n2, or++1is rejected. (This is slightly stricter than node-nth-check's lenient regex; matching is identical where both accept.) Displayrenders a canonical form (2n+1,-n+3,n,3) that round-trips throughparse.
no_std
#![no_std] and core-only — no alloc, no dependencies.
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.