wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Port of Laravel Framework's `Number::abbreviate()`.
//! Original: <https://github.com/laravel/framework/blob/12.x/src/Illuminate/Support/Number.php>
//! Laravel is created by Taylor Otwell and licensed under the MIT License.

use std::io::Write;

use clap::Args;
use wdxtools::number::{append_abbreviate, append_for_humans, Config};

use super::date::parse_i64;
use super::io::{stdin_is_pipe, write_lines, Output};

#[derive(Args, Debug)]
#[command(
    about = "Abbreviate numbers for humans",
    long_about = "Abbreviate numbers for humans (port of Laravel Number::abbreviate).",
    // Lets negative numbers be passed positionally: `numcrn -1000`.
    allow_negative_numbers = true,
    after_help = "\x1b[1mExamples:\x1b[0m
  wdxtools numcrn 489939          # 490K
  wdxtools numcrn -m 2 489939     # 489.94K
  wdxtools numcrn -l 1000000      # 1 million
  echo 1000 | wdxtools numcrn     # 1K"
)]
pub struct NumcrnArgs {
    /// Minimum decimal places (precision)
    #[arg(short, long, default_value_t = 0)]
    precision: i32,

    /// Maximum decimal places (-1 = unset)
    #[arg(short = 'm', long = "max-precision", default_value_t = -1)]
    max_precision: i32,

    /// Use long form (thousand, million, ...)
    #[arg(short, long)]
    long: bool,

    #[arg(value_name = "NUMBER")]
    numbers: Vec<String>,
}

pub fn run(args: NumcrnArgs) -> i32 {
    let cfg = Config {
        precision: args.precision,
        max_precision: args.max_precision,
    };
    let append = if args.long {
        append_for_humans
    } else {
        append_abbreviate
    };

    let mut out = Output::new();
    let mut buf = String::with_capacity(64);

    if !args.numbers.is_empty() {
        for arg in &args.numbers {
            let Some(n) = parse_number(arg) else {
                return out.fail(&format!("numcrn: invalid number: {arg:?}"));
            };
            buf.clear();
            append(&mut buf, n, cfg);
            buf.push('\n');
            let _ = out.write_all(buf.as_bytes());
        }
        return out.finish();
    }

    if !stdin_is_pipe() {
        super::print_help("numcrn");
        return 0;
    }

    let mut failed = None;
    write_lines(&mut out, |line, out| {
        let Some(n) = parse_number(line) else {
            failed = Some(format!("numcrn: invalid number: {line:?}"));
            return false;
        };
        buf.clear();
        append(&mut buf, n, cfg);
        buf.push('\n');
        let _ = out.write_all(buf.as_bytes());
        true
    });

    match failed {
        Some(msg) => out.fail(&msg),
        None => out.finish(),
    }
}

/// Integer fast path: most batch input is plain integers, and the integer
/// parser skips the full float decoder.
fn parse_number(s: &str) -> Option<f64> {
    let s = s.trim();
    if let Some(i) = parse_i64(s) {
        return Some(i as f64);
    }
    s.parse::<f64>().ok().filter(|f| f.is_finite())
}