humfmt 0.2.0

Ergonomic human-readable formatting toolkit for Rust
Documentation
use crate::locale::{English, Locale};

/// Builder-style configuration for duration and relative-time formatting.
///
/// # Examples
///
/// ```rust
/// use humfmt::DurationOptions;
///
/// let opts = DurationOptions::new().max_units(3).long_units();
/// ```
#[derive(Copy, Clone, Debug)]
pub struct DurationOptions<L: Locale = English> {
    max_units: u8,
    long_units: bool,
    locale: L,
}

impl DurationOptions<English> {
    /// Creates default duration formatting options.
    pub fn new() -> Self {
        Self {
            max_units: 2,
            long_units: false,
            locale: English,
        }
    }
}

impl<L: Locale> Default for DurationOptions<L> {
    fn default() -> Self {
        Self {
            max_units: 2,
            long_units: false,
            locale: L::default(),
        }
    }
}

impl<L: Locale> DurationOptions<L> {
    /// Limits how many non-zero units are rendered.
    pub fn max_units(mut self, n: u8) -> Self {
        self.max_units = n.clamp(1, 4);
        self
    }

    /// Uses long localized unit labels like `hour` instead of `h`.
    pub fn long_units(mut self) -> Self {
        self.long_units = true;
        self
    }

    /// Switches the active locale.
    pub fn locale<N: Locale>(self, locale: N) -> DurationOptions<N> {
        DurationOptions {
            max_units: self.max_units,
            long_units: self.long_units,
            locale,
        }
    }

    pub(crate) fn max_units_value(&self) -> u8 {
        self.max_units
    }

    pub(crate) fn long_units_value(&self) -> bool {
        self.long_units
    }

    pub(crate) fn locale_ref(&self) -> &L {
        &self.locale
    }
}