Repository: typst/typst
File: crates/typst-utils/src/format.rs (Rust)

Code before:
//! Different formatting functions.

use std::time::Duration;

/// Returns value with `n` digits after floating point where `n` is `precision`.
/// Standard rounding rule applies (if `n+1`th digit >= 5 then round up).
/// If `value` is +/- infinity returns `value`.
///
/// Will panic for a very large `value` and `precision` (if the `f64` limit is hit).
/// In practice, it should never panic, otherwise the implementation have to be
/// more robust.
pub fn round_with_precision(value: f64, precision: u8) -> f64 {
    let offset = 10_f64.powi(precision.into());
    if value.is_infinite() {
        return value;
    }
    assert!(
        value * offset < f64::MAX,
        "Hit the upper limit of f64 when rounding! ({value} * 10^{precision})"
    );
    (value * offset).round() / offset
}

/// Returns number of `(days, hours, minutes, seconds, milliseconds, microseconds)`.
fn get_duration_parts(duration: &Duration) -> (u16, u8, u8, u8, u16, u16) {
    // In practice we probably don't need nanoseconds.
    let micros = duration.as_micros();
    let (millis, micros) = (micros / 1000, (micros % 1000) as u16);
    let (sec, millis) = (millis / 1000, (millis % 1000) as u16);
    let (mins, sec) = (sec / 60, (sec % 60) as u8);
    let (hours, mins) = (mins / 60, (mins % 60) as u8);
    let (days, hours) = ((hours / 24) as u16, (hours % 24) as u8);
    (days, hours, mins, sec, millis, micros)
}

/// Format string using `days`, `hours`, `minutes`, `seconds`.
fn format_dhms(days: u16, hours: u8, minutes: u8, seconds: u8) -> String {
    match (days, hours, minutes, seconds) {
        (0, 0, 0, s) => format!("{s:2} s"),
        (0, 0, m, s) => format!("{m:2} m {s:2} s"),
        (0, h, m, s) => format!("{h:2} h {m:2} m {s:2} s"),
        (d, h, m, s) => format!("{d:3} d {h:2} h {m:2} m {s:2} s"),
    }

Review comment (suggestion):
In principle I was going to suggest moving this function to `lib.rs`, but, on second thought, after writing my reply to the thread regarding the `assert!` call (https://github.com/typst/typst/pull/4587#discussion_r1719218753), I think this function should _only_ be used for formatting purposes, to the point that this should be reflected in the docstring and maybe even in the function's name somehow (possibly unnecessary).

Code after:
//! Different formatting functions.

use std::time::Duration;

/// Returns value with `n` digits after floating point where `n` is `precision`.
/// Standard rounding rules apply (if `n+1`th digit >= 5, round up).
///
/// If rounding the `value` will have no effect (e.g., it's infinite or NaN),
/// returns `value` unchanged.
///
/// # Examples
///
/// ```
/// # use typst_utils::format::round_with_precision;
/// let rounded = round_with_precision(-0.56553, 2);
/// assert_eq!(-0.57, rounded);
/// ```
pub fn round_with_precision(value: f64, precision: u8) -> f64 {
    // Don't attempt to round the float if that wouldn't have any effect.
    // This includes infinite or NaN values, as well as integer values
    // with a filled mantissa (which can't have a fractional part).
    // Rounding with a precision larger than the amount of digits that can be
    // effectively represented would also be a no-op. Given that, the check
    // below ensures we won't proceed if `|value| >= 2^53` or if
    // `precision >= 15`, which also ensures the multiplication by `offset`
    // won't return `inf`, since `2^53 * 10^15` (larger than any possible
    // `value * offset` multiplication) does not.
    if value.is_infinite()
        || value.is_nan()
        || value.abs() >= (1_i64 << f64::MANTISSA_DIGITS) as f64
        || precision as u32 >= f64::DIGITS
    {
        return value;
    }
    let offset = 10_f64.powi(precision.into());
    assert!((value * offset).is_finite(), "{value} * {offset} is not finite!");
    (value * offset).round() / offset
}

/// Returns `(days, hours, minutes, seconds, milliseconds, microseconds)`.
fn get_duration_parts(duration: &Duration) -> (u64, u8, u8, u8, u16, u16) {
    // In practice we probably don't need nanoseconds.
    let micros = duration.as_micros();