1use std::num::NonZero;
2
3use crate::coding::varint::MAX_QUIC;
4
5const MAX_TIMESTAMP: u64 = (1 << 61) - 1;
11
12const fn bounded(value: u128, max: u64) -> Option<u64> {
14 if value <= max as u128 { Some(value as u64) } else { None }
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
22#[error("time overflow")]
23pub struct TimeOverflow;
24
25#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct Timescale(NonZero<u64>);
35
36impl Timescale {
37 pub const SECOND: Self = match Self::new(1) {
39 Ok(scale) => scale,
40 Err(_) => unreachable!(),
41 };
42 pub const MILLI: Self = match Self::new(1_000) {
44 Ok(scale) => scale,
45 Err(_) => unreachable!(),
46 };
47 pub const MICRO: Self = match Self::new(1_000_000) {
49 Ok(scale) => scale,
50 Err(_) => unreachable!(),
51 };
52 pub const NANO: Self = match Self::new(1_000_000_000) {
54 Ok(scale) => scale,
55 Err(_) => unreachable!(),
56 };
57
58 pub const fn new(units_per_second: u64) -> Result<Self, TimeOverflow> {
64 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 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 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#[derive(Clone, Copy, PartialEq, Eq, Hash)]
165pub struct Timestamp {
166 value: u64,
167 scale: Option<Timescale>,
168}
169
170impl Timestamp {
171 pub const ZERO: Self = Self::new_const(0, Timescale::SECOND);
179
180 pub const fn new(value: u64, scale: Timescale) -> Result<Self, TimeOverflow> {
183 Self::bounded(value, Some(scale))
184 }
185
186 pub const fn unscaled(key: u64) -> Self {
188 Self {
189 value: key,
190 scale: None,
191 }
192 }
193
194 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 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 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 pub const fn from_secs(seconds: u64) -> Result<Self, TimeOverflow> {
219 Self::new(seconds, Timescale::SECOND)
220 }
221
222 pub const fn from_millis(millis: u64) -> Result<Self, TimeOverflow> {
224 Self::new(millis, Timescale::MILLI)
225 }
226
227 pub const fn from_micros(micros: u64) -> Result<Self, TimeOverflow> {
229 Self::new(micros, Timescale::MICRO)
230 }
231
232 pub const fn from_nanos(nanos: u64) -> Result<Self, TimeOverflow> {
234 Self::new(nanos, Timescale::NANO)
235 }
236
237 pub const fn value(self) -> u64 {
239 self.value
240 }
241
242 pub const fn scale(self) -> Option<Timescale> {
244 self.scale
245 }
246
247 pub const fn is_zero(self) -> bool {
249 self.value == 0
250 }
251
252 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 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 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 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 pub const fn as_millis(self) -> Result<u128, TimeOverflow> {
300 self.as_scale(Timescale::MILLI)
301 }
302
303 pub const fn as_micros(self) -> Result<u128, TimeOverflow> {
305 self.as_scale(Timescale::MICRO)
306 }
307
308 pub const fn as_nanos(self) -> Result<u128, TimeOverflow> {
310 self.as_scale(Timescale::NANO)
311 }
312
313 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 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 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 pub(crate) const fn timed(self) -> Option<Self> {
350 match self.scale {
351 Some(_) => Some(self),
352 None => None,
353 }
354 }
355
356 #[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 pub(crate) fn later(self, other: Self) -> Self {
369 if other > self { other } else { self }
370 }
371
372 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 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 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 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 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 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 assert!(Timescale::new(1u64 << 62).is_err());
517 assert!(Timescale::new((1u64 << 62) - 1).is_ok());
519 }
520
521 #[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 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 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 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 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 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 #[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 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 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}