#generic-range #range

range-parser

A rust library to parse ranges representation of any kind of numbers

3 releases

0.1.2 Jul 22, 2024
0.1.1 Jul 8, 2024
0.1.0 Jul 8, 2024

#185 in Parser tooling

Download history 1206/week @ 2026-02-19 1250/week @ 2026-02-26 1418/week @ 2026-03-05 1455/week @ 2026-03-12 960/week @ 2026-03-19 750/week @ 2026-03-26 739/week @ 2026-04-02 920/week @ 2026-04-09 961/week @ 2026-04-16 874/week @ 2026-04-23 913/week @ 2026-04-30 1999/week @ 2026-05-07 1217/week @ 2026-05-14 1117/week @ 2026-05-21 991/week @ 2026-05-28 997/week @ 2026-06-04

4,574 downloads per month
Used in 2 crates

MIT license

17KB
212 lines

range-parser

license-mit build-test downloads latest version Conventional Commits docs



About range-parser

range-parser is a simple Rust crate to parse range from text representation (e.g. 1-3,5-8, 1,3,4, 1-5) into a Vector containing all the items for that range.

Get started

  1. Include range-parser to your Cargo.toml

    range-parser = "0.1"
    
  2. Parse range from str

    let range_str = "1-3,5-8";
    let range: Vec<u64> = range_parser::parse(range_str).unwrap();
    
    assert_eq!(&range, &[1, 2, 3, 5, 6, 7, 8]);
    

Supported types

range-parser supports any kind of number primitive.

range-parser for custom types

It is possible to extend the range-parser for custom types as long as they satisfy these trait bounds: T: FromStr + Add<Output = T> + PartialEq + PartialOrd + Unit + Copy,.

This requires you to implement the trait Unit which is exposed by this library.

The trait Unit is defined as

pub trait Unit {
    fn unit() -> Self;
}

and should return the base unit for a type, which for numbers should be 1.

Examples

Parse a range with a dash

let range: Vec<u64> = range_parser::parse("1-3").unwrap();
assert_eq!(range, vec![1, 2, 3]);

Parse a range with commas

let range: Vec<u64> = range_parser::parse("1,3,4").unwrap();
assert_eq!(range, vec![1, 3, 4]);

Parse a mixed range

let range: Vec<u64> = range_parser::parse("1,3-5,2").unwrap();
assert_eq!(range, vec![1, 3, 4, 5, 2]);

Parse a range with negative numbers

let range: Vec<i32> = range_parser::parse("-8,-5--1,0-3,-1").unwrap();
assert_eq!(range, vec![-8, -5, -4, -3, -2, -1, 0, 1, 2, 3, -1]);

Parse a range with custom separators

// parse range using `;` as separator for values and `..` as separator for ranges
let range: Vec<i32> = range_parser::parse_with("-2;0..3;-1;7", ";", "..").unwrap();
assert_eq!(range, vec![-2, 0, 1, 2, 3, -1, 7]);

Changelog

View range-parser's changelog HERE


License

range-parser is licensed under the MIT license.

You can read the entire license HERE

Dependencies

~120–480KB
~11K SLoC