fill-range 0.1.0

Fill in a range of numbers or letters: fill("1","5") -> [1,2,3,4,5], fill("a","e") -> [a,b,c,d,e]. A faithful port of the fill-range npm package. Zero dependencies, no_std.
Documentation
//! # fill-range — fill in a range of numbers or letters
//!
//! Expand a range into the sequence of values between its bounds — numbers
//! (`"1".."5"` → `["1","2","3","4","5"]`), letters (`"a".."e"` →
//! `["a","b","c","d","e"]`), with an optional step and automatic zero-padding
//! (`"01".."05"` → `["01",…,"05"]`). A faithful Rust port of the
//! [`fill-range`](https://www.npmjs.com/package/fill-range) npm package. Zero
//! dependencies and `#![no_std]`.
//!
//! ```
//! use fill_range::{fill, fill_step};
//!
//! assert_eq!(fill("1", "5"), ["1", "2", "3", "4", "5"]);
//! assert_eq!(fill("a", "e"), ["a", "b", "c", "d", "e"]);
//! assert_eq!(fill("01", "05"), ["01", "02", "03", "04", "05"]); // auto-padded
//! assert_eq!(fill("5", "1"), ["5", "4", "3", "2", "1"]);        // descending
//! assert_eq!(fill_step("0", "10", 2), ["0", "2", "4", "6", "8", "10"]);
//! ```
//!
//! To build a *regex* that matches a numeric range (the `toRegex` option of the npm
//! package), compose with the [`to-regex-range`](https://crates.io/crates/to-regex-range)
//! crate.

#![no_std]
#![doc(html_root_url = "https://docs.rs/fill-range/0.1.0")]

extern crate alloc;

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

// Compile-test the README's examples as part of `cargo test`.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

/// Fill in the range from `start` to `end` (inclusive) with a step of 1.
///
/// `start` and `end` may both be integers (in either order, optionally zero-padded)
/// or both single letters. An invalid range yields an empty list.
///
/// ```
/// assert_eq!(fill_range::fill("1", "3"), ["1", "2", "3"]);
/// ```
#[must_use]
pub fn fill(start: &str, end: &str) -> Vec<String> {
    fill_step(start, end, 1)
}

/// Fill in the range from `start` to `end` (inclusive) with the given `step`.
///
/// The step's magnitude is used (the direction is taken from `start`/`end`); a step
/// of `0` is treated as `1`.
///
/// ```
/// assert_eq!(fill_range::fill_step("0", "10", 5), ["0", "5", "10"]);
/// ```
#[must_use]
pub fn fill_step(start: &str, end: &str, step: i64) -> Vec<String> {
    if start.is_empty() || end.is_empty() {
        return Vec::new();
    }
    match (parse_int(start), parse_int(end)) {
        (Some(a), Some(b)) => fill_numbers(start, end, a, b, step),
        _ => fill_letters(start, end, step),
    }
}

fn fill_numbers(start: &str, end: &str, a: i64, b: i64, step: i64) -> Vec<String> {
    let descending = a > b;
    let step_string = step.to_string();
    let step = step.saturating_abs().max(1);

    let padded = has_leading_zero(start) || has_leading_zero(end) || has_leading_zero(&step_string);
    let max_len = if padded {
        start
            .chars()
            .count()
            .max(end.chars().count())
            .max(step_string.chars().count())
    } else {
        0
    };

    let mut range = Vec::new();
    let mut a = a;
    loop {
        let in_range = if descending { a >= b } else { a <= b };
        if !in_range {
            break;
        }
        range.push(pad_number(a, max_len));
        a = if descending {
            match a.checked_sub(step) {
                Some(next) => next,
                None => break,
            }
        } else {
            match a.checked_add(step) {
                Some(next) => next,
                None => break,
            }
        };
    }
    range
}

fn fill_letters(start: &str, end: &str, step: i64) -> Vec<String> {
    // A non-numeric bound must be a single (UTF-16) code unit, mirroring the
    // reference's `length > 1` check.
    let start_num = parse_int(start).is_some();
    let end_num = parse_int(end).is_some();
    if (!start_num && start.encode_utf16().count() > 1)
        || (!end_num && end.encode_utf16().count() > 1)
    {
        return Vec::new();
    }

    let a0 = start.chars().next().map_or(0i64, |c| c as i64);
    let b = end.chars().next().map_or(0i64, |c| c as i64);
    let descending = a0 > b;
    let step = step.saturating_abs().max(1);

    let mut range = Vec::new();
    let mut a = a0;
    loop {
        let in_range = if descending { a >= b } else { a <= b };
        if !in_range {
            break;
        }
        let ch = u32::try_from(a)
            .ok()
            .and_then(char::from_u32)
            .map_or_else(String::new, |c| c.to_string());
        range.push(ch);
        a = if descending {
            match a.checked_sub(step) {
                Some(next) => next,
                None => break,
            }
        } else {
            match a.checked_add(step) {
                Some(next) => next,
                None => break,
            }
        };
    }
    range
}

/// Parse `s` as an integer (the reference's `Number.isInteger(+s)` check). Leading
/// zeros and a leading sign are accepted; values outside `i64` are rejected.
fn parse_int(s: &str) -> Option<i64> {
    s.trim().parse::<i64>().ok()
}

/// Whether `s` has a leading zero (and is not just `"0"`), mirroring the reference's
/// `zeros` helper.
fn has_leading_zero(s: &str) -> bool {
    let v = s.strip_prefix('-').unwrap_or(s);
    v != "0" && v.starts_with('0')
}

/// Format `value` zero-padded to `max_len` characters (a sign is kept up front).
fn pad_number(value: i64, max_len: usize) -> String {
    let s = value.to_string();
    if max_len == 0 {
        return s;
    }
    match s.strip_prefix('-') {
        Some(rest) => {
            let width = max_len.saturating_sub(1);
            format!("-{rest:0>width$}")
        }
        None => format!("{s:0>max_len$}"),
    }
}