wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
use super::interval::Interval;
use super::options::{Config, Options, Syntax, Unit};
use crate::number::format_i64;

/// English strings for a single time unit.
struct UnitInfo {
    singular: &'static str,
    plural: &'static str,
    short: &'static str,
}

/// Indexed by the [`Unit`] constants. Direct array lookup, no map.
const UNIT_TABLE: [UnitInfo; 7] = [
    UnitInfo {
        singular: "year",
        plural: "years",
        short: "y",
    },
    UnitInfo {
        singular: "month",
        plural: "months",
        short: "mo",
    },
    UnitInfo {
        singular: "week",
        plural: "weeks",
        short: "w",
    },
    UnitInfo {
        singular: "day",
        plural: "days",
        short: "d",
    },
    UnitInfo {
        singular: "hour",
        plural: "hours",
        short: "h",
    },
    UnitInfo {
        singular: "minute",
        plural: "minutes",
        short: "m",
    },
    UnitInfo {
        singular: "second",
        plural: "seconds",
        short: "s",
    },
];

/// How many of `unit[i+1]` fit in one `unit[i]`:
/// year→month=12, month→week=4, week→day=7, day→hour=24, hour→min=60, min→sec=60.
const CASCADE_FACTORS: [i32; 6] = [12, 4, 7, 24, 60, 60];

/// Formats an interval into a human-readable string.
pub fn format_interval(iv: Interval, cfg: Config) -> String {
    let mut s = String::with_capacity(48);
    append_interval(&mut s, iv, cfg);
    s
}

/// Core formatting engine, mirroring `CarbonInterval::forHumans`.
pub fn append_interval(out: &mut String, iv: Interval, cfg: Config) {
    let syntax = match cfg.syntax {
        Syntax::RelativeAuto => Syntax::RelativeToNow,
        s => s,
    };
    let absolute = syntax == Syntax::Absolute;
    let relative_to_now = syntax == Syntax::RelativeToNow;

    let mut vals = iv.values();

    // Apply skip: cascade skipped unit values into the next smaller unit.
    if cfg.skip != 0 {
        for i in 0..vals.len() - 1 {
            if cfg.skip & (1 << i) != 0 && vals[i] != 0 {
                vals[i + 1] += vals[i] * CASCADE_FACTORS[i];
                vals[i] = 0;
            }
        }
        if cfg.skip & (1 << (vals.len() - 1)) != 0 {
            vals[vals.len() - 1] = 0;
        }
    }

    // Collect non-zero parts into a stack array (at most 7).
    let mut result = [(0i32, 0usize); 7];
    let mut result_len = 0usize;

    for (i, &v) in vals.iter().enumerate() {
        if v > 0 {
            result[result_len] = (v, i);
            result_len += 1;
        } else if cfg.options.contains(Options::SEQUENTIAL_PARTS_ONLY) && result_len > 0 {
            break;
        }
        if result_len >= cfg.parts {
            break;
        }
    }

    // Zero diff.
    if result_len == 0 {
        if relative_to_now && cfg.options.contains(Options::JUST_NOW) {
            out.push_str("just now");
            return;
        }
        let count = i32::from(cfg.options.contains(Options::NO_ZERO_DIFF));
        append_unit(out, count, Unit::Second as usize, cfg.short);
        append_suffix(out, iv.invert, absolute, relative_to_now);
        return;
    }

    // Special day words, only for single-part day results.
    if cfg.parts == 1
        && result_len == 1
        && result[0].1 == Unit::Day as usize
        && !absolute
        && relative_to_now
    {
        if result[0].0 == 1 && cfg.options.contains(Options::ONE_DAY_WORDS) {
            out.push_str(if !iv.invert { "yesterday" } else { "tomorrow" });
            return;
        }
        if result[0].0 == 2 && cfg.options.contains(Options::TWO_DAY_WORDS) {
            out.push_str(if !iv.invert {
                "before yesterday"
            } else {
                "after tomorrow"
            });
            return;
        }
    }

    // Build "{part1}, {part2}, and {partN} ago". Short form joins with a bare
    // space and drops the conjunction — "1h 30m", not "1h and 30m".
    for (i, &(count, unit)) in result.iter().take(result_len).enumerate() {
        if i > 0 {
            if cfg.short {
                out.push(' ');
            } else if i == result_len - 1 && result_len == 2 {
                out.push_str(" and ");
            } else if i == result_len - 1 {
                out.push_str(", and ");
            } else {
                out.push_str(", ");
            }
        }
        append_unit(out, count, unit, cfg.short);
    }

    append_suffix(out, iv.invert, absolute, relative_to_now);
}

/// Appends `"{count}{unit}"` or `"{count} {unit}"`.
#[inline]
pub(crate) fn append_unit(out: &mut String, count: i32, unit_idx: usize, short: bool) {
    format_i64(out, count as i64);
    let info = &UNIT_TABLE[unit_idx];
    if short {
        out.push_str(info.short);
        return;
    }
    out.push(' ');
    out.push_str(if count == 1 {
        info.singular
    } else {
        info.plural
    });
}

/// Appends the temporal modifier (" ago", " from now", ...).
#[inline]
fn append_suffix(out: &mut String, invert: bool, absolute: bool, relative_to_now: bool) {
    if absolute {
        return;
    }
    if relative_to_now {
        out.push_str(if !invert { " ago" } else { " from now" });
        return;
    }
    out.push_str(if !invert { " before" } else { " after" });
}