wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Human-readable time difference formatting.
//!
//! [`diff_for_humans`] is a port of Carbon's `CarbonInterface::diffForHumans()`.
//! Original source: <https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Traits/Difference.php>
//! Carbon is created by Brian Nesbitt and licensed under the MIT License.

mod format;
mod interval;
mod options;

use jiff::Zoned;

pub use format::{append_interval, format_interval};
pub use interval::{diff, Interval};
pub use options::{Config, Options, Syntax, Unit};

/// Returns a human-readable string describing the difference between `from`
/// and `to`.
///
/// With [`Syntax::RelativeAuto`], the output is framed relative to now
/// ("ago"/"from now"); pass [`Syntax::RelativeToOther`] to frame it against
/// `to` instead ("before"/"after").
pub fn diff_for_humans(from: &Zoned, to: &Zoned, cfg: Config) -> String {
    let mut s = String::with_capacity(48);
    append_diff_for_humans(&mut s, from, to, cfg);
    s
}

/// Allocation-free counterpart of [`diff_for_humans`].
#[inline]
pub fn append_diff_for_humans(out: &mut String, from: &Zoned, to: &Zoned, cfg: Config) {
    append_interval(out, diff(from, to), cfg)
}

/// Pre-computed configuration for repeated formatting against a fixed
/// reference instant. Captures the reference time once at construction.
#[derive(Clone, Debug)]
pub struct Formatter {
    now: Zoned,
    cfg: Config,
}

impl Formatter {
    /// Creates a formatter anchored at `now`.
    ///
    /// [`Syntax::RelativeAuto`] resolves to [`Syntax::RelativeToNow`]; pass an
    /// explicit syntax to override.
    pub fn new(now: Zoned, mut cfg: Config) -> Self {
        if cfg.syntax == Syntax::RelativeAuto {
            cfg.syntax = Syntax::RelativeToNow;
        }
        Self { now, cfg }
    }

    /// The reference instant this formatter compares against.
    pub fn reference(&self) -> &Zoned {
        &self.now
    }

    /// Formats the difference between `from` and the reference instant.
    pub fn format(&self, from: &Zoned) -> String {
        format_interval(diff(from, &self.now), self.cfg)
    }

    /// Allocation-free counterpart of [`Formatter::format`].
    #[inline]
    pub fn append_format(&self, out: &mut String, from: &Zoned) {
        append_interval(out, diff(from, &self.now), self.cfg)
    }
}