Skip to main content

fill_range/
lib.rs

1//! # fill-range — fill in a range of numbers or letters
2//!
3//! Expand a range into the sequence of values between its bounds — numbers
4//! (`"1".."5"` → `["1","2","3","4","5"]`), letters (`"a".."e"` →
5//! `["a","b","c","d","e"]`), with an optional step and automatic zero-padding
6//! (`"01".."05"` → `["01",…,"05"]`). A faithful Rust port of the
7//! [`fill-range`](https://www.npmjs.com/package/fill-range) npm package. Zero
8//! dependencies and `#![no_std]`.
9//!
10//! ```
11//! use fill_range::{fill, fill_step};
12//!
13//! assert_eq!(fill("1", "5"), ["1", "2", "3", "4", "5"]);
14//! assert_eq!(fill("a", "e"), ["a", "b", "c", "d", "e"]);
15//! assert_eq!(fill("01", "05"), ["01", "02", "03", "04", "05"]); // auto-padded
16//! assert_eq!(fill("5", "1"), ["5", "4", "3", "2", "1"]);        // descending
17//! assert_eq!(fill_step("0", "10", 2), ["0", "2", "4", "6", "8", "10"]);
18//! ```
19//!
20//! To build a *regex* that matches a numeric range (the `toRegex` option of the npm
21//! package), compose with the [`to-regex-range`](https://crates.io/crates/to-regex-range)
22//! crate.
23
24#![no_std]
25#![doc(html_root_url = "https://docs.rs/fill-range/0.1.0")]
26
27extern crate alloc;
28
29use alloc::format;
30use alloc::string::{String, ToString};
31use alloc::vec::Vec;
32
33// Compile-test the README's examples as part of `cargo test`.
34#[cfg(doctest)]
35#[doc = include_str!("../README.md")]
36struct ReadmeDoctests;
37
38/// Fill in the range from `start` to `end` (inclusive) with a step of 1.
39///
40/// `start` and `end` may both be integers (in either order, optionally zero-padded)
41/// or both single letters. An invalid range yields an empty list.
42///
43/// ```
44/// assert_eq!(fill_range::fill("1", "3"), ["1", "2", "3"]);
45/// ```
46#[must_use]
47pub fn fill(start: &str, end: &str) -> Vec<String> {
48    fill_step(start, end, 1)
49}
50
51/// Fill in the range from `start` to `end` (inclusive) with the given `step`.
52///
53/// The step's magnitude is used (the direction is taken from `start`/`end`); a step
54/// of `0` is treated as `1`.
55///
56/// ```
57/// assert_eq!(fill_range::fill_step("0", "10", 5), ["0", "5", "10"]);
58/// ```
59#[must_use]
60pub fn fill_step(start: &str, end: &str, step: i64) -> Vec<String> {
61    if start.is_empty() || end.is_empty() {
62        return Vec::new();
63    }
64    match (parse_int(start), parse_int(end)) {
65        (Some(a), Some(b)) => fill_numbers(start, end, a, b, step),
66        _ => fill_letters(start, end, step),
67    }
68}
69
70fn fill_numbers(start: &str, end: &str, a: i64, b: i64, step: i64) -> Vec<String> {
71    let descending = a > b;
72    let step_string = step.to_string();
73    let step = step.saturating_abs().max(1);
74
75    let padded = has_leading_zero(start) || has_leading_zero(end) || has_leading_zero(&step_string);
76    let max_len = if padded {
77        start
78            .chars()
79            .count()
80            .max(end.chars().count())
81            .max(step_string.chars().count())
82    } else {
83        0
84    };
85
86    let mut range = Vec::new();
87    let mut a = a;
88    loop {
89        let in_range = if descending { a >= b } else { a <= b };
90        if !in_range {
91            break;
92        }
93        range.push(pad_number(a, max_len));
94        a = if descending {
95            match a.checked_sub(step) {
96                Some(next) => next,
97                None => break,
98            }
99        } else {
100            match a.checked_add(step) {
101                Some(next) => next,
102                None => break,
103            }
104        };
105    }
106    range
107}
108
109fn fill_letters(start: &str, end: &str, step: i64) -> Vec<String> {
110    // A non-numeric bound must be a single (UTF-16) code unit, mirroring the
111    // reference's `length > 1` check.
112    let start_num = parse_int(start).is_some();
113    let end_num = parse_int(end).is_some();
114    if (!start_num && start.encode_utf16().count() > 1)
115        || (!end_num && end.encode_utf16().count() > 1)
116    {
117        return Vec::new();
118    }
119
120    let a0 = start.chars().next().map_or(0i64, |c| c as i64);
121    let b = end.chars().next().map_or(0i64, |c| c as i64);
122    let descending = a0 > b;
123    let step = step.saturating_abs().max(1);
124
125    let mut range = Vec::new();
126    let mut a = a0;
127    loop {
128        let in_range = if descending { a >= b } else { a <= b };
129        if !in_range {
130            break;
131        }
132        let ch = u32::try_from(a)
133            .ok()
134            .and_then(char::from_u32)
135            .map_or_else(String::new, |c| c.to_string());
136        range.push(ch);
137        a = if descending {
138            match a.checked_sub(step) {
139                Some(next) => next,
140                None => break,
141            }
142        } else {
143            match a.checked_add(step) {
144                Some(next) => next,
145                None => break,
146            }
147        };
148    }
149    range
150}
151
152/// Parse `s` as an integer (the reference's `Number.isInteger(+s)` check). Leading
153/// zeros and a leading sign are accepted; values outside `i64` are rejected.
154fn parse_int(s: &str) -> Option<i64> {
155    s.trim().parse::<i64>().ok()
156}
157
158/// Whether `s` has a leading zero (and is not just `"0"`), mirroring the reference's
159/// `zeros` helper.
160fn has_leading_zero(s: &str) -> bool {
161    let v = s.strip_prefix('-').unwrap_or(s);
162    v != "0" && v.starts_with('0')
163}
164
165/// Format `value` zero-padded to `max_len` characters (a sign is kept up front).
166fn pad_number(value: i64, max_len: usize) -> String {
167    let s = value.to_string();
168    if max_len == 0 {
169        return s;
170    }
171    match s.strip_prefix('-') {
172        Some(rest) => {
173            let width = max_len.saturating_sub(1);
174            format!("-{rest:0>width$}")
175        }
176        None => format!("{s:0>max_len$}"),
177    }
178}