use crate::error::InvalidValue;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rounding {
Floor,
Nearest,
Ceil,
TowardZero,
}
impl Rounding {
pub fn name(&self) -> &'static str {
match self {
Rounding::Floor => "floor",
Rounding::Ceil => "ceil",
Rounding::Nearest => "nearest",
Rounding::TowardZero => "toward zero",
}
}
}
crate::impl_spec_display!(Rounding);
#[macro_export]
macro_rules! timescale {
($value:expr) => {
const {
match ::core::num::NonZeroU32::new($value) {
::core::option::Option::Some(nz) => $crate::timescale::Timescale::from_nonzero(nz),
::core::option::Option::None => panic!("a timescale is never zero"),
}
}
};
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Timescale(core::num::NonZeroU32);
impl Timescale {
pub const MICROS: Self = crate::timescale!(crate::units::MICROS_PER_SEC as u32);
pub const NANOS: Self = crate::timescale!(1_000_000_000);
#[must_use]
pub const fn from_nonzero(value: core::num::NonZeroU32) -> Self {
Self(value)
}
#[must_use]
pub const fn new(value: u32) -> Option<Self> {
match core::num::NonZeroU32::new(value) {
Some(nz) => Some(Self(nz)),
None => None,
}
}
pub fn try_new(value: u32) -> Result<Self, InvalidValue> {
core::num::NonZeroU32::new(value)
.map(Self)
.ok_or(InvalidValue {
field: "timescale",
value: u64::from(value),
reason: "must be non-zero",
})
}
#[must_use]
pub const fn get(self) -> u32 {
self.0.get()
}
}
impl core::fmt::Debug for Timescale {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Debug::fmt(&self.0.get(), f)
}
}
impl core::fmt::Display for Timescale {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(&self.0, f)
}
}
impl From<core::num::NonZeroU32> for Timescale {
fn from(v: core::num::NonZeroU32) -> Self {
Self(v)
}
}
impl From<Timescale> for u32 {
fn from(t: Timescale) -> Self {
t.0.get()
}
}
impl From<Timescale> for u64 {
fn from(t: Timescale) -> Self {
t.0.get() as u64
}
}
impl From<Timescale> for core::num::NonZeroU32 {
fn from(t: Timescale) -> Self {
t.0
}
}
impl TryFrom<u32> for Timescale {
type Error = InvalidValue;
fn try_from(v: u32) -> Result<Self, Self::Error> {
Self::try_new(v)
}
}
impl TryFrom<u64> for Timescale {
type Error = InvalidValue;
fn try_from(v: u64) -> Result<Self, Self::Error> {
let narrow = u32::try_from(v).map_err(|_| InvalidValue {
field: "timescale",
value: v,
reason: "timescale does not fit 32 bits",
})?;
Self::try_new(narrow)
}
}
#[must_use]
pub fn rescale(ticks: i128, from: Timescale, to: Timescale, rounding: Rounding) -> i128 {
let den = i128::from(from.get());
let num = ticks.saturating_mul(i128::from(to.get()));
match rounding {
Rounding::Floor => num.div_euclid(den),
Rounding::Ceil => {
let floor = num.div_euclid(den);
if num.rem_euclid(den) == 0 {
floor
} else {
floor.saturating_add(1)
}
}
Rounding::TowardZero => num / den,
Rounding::Nearest => {
let half = den >> 1;
if num >= 0 {
num.saturating_add(half) / den
} else {
num.saturating_sub(half) / den
}
}
}
}
#[must_use]
pub fn cmp_ticks(a: i64, a_ts: Timescale, b: i64, b_ts: Timescale) -> core::cmp::Ordering {
let a_ts = i128::from(a_ts.get());
let b_ts = i128::from(b_ts.get());
(i128::from(a) * b_ts).cmp(&(i128::from(b) * a_ts))
}
#[must_use]
pub fn to_duration(ticks: u64, timescale: Timescale, rounding: Rounding) -> core::time::Duration {
core::time::Duration::from_nanos(rescale_u64(ticks, timescale, Timescale::NANOS, rounding))
}
#[must_use]
pub fn from_duration(
duration: core::time::Duration,
timescale: Timescale,
rounding: Rounding,
) -> u64 {
let nanos = i128::try_from(duration.as_nanos()).unwrap_or(i128::MAX);
u64::try_from(rescale(nanos, Timescale::NANOS, timescale, rounding)).unwrap_or(u64::MAX)
}
#[must_use]
pub fn rescale_i64(ticks: i64, from: Timescale, to: Timescale, rounding: Rounding) -> i64 {
let scaled = rescale(i128::from(ticks), from, to, rounding);
i64::try_from(scaled).unwrap_or(if scaled < 0 { i64::MIN } else { i64::MAX })
}
#[must_use]
pub fn rescale_u64(ticks: u64, from: Timescale, to: Timescale, rounding: Rounding) -> u64 {
let scaled = rescale(i128::from(ticks), from, to, rounding);
u64::try_from(scaled).unwrap_or(if scaled < 0 { 0 } else { u64::MAX })
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
const T1: Timescale = crate::timescale!(1);
const T48K: Timescale = crate::timescale!(48_000);
const T90K: Timescale = crate::timescale!(90_000);
fn ts(value: u32) -> Timescale {
Timescale::try_new(value).expect("a non-zero timescale")
}
#[test]
fn rounding_modes_differ_on_a_half_and_a_negative() {
let two = ts(2);
assert_eq!(rescale(3, two, T1, Rounding::Floor), 1);
assert_eq!(rescale(3, two, T1, Rounding::Nearest), 2);
assert_eq!(rescale(3, two, T1, Rounding::TowardZero), 1);
assert_eq!(rescale(-3, two, T1, Rounding::Floor), -2);
assert_eq!(rescale(-3, two, T1, Rounding::Nearest), -2);
assert_eq!(rescale(-3, two, T1, Rounding::TowardZero), -1);
}
#[test]
fn rescale_to_and_from_micros() {
let three = ts(3);
assert_eq!(
rescale(90_000, T90K, Timescale::MICROS, Rounding::Floor),
1_000_000
);
assert_eq!(
rescale(1, three, Timescale::MICROS, Rounding::TowardZero),
333_333
);
assert_eq!(
rescale(-1, three, Timescale::MICROS, Rounding::Floor),
-333_334
);
assert_eq!(
rescale(1_000_001, Timescale::MICROS, T90K, Rounding::Ceil),
90_001
);
assert_eq!(
rescale(1_000_001, Timescale::MICROS, T90K, Rounding::Floor),
90_000
);
assert_eq!(
rescale(5, T1, Timescale::MICROS, Rounding::Floor),
5_000_000
);
}
#[test]
fn identity_and_known_conversion() {
assert_eq!(rescale(90_000, T90K, T90K, Rounding::Nearest), 90_000);
assert_eq!(rescale(48_000, T48K, T90K, Rounding::Floor), 90_000);
assert_eq!(rescale_u64(1024, T48K, T90K, Rounding::Nearest), 1920);
}
#[test]
fn a_zero_timescale_is_an_error_from_every_runtime_constructor() {
assert_eq!(
Timescale::try_new(0).map(Timescale::get),
Err(InvalidValue {
field: "timescale",
value: 0,
reason: "must be non-zero",
})
);
assert_eq!(
Timescale::try_from(0u32).map(Timescale::get),
Err(InvalidValue {
field: "timescale",
value: 0,
reason: "must be non-zero",
})
);
}
#[test]
fn the_literal_macro_names_the_timescale_it_is_given() {
const T: Timescale = crate::timescale!(90_000);
assert_eq!(T.get(), 90_000);
assert_eq!(crate::timescale!(1).get(), 1);
assert_eq!(Timescale::from_nonzero(core::num::NonZeroU32::MIN).get(), 1);
}
#[test]
fn zero_timescale_is_rejected_not_flattened_to_one() {
assert!(Timescale::try_new(0).is_err());
let err = Timescale::try_new(0).expect_err("a zero timescale is an error");
assert_eq!(err.field, "timescale");
assert_eq!(err.value, 0);
assert_eq!(err.reason, "must be non-zero");
assert_eq!(Timescale::try_new(1).map(Timescale::get), Ok(1));
assert_eq!(Timescale::try_new(90_000).map(Timescale::get), Ok(90_000));
assert_eq!(
rescale(7, T1, Timescale::MICROS, Rounding::Floor),
7_000_000
);
}
#[test]
fn timescale_try_from_u32_rejects_zero() {
let err = Timescale::try_from(0u32).expect_err("a zero timescale is an error");
assert_eq!(err.field, "timescale");
assert_eq!(err.value, 0);
assert_eq!(err.reason, "must be non-zero");
let ok: Timescale = 90_000u32.try_into().expect("non-zero converts");
assert_eq!(ok, T90K);
assert_eq!(u32::from(ok), 90_000);
}
#[test]
fn saturates_instead_of_wrapping() {
let max = ts(u32::MAX);
assert_eq!(rescale_i64(i64::MAX, T1, max, Rounding::Floor), i64::MAX);
assert_eq!(rescale_i64(i64::MIN, T1, max, Rounding::Floor), i64::MIN);
assert_eq!(rescale_u64(u64::MAX, T1, max, Rounding::Nearest), u64::MAX);
assert_eq!(rescale_u64(0, T1, T1, Rounding::Nearest), 0);
assert_eq!(rescale(i128::MAX, T1, ts(2), Rounding::Floor), i128::MAX);
}
#[test]
fn ceil_rounds_toward_positive_infinity() {
let two = ts(2);
assert_eq!(rescale(3, two, T1, Rounding::Ceil), 2);
assert_eq!(rescale(4, two, T1, Rounding::Ceil), 2);
assert_eq!(rescale(-3, two, T1, Rounding::Ceil), -1);
assert_eq!(rescale(-4, two, T1, Rounding::Ceil), -2);
assert_eq!(rescale(5, T1, T1, Rounding::Ceil), 5);
assert_eq!(
rescale_i64(i64::MAX, T1, ts(u32::MAX), Rounding::Ceil),
i64::MAX
);
}
#[test]
fn cmp_ticks_is_exact_across_timescales() {
use core::cmp::Ordering::{Equal, Greater, Less};
assert_eq!(cmp_ticks(90_000, T90K, 48_000, T48K), Equal);
assert_eq!(cmp_ticks(1, ts(3), 1, ts(2)), Less);
assert_eq!(cmp_ticks(i64::MAX, T1, i64::MAX, ts(2)), Greater);
assert_eq!(cmp_ticks(5, T1, 5, T1), Equal);
}
#[test]
fn labels() {
assert_eq!(Rounding::Ceil.to_string(), "ceil");
assert_eq!(Rounding::Nearest.name(), "nearest");
assert_eq!(Rounding::TowardZero.to_string(), "toward zero");
}
#[test]
fn a_u64_timescale_narrows_with_a_typed_error() {
assert_eq!(Timescale::try_from(90_000u64), Ok(T90K));
assert!(Timescale::try_from(0u64).is_err());
assert!(Timescale::try_from(u64::from(u32::MAX) + 1).is_err());
}
#[test]
fn durations_and_ticks_convert_both_ways() {
let one_and_a_half = core::time::Duration::from_millis(1_500);
assert_eq!(
from_duration(one_and_a_half, T90K, Rounding::Nearest),
135_000
);
assert_eq!(
to_duration(135_000, T90K, Rounding::Nearest),
one_and_a_half
);
assert_eq!(
from_duration(core::time::Duration::MAX, T90K, Rounding::Floor),
u64::MAX
);
}
}