Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.0

0.7.0 / src / clock / duration.lucb

#==============================================================================================
#
#   duration - A span of time
#
#   DESCRIPTION:
#       Whole nanoseconds, positive or negative, made from seconds or milliseconds and read
#       back the same ways, with the arithmetic durations need.
#
#==============================================================================================

## A span of time in whole nanoseconds, positive or negative: about 292 years either way.
## Arithmetic past that traps, as integer arithmetic does. `Duration(nanoseconds = n)`
## makes one from nanoseconds.
pub struct Duration:
    ## The span in nanoseconds.
    pub let nanoseconds: i64

    ## `seconds` seconds, rounded to the nearest nanosecond.
    pub static func of_seconds(seconds: f64) -> Duration!:
        let nanoseconds = seconds * 1000000000.0
        if not (nanoseconds >= -9.2e18 and nanoseconds <= 9.2e18):
            error(invalid, "a duration must be a finite number of seconds within 292 years")
        return Duration(nanoseconds = (i64)(nanoseconds + (0.5 if nanoseconds >= 0.0 else -0.5)))

    ## `milliseconds` milliseconds.
    pub static func of_milliseconds(milliseconds: i64) -> Duration:
        return Duration(nanoseconds = milliseconds * 1000000)

    ## The span in seconds, with its fraction.
    pub func seconds() -> f64:
        return (f64)self.nanoseconds / 1000000000.0

    ## The span in whole milliseconds, rounded toward zero.
    pub func milliseconds() -> i64:
        return self.nanoseconds // 1000000

    ## This span and `other` together.
    pub func plus(other: Duration) -> Duration:
        return Duration(nanoseconds = self.nanoseconds + other.nanoseconds)

    ## This span less `other`.
    pub func minus(other: Duration) -> Duration:
        return Duration(nanoseconds = self.nanoseconds - other.nanoseconds)

    ## This span scaled by `factor`, rounded to the nearest nanosecond.
    pub func times(factor: f64) -> Duration!:
        return try Duration.of_seconds(self.seconds() * factor)

    ## Whether the span is shorter than `other`.
    pub func is_shorter(other: Duration) -> bool:
        return self.nanoseconds < other.nanoseconds

    ## Whether the span runs backwards.
    pub func is_negative() -> bool:
        return self.nanoseconds < 0