Skip to main content

moq_net/model/
time.rs

1use std::num::NonZero;
2
3use crate::coding::varint::MAX_QUIC;
4
5/// The largest [`Timestamp`] value, `2^61 - 1`.
6///
7/// lite-05/06 zigzag a group's first timestamp from zero into a QUIC varint, which halves
8/// its positive range. Bounding every timestamp here keeps each one encodable on every
9/// version, including after a relay forwards it from lite-07 or moq-transport.
10const MAX_TIMESTAMP: u64 = (1 << 61) - 1;
11
12/// `value`, or `None` past `max`.
13const fn bounded(value: u128, max: u64) -> Option<u64> {
14	if value <= max as u128 { Some(value as u64) } else { None }
15}
16
17/// Returned when a [`Timestamp`] operation would exceed its range (`2^61 - 1`), a
18/// [`Timescale`] would exceed the QUIC varint range (`2^62 - 1`), scale conversion or
19/// arithmetic would overflow, arithmetic mixes timestamps with mismatched scales, or a
20/// conversion needs the scale an unscaled [`Timestamp`] lacks.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
22#[error("time overflow")]
23pub struct TimeOverflow;
24
25/// Units per second used by a track for frame timestamps.
26///
27/// Newtype around [`NonZero<u64>`]. Zero is structurally impossible, so the
28/// arithmetic on [`Timestamp`] can divide by `self.scale` without ever risking
29/// a divide by zero. Use the named constants ([`Self::SECOND`], [`Self::MILLI`],
30/// [`Self::MICRO`], [`Self::NANO`]) instead of writing raw integers at call sites;
31/// for runtime values, use [`Self::new`] or [`TryFrom`], which return [`TimeOverflow`]
32/// for `0` or for values past the QUIC varint range.
33#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct Timescale(NonZero<u64>);
35
36impl Timescale {
37	/// One unit per second (`1`).
38	pub const SECOND: Self = match Self::new(1) {
39		Ok(scale) => scale,
40		Err(_) => unreachable!(),
41	};
42	/// 1,000 units per second (`1_000`).
43	pub const MILLI: Self = match Self::new(1_000) {
44		Ok(scale) => scale,
45		Err(_) => unreachable!(),
46	};
47	/// 1,000,000 units per second (`1_000_000`). Widely used by container formats.
48	pub const MICRO: Self = match Self::new(1_000_000) {
49		Ok(scale) => scale,
50		Err(_) => unreachable!(),
51	};
52	/// 1,000,000,000 units per second (`1_000_000_000`).
53	pub const NANO: Self = match Self::new(1_000_000_000) {
54		Ok(scale) => scale,
55		Err(_) => unreachable!(),
56	};
57
58	/// Construct a timescale from a raw value (units per second).
59	///
60	/// Returns [`TimeOverflow`] if `units_per_second` is `0` (would divide by zero)
61	/// or exceeds `2^62 - 1` (the QUIC varint range, matching [`Timestamp`] values).
62	/// Every runtime constructor, including [`TryFrom`], goes through this check.
63	pub const fn new(units_per_second: u64) -> Result<Self, TimeOverflow> {
64		// Reject values that wouldn't fit in a QUIC varint, keeping the constraint
65		// symmetric with Timestamp's raw value.
66		if bounded(units_per_second as u128, MAX_QUIC).is_none() {
67			return Err(TimeOverflow);
68		}
69		match NonZero::new(units_per_second) {
70			Some(n) => Ok(Self(n)),
71			None => Err(TimeOverflow),
72		}
73	}
74
75	/// The raw units-per-second value (always non-zero).
76	pub const fn as_u64(self) -> u64 {
77		self.0.get()
78	}
79}
80
81impl TryFrom<u64> for Timescale {
82	type Error = TimeOverflow;
83
84	fn try_from(units_per_second: u64) -> Result<Self, Self::Error> {
85		Self::new(units_per_second)
86	}
87}
88
89impl TryFrom<NonZero<u64>> for Timescale {
90	type Error = TimeOverflow;
91
92	/// Same bound as [`Self::new`]: non-zero is not enough, the value must also fit
93	/// in a QUIC varint.
94	fn try_from(units_per_second: NonZero<u64>) -> Result<Self, Self::Error> {
95		Self::new(units_per_second.get())
96	}
97}
98
99impl From<Timescale> for u64 {
100	fn from(scale: Timescale) -> Self {
101		scale.0.get()
102	}
103}
104
105impl From<Timescale> for NonZero<u64> {
106	fn from(scale: Timescale) -> Self {
107		scale.0
108	}
109}
110
111impl std::fmt::Debug for Timescale {
112	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113		match *self {
114			Self::SECOND => write!(f, "Timescale::SECOND"),
115			Self::MILLI => write!(f, "Timescale::MILLI"),
116			Self::MICRO => write!(f, "Timescale::MICRO"),
117			Self::NANO => write!(f, "Timescale::NANO"),
118			Self(n) => write!(f, "Timescale({n})"),
119		}
120	}
121}
122
123impl std::fmt::Display for Timescale {
124	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125		write!(f, "{}", self.0)
126	}
127}
128
129/// A timestamp in a track's timescale (units per second), or a scale-less track's group key.
130///
131/// All timestamps within a track are relative, so zero for one track is not zero for another.
132/// A scaled value is at most `2^61 - 1`, the most every moq-lite version can encode as a
133/// group's first frame, while an unscaled key spans every group key; the scale is carried alongside so frames from different
134/// sources can be compared and converted without lossy detours through a single fixed scale.
135///
136/// A scale-less track has no time: each frame's timestamp is [`Self::unscaled`], whose value
137/// is its group's key. Anything that needs a scale ([`Self::convert`], `as_secs`, `as_millis`,
138/// and so on) is [`TimeOverflow`] on one, and it orders against no scaled timestamp.
139///
140/// # An instant, not a number
141///
142/// A `Timestamp` is a point in time (like [`std::time::Instant`]), not a scalar, so it has no
143/// arithmetic operators: adding two instants is meaningless, and a scale mismatch can't be a
144/// silent panic. Use [`Self::checked_add`] / [`Self::checked_sub`], which **require both
145/// operands to share a scale** and return [`TimeOverflow`] otherwise. To combine timestamps
146/// from different scales, [`Self::convert`] one to the other's scale first.
147///
148/// # Equality vs ordering
149///
150/// These two intentionally disagree, so pick the one you mean:
151///
152/// - [`Eq`] / [`Hash`] are **structural** (field-wise): `from_secs(1) != from_millis(1000)`,
153///   because they encode as different `(value, scale)` pairs on the wire. Two timestamps are
154///   equal only when both their value and scale match.
155/// - [`PartialOrd`] is **temporal**: it cross-multiplies scales, so `from_millis(1000)` orders
156///   after `from_millis(999)` and `from_secs(1)` slots in between. When a cross-scale comparison
157///   is otherwise a tie, it breaks by `(scale, value)` to stay consistent with `Eq`. A scaled
158///   and an unscaled timestamp don't compare: `partial_cmp` is `None`, so `<` and `>` are both
159///   false. There is no [`Ord`].
160///
161/// So `from_secs(1).partial_cmp(&from_millis(1000))` is *not* `Equal`, and neither is `==` true.
162/// If you want "same instant regardless of encoding", compare after a [`Self::convert`] to a
163/// common scale.
164#[derive(Clone, Copy, PartialEq, Eq, Hash)]
165pub struct Timestamp {
166	value: u64,
167	scale: Option<Timescale>,
168}
169
170impl Timestamp {
171	/// The zero timestamp: value `0` at [`Timescale::SECOND`].
172	///
173	/// The scale is not incidental. Equality and ordering are scale-aware (see the type
174	/// docs), so this is *not* interchangeable with `0` at another scale; use
175	/// [`Self::is_zero`] to test a zero value regardless of scale. In particular, don't
176	/// seed a `.max()` accumulator with this: a later value at a finer scale would lose
177	/// the tie-break. Reach for `Option<Timestamp>` instead.
178	pub const ZERO: Self = Self::new_const(0, Timescale::SECOND);
179
180	/// Construct a timestamp directly from a raw value at the given scale.
181	/// Returns [`TimeOverflow`] if `value` exceeds `2^61 - 1`.
182	pub const fn new(value: u64, scale: Timescale) -> Result<Self, TimeOverflow> {
183		Self::bounded(value, Some(scale))
184	}
185
186	/// A scale-less track's timestamp: `key` is its group's key, with no time.
187	pub const fn unscaled(key: u64) -> Self {
188		Self {
189			value: key,
190			scale: None,
191		}
192	}
193
194	/// `value` at `scale`, bounded to `2^61 - 1` when it carries a time.
195	const fn bounded(value: u64, scale: Option<Timescale>) -> Result<Self, TimeOverflow> {
196		match (scale, bounded(value as u128, MAX_TIMESTAMP)) {
197			(None, _) => Ok(Self { value, scale }),
198			(Some(_), Some(value)) => Ok(Self { value, scale }),
199			(Some(_), None) => Err(TimeOverflow),
200		}
201	}
202
203	/// Const-context twin of [`Self::new`] that panics on overflow.
204	const fn new_const(value: u64, scale: Timescale) -> Self {
205		match Self::new(value, scale) {
206			Ok(time) => time,
207			Err(_) => panic!("timestamp value exceeds 2^61 - 1"),
208		}
209	}
210
211	/// Construct a timestamp from a raw value and a `units_per_second` scale.
212	/// Returns [`TimeOverflow`] if the scale is zero or the value is out of range.
213	pub fn from_scale(value: u64, units_per_second: u64) -> Result<Self, TimeOverflow> {
214		Self::new(value, Timescale::new(units_per_second)?)
215	}
216
217	/// Convert a number of seconds to a timestamp at [`Timescale::SECOND`].
218	pub const fn from_secs(seconds: u64) -> Result<Self, TimeOverflow> {
219		Self::new(seconds, Timescale::SECOND)
220	}
221
222	/// Convert a number of milliseconds to a timestamp at [`Timescale::MILLI`].
223	pub const fn from_millis(millis: u64) -> Result<Self, TimeOverflow> {
224		Self::new(millis, Timescale::MILLI)
225	}
226
227	/// Convert a number of microseconds to a timestamp at [`Timescale::MICRO`].
228	pub const fn from_micros(micros: u64) -> Result<Self, TimeOverflow> {
229		Self::new(micros, Timescale::MICRO)
230	}
231
232	/// Convert a number of nanoseconds to a timestamp at [`Timescale::NANO`].
233	pub const fn from_nanos(nanos: u64) -> Result<Self, TimeOverflow> {
234		Self::new(nanos, Timescale::NANO)
235	}
236
237	/// The raw value in the timestamp's own scale, or the group key when unscaled.
238	pub const fn value(self) -> u64 {
239		self.value
240	}
241
242	/// The scale (units per second) attached to this timestamp, or `None` when unscaled.
243	pub const fn scale(self) -> Option<Timescale> {
244		self.scale
245	}
246
247	/// Whether the raw value is zero. Does not consider scale.
248	pub const fn is_zero(self) -> bool {
249		self.value == 0
250	}
251
252	/// The scale, or [`TimeOverflow`] when unscaled: a group key has no time to convert.
253	const fn scaled(self) -> Result<NonZero<u64>, TimeOverflow> {
254		match self.scale {
255			Some(scale) => Ok(scale.0),
256			None => Err(TimeOverflow),
257		}
258	}
259
260	/// Re-express this timestamp at a new scale. Returns [`TimeOverflow`] if it is unscaled,
261	/// or if the new value would exceed `2^61 - 1`.
262	pub const fn convert(self, new_scale: Timescale) -> Result<Self, TimeOverflow> {
263		let scale = match self.scaled() {
264			Ok(scale) => scale.get(),
265			Err(err) => return Err(err),
266		};
267		if scale == new_scale.0.get() {
268			return Ok(self);
269		}
270		match (self.value as u128).checked_mul(new_scale.0.get() as u128) {
271			Some(scaled) => match bounded(scaled / scale as u128, MAX_TIMESTAMP) {
272				Some(value) => Ok(Self {
273					value,
274					scale: Some(new_scale),
275				}),
276				None => Err(TimeOverflow),
277			},
278			None => Err(TimeOverflow),
279		}
280	}
281
282	/// The value re-expressed at `target` as a `u128`, or [`TimeOverflow`] when unscaled.
283	pub const fn as_scale(self, target: Timescale) -> Result<u128, TimeOverflow> {
284		match self.scaled() {
285			Ok(scale) => Ok(self.value as u128 * target.0.get() as u128 / scale.get() as u128),
286			Err(err) => Err(err),
287		}
288	}
289
290	/// The value re-expressed in seconds, or [`TimeOverflow`] when unscaled.
291	pub const fn as_secs(self) -> Result<u64, TimeOverflow> {
292		match self.scaled() {
293			Ok(scale) => Ok(self.value / scale.get()),
294			Err(err) => Err(err),
295		}
296	}
297
298	/// The value re-expressed in milliseconds, or [`TimeOverflow`] when unscaled.
299	pub const fn as_millis(self) -> Result<u128, TimeOverflow> {
300		self.as_scale(Timescale::MILLI)
301	}
302
303	/// The value re-expressed in microseconds, or [`TimeOverflow`] when unscaled.
304	pub const fn as_micros(self) -> Result<u128, TimeOverflow> {
305		self.as_scale(Timescale::MICRO)
306	}
307
308	/// The value re-expressed in nanoseconds, or [`TimeOverflow`] when unscaled.
309	pub const fn as_nanos(self) -> Result<u128, TimeOverflow> {
310		self.as_scale(Timescale::NANO)
311	}
312
313	/// Whether both carry the same scale, or both none.
314	const fn same_scale(self, rhs: Self) -> bool {
315		match (self.scale, rhs.scale) {
316			(Some(a), Some(b)) => a.0.get() == b.0.get(),
317			(None, None) => true,
318			_ => false,
319		}
320	}
321
322	/// Add two timestamps. Returns [`TimeOverflow`] if the sum exceeds `2^61 - 1` or
323	/// if the scales differ.
324	pub const fn checked_add(self, rhs: Self) -> Result<Self, TimeOverflow> {
325		if !self.same_scale(rhs) {
326			return Err(TimeOverflow);
327		}
328		match self.value.checked_add(rhs.value) {
329			Some(result) => Self::bounded(result, self.scale),
330			None => Err(TimeOverflow),
331		}
332	}
333
334	/// Subtract `rhs` from `self`. Returns [`TimeOverflow`] if `rhs > self` or if the
335	/// scales differ.
336	pub const fn checked_sub(self, rhs: Self) -> Result<Self, TimeOverflow> {
337		if !self.same_scale(rhs) {
338			return Err(TimeOverflow);
339		}
340		match self.value.checked_sub(rhs.value) {
341			Some(result) => Self::bounded(result, self.scale),
342			None => Err(TimeOverflow),
343		}
344	}
345}
346
347impl Timestamp {
348	/// This timestamp when it carries a time, or `None` for a scale-less track's key.
349	pub(crate) const fn timed(self) -> Option<Self> {
350		match self.scale {
351			Some(_) => Some(self),
352			None => None,
353		}
354	}
355
356	/// A received frame's time: the `timestamp` its wire carried, or on a scale-less track,
357	/// which carries none, its group's `key`.
358	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
359	pub(crate) fn received(timestamp: Option<Self>, key: u64) -> Self {
360		match timestamp {
361			Some(timestamp) => timestamp,
362			None => Self::unscaled(key),
363		}
364	}
365
366	/// The later of two timestamps of one track, which share a scale; `self` when they
367	/// don't compare.
368	pub(crate) fn later(self, other: Self) -> Self {
369		if other > self { other } else { self }
370	}
371
372	/// The earlier of two timestamps of one track, which share a scale; `self` when they
373	/// don't compare.
374	pub(crate) fn earlier(self, other: Self) -> Self {
375		if other < self { other } else { self }
376	}
377}
378
379impl TryFrom<std::time::Duration> for Timestamp {
380	type Error = TimeOverflow;
381
382	/// Convert a [`std::time::Duration`] into a nanosecond-scale timestamp.
383	fn try_from(duration: std::time::Duration) -> Result<Self, Self::Error> {
384		match bounded(duration.as_nanos(), MAX_TIMESTAMP) {
385			Some(value) => Ok(Self {
386				value,
387				scale: Some(Timescale::NANO),
388			}),
389			None => Err(TimeOverflow),
390		}
391	}
392}
393
394impl TryFrom<Timestamp> for std::time::Duration {
395	type Error = TimeOverflow;
396
397	/// The time since the track's zero, or [`TimeOverflow`] when unscaled.
398	fn try_from(time: Timestamp) -> Result<Self, Self::Error> {
399		let nanos = time.as_nanos()?;
400		Ok(std::time::Duration::new(
401			time.as_secs()?,
402			(nanos % 1_000_000_000) as u32,
403		))
404	}
405}
406
407impl std::fmt::Debug for Timestamp {
408	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409		let Ok(nanos) = self.as_nanos() else {
410			return write!(f, "#{}", self.value);
411		};
412
413		// Choose the largest unit where we don't need decimal places.
414		if nanos.is_multiple_of(1_000_000_000) {
415			write!(f, "{}s", nanos / 1_000_000_000)
416		} else if nanos.is_multiple_of(1_000_000) {
417			write!(f, "{}ms", nanos / 1_000_000)
418		} else if nanos.is_multiple_of(1_000) {
419			write!(f, "{}µs", nanos / 1_000)
420		} else {
421			write!(f, "{}ns", nanos)
422		}
423	}
424}
425
426impl PartialOrd for Timestamp {
427	/// Temporal comparison, normalizing across scales (see the type-level docs for how
428	/// this relates to structural `Eq`).
429	///
430	/// - Equal scales, or two unscaled keys, compare raw values directly.
431	/// - Otherwise cross-multiplies in 128-bit so e.g. `1s > 2ms` orders correctly.
432	/// - A would-be cross-scale tie (e.g. `from_secs(1)` vs `from_millis(1000)`) breaks by
433	///   `(scale, value)`, keeping the order consistent with the field-wise `Eq`/`Hash`.
434	/// - A scaled and an unscaled timestamp are `None`.
435	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
436		let (lhs_scale, rhs_scale) = match (self.scale, other.scale) {
437			(None, None) => return Some(self.value.cmp(&other.value)),
438			(Some(lhs), Some(rhs)) => (lhs.0.get(), rhs.0.get()),
439			_ => return None,
440		};
441		if lhs_scale == rhs_scale {
442			return Some(self.value.cmp(&other.value));
443		}
444		let lhs = self.value as u128 * rhs_scale as u128;
445		let rhs = other.value as u128 * lhs_scale as u128;
446		Some(
447			lhs.cmp(&rhs)
448				.then_with(|| lhs_scale.cmp(&rhs_scale))
449				.then_with(|| self.value.cmp(&other.value)),
450		)
451	}
452}
453
454impl From<crate::time::Instant> for Timestamp {
455	/// Convert an [`Instant`](crate::time::Instant) into a millisecond-scale timestamp,
456	/// measured from the model clock's anchor.
457	///
458	/// One-way only: there is no inverse, since the anchor is jittered to keep a
459	/// [`Timestamp`] from being read back as a clock.
460	fn from(instant: crate::time::Instant) -> Self {
461		let (anchor, offset) = crate::model::clock::anchor();
462		let duration = match instant.checked_duration_since(anchor) {
463			Some(forward) => offset + forward,
464			None => offset.saturating_sub(anchor.duration_since(instant)),
465		};
466		Timestamp::from_millis(duration.as_millis() as u64).expect("clock is somehow past the year 2300")
467	}
468}
469
470#[cfg(test)]
471mod tests {
472	use super::*;
473
474	#[test]
475	fn test_from_secs() {
476		let time = Timestamp::from_secs(5).unwrap();
477		assert_eq!(time.scale(), Some(Timescale::SECOND));
478		assert_eq!(time.as_secs().unwrap(), 5);
479		assert_eq!(time.as_millis().unwrap(), 5000);
480		assert_eq!(time.as_micros().unwrap(), 5_000_000);
481		assert_eq!(time.as_nanos().unwrap(), 5_000_000_000);
482	}
483
484	#[test]
485	fn test_from_millis() {
486		let time = Timestamp::from_millis(5000).unwrap();
487		assert_eq!(time.scale(), Some(Timescale::MILLI));
488		assert_eq!(time.as_secs().unwrap(), 5);
489		assert_eq!(time.as_millis().unwrap(), 5000);
490	}
491
492	#[test]
493	fn test_from_micros() {
494		let time = Timestamp::from_micros(5_000_000).unwrap();
495		assert_eq!(time.scale(), Some(Timescale::MICRO));
496		assert_eq!(time.as_secs().unwrap(), 5);
497		assert_eq!(time.as_micros().unwrap(), 5_000_000);
498	}
499
500	#[test]
501	fn test_from_nanos() {
502		let time = Timestamp::from_nanos(5_000_000_000).unwrap();
503		assert_eq!(time.scale(), Some(Timescale::NANO));
504		assert_eq!(time.as_secs().unwrap(), 5);
505		assert_eq!(time.as_nanos().unwrap(), 5_000_000_000);
506	}
507
508	#[test]
509	fn test_timescale_new_rejects_zero_and_overflow() {
510		assert!(Timescale::new(0).is_err());
511		assert!(Timescale::new(1).is_ok());
512		assert_eq!(Timescale::new(1).unwrap(), Timescale::SECOND);
513		assert_eq!(Timescale::new(1_000).unwrap(), Timescale::MILLI);
514
515		// Above the QUIC varint range.
516		assert!(Timescale::new(1u64 << 62).is_err());
517		// Right at the top of the varint range is still valid.
518		assert!(Timescale::new((1u64 << 62) - 1).is_ok());
519	}
520
521	/// A timestamp is refused where any version could not carry it as a group's first frame,
522	/// which lite-05/06 zigzag from zero into a QUIC varint.
523	#[test]
524	fn test_timestamp_fits_a_lite06_first_frame() {
525		let max = Timestamp::new(MAX_TIMESTAMP, Timescale::MICRO).unwrap();
526		assert!(crate::coding::varint::zigzag(max.value() as i64) <= MAX_QUIC);
527
528		for value in [MAX_TIMESTAMP + 1, MAX_QUIC] {
529			assert!(Timestamp::from_micros(value).is_err(), "{value}");
530		}
531		assert!(max.checked_add(Timestamp::from_micros(1).unwrap()).is_err());
532		assert!(max.convert(Timescale::NANO).is_err());
533		assert!(Timestamp::try_from(std::time::Duration::from_nanos(MAX_TIMESTAMP + 1)).is_err());
534	}
535
536	#[test]
537	fn test_timescale_try_from_nonzero_enforces_varint() {
538		use std::num::NonZero;
539
540		assert_eq!(
541			Timescale::try_from(NonZero::new(1).unwrap()).unwrap(),
542			Timescale::SECOND
543		);
544		assert_eq!(
545			Timescale::try_from(NonZero::new((1u64 << 62) - 1).unwrap())
546				.unwrap()
547				.as_u64(),
548			(1u64 << 62) - 1
549		);
550		assert!(Timescale::try_from(NonZero::new(1u64 << 62).unwrap()).is_err());
551		assert!(Timescale::try_from(NonZero::new(u64::MAX).unwrap()).is_err());
552	}
553
554	#[test]
555	fn test_convert_to_finer() {
556		let time_ms = Timestamp::from_millis(5000).unwrap();
557		let time_us = time_ms.convert(Timescale::MICRO).unwrap();
558		assert_eq!(time_us.scale(), Some(Timescale::MICRO));
559		assert_eq!(time_us.as_micros().unwrap(), 5_000_000);
560	}
561
562	#[test]
563	fn test_convert_to_coarser() {
564		let time_ms = Timestamp::from_millis(5000).unwrap();
565		let time_s = time_ms.convert(Timescale::SECOND).unwrap();
566		assert_eq!(time_s.scale(), Some(Timescale::SECOND));
567		assert_eq!(time_s.as_secs().unwrap(), 5);
568	}
569
570	#[test]
571	fn test_convert_precision_loss() {
572		// 1234 ms = 1.234 s, rounds down to 1 s
573		let time_ms = Timestamp::from_millis(1234).unwrap();
574		let time_s = time_ms.convert(Timescale::SECOND).unwrap();
575		assert_eq!(time_s.as_secs().unwrap(), 1);
576	}
577
578	#[test]
579	fn test_convert_roundtrip() {
580		let original = Timestamp::from_millis(5000).unwrap();
581		let as_micros = original.convert(Timescale::MICRO).unwrap();
582		let back = as_micros.convert(Timescale::MILLI).unwrap();
583		assert_eq!(original.value(), back.value());
584		assert_eq!(original.scale(), back.scale());
585	}
586
587	#[test]
588	fn test_convert_same_scale() {
589		let time = Timestamp::from_millis(5000).unwrap();
590		let converted = time.convert(Timescale::MILLI).unwrap();
591		assert_eq!(time, converted);
592	}
593
594	#[test]
595	fn test_add_same_scale() {
596		let a = Timestamp::from_millis(1000).unwrap();
597		let b = Timestamp::from_millis(2000).unwrap();
598		let c = a.checked_add(b).unwrap();
599		assert_eq!(c.as_millis().unwrap(), 3000);
600		assert_eq!(c.scale(), Some(Timescale::MILLI));
601	}
602
603	#[test]
604	fn test_add_mismatched_scale() {
605		let a = Timestamp::from_millis(1000).unwrap();
606		let b = Timestamp::from_micros(1000).unwrap();
607		assert!(a.checked_add(b).is_err());
608	}
609
610	#[test]
611	fn test_new_const_matches_fallible() {
612		const C: Timestamp = Timestamp::new_const(42, Timescale::MICRO);
613		assert_eq!(C, Timestamp::new(42, Timescale::MICRO).unwrap());
614	}
615
616	#[test]
617	fn test_zero_is_scale_aware() {
618		// ZERO is second-scale. is_zero() sees the value regardless of scale, but
619		// equality is structural, so it's not interchangeable with 0 at another scale.
620		assert!(Timestamp::ZERO.is_zero());
621		let zero_ms = Timestamp::from_millis(0).unwrap();
622		assert!(zero_ms.is_zero());
623		assert_ne!(Timestamp::ZERO, zero_ms);
624		assert_ne!(Timestamp::ZERO.partial_cmp(&zero_ms), Some(std::cmp::Ordering::Equal));
625	}
626
627	#[test]
628	fn test_sub_underflow() {
629		let a = Timestamp::from_millis(1000).unwrap();
630		let b = Timestamp::from_millis(2000).unwrap();
631		assert!(a.checked_sub(b).is_err());
632	}
633
634	#[test]
635	fn test_ordering_same_scale() {
636		let a = Timestamp::from_secs(1).unwrap();
637		let b = Timestamp::from_secs(2).unwrap();
638		assert!(a < b);
639		assert!(b > a);
640	}
641
642	#[test]
643	fn test_ordering_across_known_scales() {
644		// Cross-scale ordering normalizes to a common scale.
645		let one_sec = Timestamp::from_secs(1).unwrap();
646		let two_ms = Timestamp::from_millis(2).unwrap();
647		assert!(one_sec > two_ms);
648		assert!(two_ms < one_sec);
649
650		// Temporally-equivalent timestamps with different representations are NOT
651		// Equal under cmp: derived Eq compares fields, and Ord must agree.
652		let one_sec_b = Timestamp::from_millis(1000).unwrap();
653		assert_ne!(one_sec.partial_cmp(&one_sec_b), Some(std::cmp::Ordering::Equal));
654		assert_ne!(one_sec, one_sec_b);
655		assert_eq!(one_sec.partial_cmp(&one_sec), Some(std::cmp::Ordering::Equal));
656
657		// Mixed-scale sort lands in correct temporal order.
658		let mut items = [
659			Timestamp::from_secs(2).unwrap(),
660			Timestamp::from_millis(500).unwrap(),
661			Timestamp::from_micros(1_500_000).unwrap(),
662		];
663		items.sort_by(|a, b| a.partial_cmp(b).unwrap());
664		assert_eq!(items[0], Timestamp::from_millis(500).unwrap());
665		assert_eq!(items[1], Timestamp::from_micros(1_500_000).unwrap());
666		assert_eq!(items[2], Timestamp::from_secs(2).unwrap());
667	}
668
669	#[test]
670	fn test_duration_conversion() {
671		let duration = std::time::Duration::from_secs(5);
672		let time: Timestamp = duration.try_into().unwrap();
673		assert_eq!(time.scale(), Some(Timescale::NANO));
674		assert_eq!(time.as_secs().unwrap(), 5);
675
676		let duration_back: std::time::Duration = time.try_into().unwrap();
677		assert_eq!(duration_back.as_secs(), 5);
678	}
679
680	#[test]
681	fn test_debug_format_units() {
682		let t = Timestamp::from_millis(100_000).unwrap();
683		assert_eq!(format!("{:?}", t), "100s");
684
685		let t = Timestamp::from_millis(100).unwrap();
686		assert_eq!(format!("{:?}", t), "100ms");
687
688		let t = Timestamp::from_micros(1500).unwrap();
689		assert_eq!(format!("{:?}", t), "1500µs");
690
691		let t = Timestamp::from_micros(1000).unwrap();
692		assert_eq!(format!("{:?}", t), "1ms");
693	}
694
695	/// A scale-less key carries no time: anything needing a scale fails, it orders only
696	/// against other keys, and arithmetic stays among keys.
697	#[test]
698	fn test_unscaled_has_no_time() {
699		let key = Timestamp::unscaled(7);
700		assert_eq!((key.value(), key.scale()), (7, None));
701		assert!(key.convert(Timescale::MILLI).is_err());
702		assert!(key.as_millis().is_err());
703		assert!(key.as_secs().is_err());
704		assert!(std::time::Duration::try_from(key).is_err());
705		// A key spans every group key, past where a time stops.
706		assert_eq!(Timestamp::unscaled(u64::MAX - 1).value(), u64::MAX - 1);
707		assert!(
708			Timestamp::unscaled(u64::MAX)
709				.checked_add(Timestamp::unscaled(1))
710				.is_err()
711		);
712
713		let millis = Timestamp::from_millis(7).unwrap();
714		assert_ne!(key, millis);
715		assert_eq!(key.partial_cmp(&millis), None);
716		assert_eq!(millis.partial_cmp(&key), None, "incomparable either way");
717		assert!(key.checked_add(millis).is_err());
718
719		let next = Timestamp::unscaled(8);
720		assert!(key < next);
721		assert_eq!(key.checked_add(Timestamp::unscaled(1)).unwrap(), next);
722		assert_eq!(format!("{key:?}"), "#7");
723	}
724
725	#[test]
726	fn test_custom_scale_convert() {
727		// 120 units at 60Hz = 2 seconds, expressed at 1000Hz = 2000 ms.
728		let scale_60 = Timescale::new(60).unwrap();
729		let t = Timestamp::new(120, scale_60)
730			.unwrap()
731			.convert(Timescale::MILLI)
732			.unwrap();
733		assert_eq!(t.scale(), Some(Timescale::MILLI));
734		assert_eq!(t.as_millis().unwrap(), 2000);
735	}
736}