ctb_formats_math/
range_generator.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Generator for ranges of numbers in various number bases.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, ensure};
30use malachite::base::num::arithmetic::traits::UnsignedAbs;
31use malachite::base::num::basic::traits::Zero;
32use malachite::{Integer, Natural};
33
34use crate::base::Base;
35use crate::parsing::{ParsedNumber, format_scaled};
36
37/// Generates a vector of strings representing numbers in the given base from
38/// `start` to `end` (inclusive) stepping by `step`. The width of the start
39/// string sets the minimum output width for zero-padding.
40#[expect(
41    clippy::arithmetic_side_effects,
42    reason = "Natural and Integer are arbitrary-precision and cannot overflow"
43)]
44pub fn range(
45    base: Base,
46    start: &str,
47    end: &str,
48    step: &str,
49) -> Result<Vec<String>> {
50    let start_num = ParsedNumber::parse(start, base)?;
51    let end_num = ParsedNumber::parse(end, base)?;
52    let step_str = if step.is_empty() { "1" } else { step };
53    let step_base = if base.radix() == 64 {
54        Base::Decimal
55    } else {
56        base
57    };
58    let step_num = ParsedNumber::parse(step_str, step_base)?;
59
60    let dec_places = start_num
61        .frac_len
62        .max(end_num.frac_len)
63        .max(step_num.frac_len);
64
65    let has_decimal =
66        start_num.has_decimal || end_num.has_decimal || step_num.has_decimal;
67
68    let start_val = start_num.to_scaled_integer(dec_places)?;
69    let end_val = end_num.to_scaled_integer(dec_places)?;
70    let step_raw = step_num.to_scaled_integer(dec_places)?;
71    let step_val = step_raw.unsigned_abs();
72    ensure!(step_val > Natural::ZERO, "Step cannot be zero");
73    let step_int = Integer::from(step_val);
74
75    let mut result = Vec::new();
76
77    if start_val <= end_val {
78        let mut curr = start_val;
79        while curr <= end_val {
80            result.push(format_scaled(
81                &curr,
82                base,
83                dec_places,
84                start_num.int_width,
85                start_num.frac_len,
86                has_decimal,
87            )?);
88            curr += &step_int;
89        }
90    } else {
91        let mut curr = start_val;
92        while curr >= end_val {
93            result.push(format_scaled(
94                &curr,
95                base,
96                dec_places,
97                start_num.int_width,
98                start_num.frac_len,
99                has_decimal,
100            )?);
101            curr -= &step_int;
102        }
103    }
104
105    Ok(result)
106}
107
108/// Generates a formatted string of numbers from `range`, joined by `separator`
109/// with no trailing separator.
110#[must_use]
111pub fn range_format(range: &[String], separator: &str) -> String {
112    range.join(separator)
113}
114
115/// Generates a formatted string of numbers from `range`, with `separator`
116/// appended to every item (including the trailing one).
117#[must_use]
118pub fn range_format_trailing(range: &[String], separator: &str) -> String {
119    let mut out = String::new();
120    for item in range {
121        out.push_str(item);
122        out.push_str(separator);
123    }
124    out
125}
126
127/// Alias for [`range_format_trailing`].
128#[must_use]
129pub fn range_trailing(range: &[String], separator: &str) -> String {
130    range_format_trailing(range, separator)
131}
132
133/// Arguments for the `range_gen` CLI command.
134#[derive(clap::Args, Debug, Clone)]
135#[command(
136    after_help = "Examples:\n  $ ctoolbox range_gen 1 10\n  1\n  2\n  3\n  4\n  5\n  6\n  7\n  8\n  9\n  10\n\n  $ ctoolbox range_gen -s 2 1 10\n  1\n  3\n  5\n  7\n  9\n\n  $ ctoolbox range_gen -b 16 -t -S, 18D0C 18D12\n  18D0C,18D0D,18D0E,18D0F,18D10,18D11,18D12,\n\n  $ ctoolbox range_gen -b hex 0x00 0x10\n  00\n  01\n  02\n  03\n  04\n  05\n  06\n  07\n  08\n  09\n  0A\n  0B\n  0C\n  0D\n  0E\n  0F\n  10"
137)]
138pub struct RangeGenArgs {
139    /// Starting value of the range
140    pub start: String,
141    /// Ending value of the range
142    pub end: String,
143    /// Step size (defaults to "1")
144    #[arg(short, long, default_value = "1")]
145    pub step: String,
146    /// Number base (e.g. "10", "16", "2", "64", "hex", "bin", "oct")
147    #[arg(short, long, default_value = "10")]
148    pub base: String,
149    /// Separator between output items (defaults to newline)
150    #[arg(short = 'S', long, default_value = "\n")]
151    pub separator: String,
152    /// Append a trailing separator to the output
153    #[arg(short, long)]
154    pub trailing: bool,
155}
156
157/// CLI tool handler for range generation.
158pub fn range_cli_handler(args: &RangeGenArgs) -> Result<String> {
159    let base = Base::from_str_or_name(&args.base)?;
160    let items = range(base, &args.start, &args.end, &args.step)?;
161    if args.trailing {
162        Ok(range_format_trailing(&items, &args.separator))
163    } else {
164        Ok(range_format(&items, &args.separator))
165    }
166}
167
168#[cfg(test)]
169#[allow(
170    clippy::panic,
171    clippy::expect_used,
172    clippy::unwrap_used,
173    clippy::unwrap_in_result,
174    clippy::panic_in_result_fn,
175    clippy::indexing_slicing,
176    clippy::arithmetic_side_effects,
177    reason = "Standard repository test boilerplate"
178)]
179mod tests {
180    use super::*;
181    use crate::base;
182
183    #[crate::ctb_test]
184    fn test_range_hex() -> Result<()> {
185        let items = range(base::Hex, "0A", "12", "1")?;
186        assert_eq!(
187            items,
188            vec!["0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12"]
189        );
190
191        let formatted = range_format(&range(base::Hex, "0A", "12", "1")?, ", ");
192        assert_eq!(formatted, "0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12");
193        Ok(())
194    }
195
196    #[crate::ctb_test]
197    fn test_range_hex_prefix() -> Result<()> {
198        let items = range(base::Hex, "0x00", "0x10", "1")?;
199        assert_eq!(items.len(), 17);
200        assert_eq!(items.first().map(String::as_str), Some("00"));
201        assert_eq!(items.last().map(String::as_str), Some("10"));
202        Ok(())
203    }
204
205    #[crate::ctb_test]
206    fn test_range_trailing_decimal() -> Result<()> {
207        let formatted =
208            range_trailing(&range(base::Decimal, "9", "12", "1")?, "\n");
209        assert_eq!(formatted, "9\n10\n11\n12\n");
210
211        let formatted2 =
212            range_format_trailing(&range(base::Decimal, "9", "12", "1")?, "\n");
213        assert_eq!(formatted2, "9\n10\n11\n12\n");
214        Ok(())
215    }
216
217    #[crate::ctb_test]
218    fn test_range_descending() -> Result<()> {
219        let items = range(base::Decimal, "05", "02", "1")?;
220        assert_eq!(items, vec!["05", "04", "03", "02"]);
221        let items = range(base::Decimal, "02", "-2", "1")?;
222        assert_eq!(items, vec!["02", "01", "00", "-01", "-02"]);
223        let items = range(base::Decimal, "0.010", "-0.010", "0.02")?;
224        assert_eq!(items, vec!["0.010", "-0.010"]);
225        Ok(())
226    }
227
228    #[crate::ctb_test]
229    fn test_range_single_value() -> Result<()> {
230        let items = range(base::Decimal, "42", "42", "1")?;
231        assert_eq!(items, vec!["42"]);
232        Ok(())
233    }
234
235    #[crate::ctb_test]
236    fn test_range_base64() -> Result<()> {
237        let b64 = Base::new(64)?;
238        let items = range(b64, "A", "D", "1")?;
239        assert_eq!(items, vec!["A", "B", "C", "D"]);
240        let items = range(b64, "9", "/", "1")?;
241        assert_eq!(items, vec!["9", "+", "/"]);
242        Ok(())
243    }
244}