1use rand::Rng;
2
3use crate::coding::{Decode, DecodeError, Encode, VarInt};
4
5use std::sync::LazyLock;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8pub type Time = Timescale<1_000>;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
14#[error("time overflow")]
15pub struct TimeOverflow;
16
17#[derive(Clone, Default, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25pub struct Timescale<const SCALE: u64>(VarInt);
26
27impl<const SCALE: u64> Timescale<SCALE> {
28 pub const MAX: Self = Self(VarInt::MAX);
30
31 pub const ZERO: Self = Self(VarInt::ZERO);
33
34 pub const fn new(value: u32) -> Self {
35 Self(VarInt::from_u32(value))
36 }
37
38 pub const fn new_u64(value: u64) -> Result<Self, TimeOverflow> {
39 match VarInt::from_u64(value) {
40 Some(varint) => Ok(Self(varint)),
41 None => Err(TimeOverflow),
42 }
43 }
44
45 pub const fn from_secs(seconds: u64) -> Result<Self, TimeOverflow> {
47 match seconds.checked_mul(SCALE) {
49 Some(value) => Self::new_u64(value),
50 None => Err(TimeOverflow),
51 }
52 }
53
54 pub const fn from_secs_unchecked(seconds: u64) -> Self {
55 match Self::from_secs(seconds) {
56 Ok(time) => time,
57 Err(_) => panic!("time overflow"),
58 }
59 }
60
61 pub const fn from_millis(millis: u64) -> Result<Self, TimeOverflow> {
63 Self::from_scale(millis, 1000)
64 }
65
66 pub const fn from_millis_unchecked(millis: u64) -> Self {
67 Self::from_scale_unchecked(millis, 1000)
68 }
69
70 pub const fn from_micros(micros: u64) -> Result<Self, TimeOverflow> {
71 Self::from_scale(micros, 1_000_000)
72 }
73
74 pub const fn from_micros_unchecked(micros: u64) -> Self {
75 Self::from_scale_unchecked(micros, 1_000_000)
76 }
77
78 pub const fn from_nanos(nanos: u64) -> Result<Self, TimeOverflow> {
79 Self::from_scale(nanos, 1_000_000_000)
80 }
81
82 pub const fn from_nanos_unchecked(nanos: u64) -> Self {
83 Self::from_scale_unchecked(nanos, 1_000_000_000)
84 }
85
86 pub const fn from_scale(value: u64, scale: u64) -> Result<Self, TimeOverflow> {
87 match VarInt::from_u128(value as u128 * SCALE as u128 / scale as u128) {
88 Some(varint) => Ok(Self(varint)),
89 None => Err(TimeOverflow),
90 }
91 }
92
93 pub const fn from_scale_u128(value: u128, scale: u64) -> Result<Self, TimeOverflow> {
94 match value.checked_mul(SCALE as u128) {
95 Some(value) => match VarInt::from_u128(value / scale as u128) {
96 Some(varint) => Ok(Self(varint)),
97 None => Err(TimeOverflow),
98 },
99 None => Err(TimeOverflow),
100 }
101 }
102
103 pub const fn from_scale_unchecked(value: u64, scale: u64) -> Self {
104 match Self::from_scale(value, scale) {
105 Ok(time) => time,
106 Err(_) => panic!("time overflow"),
107 }
108 }
109
110 pub const fn as_secs(self) -> u64 {
112 self.0.into_inner() / SCALE
113 }
114
115 pub const fn as_millis(self) -> u128 {
119 self.as_scale(1000)
120 }
121
122 pub const fn as_micros(self) -> u128 {
124 self.as_scale(1_000_000)
125 }
126
127 pub const fn as_nanos(self) -> u128 {
129 self.as_scale(1_000_000_000)
130 }
131
132 pub const fn as_scale(self, scale: u64) -> u128 {
133 self.0.into_inner() as u128 * scale as u128 / SCALE as u128
134 }
135
136 pub const fn max(self, other: Self) -> Self {
138 if self.0.into_inner() > other.0.into_inner() {
139 self
140 } else {
141 other
142 }
143 }
144
145 pub const fn checked_add(self, rhs: Self) -> Result<Self, TimeOverflow> {
146 let lhs = self.0.into_inner();
147 let rhs = rhs.0.into_inner();
148 match lhs.checked_add(rhs) {
149 Some(result) => Self::new_u64(result),
150 None => Err(TimeOverflow),
151 }
152 }
153
154 pub const fn checked_sub(self, rhs: Self) -> Result<Self, TimeOverflow> {
155 let lhs = self.0.into_inner();
156 let rhs = rhs.0.into_inner();
157 match lhs.checked_sub(rhs) {
158 Some(result) => Self::new_u64(result),
159 None => Err(TimeOverflow),
160 }
161 }
162
163 pub const fn is_zero(self) -> bool {
164 self.0.into_inner() == 0
165 }
166
167 pub fn now() -> Self {
168 tokio::time::Instant::now().into()
170 }
171
172 pub const fn convert<const NEW_SCALE: u64>(self) -> Result<Timescale<NEW_SCALE>, TimeOverflow> {
177 let value = self.0.into_inner();
178 match (value as u128).checked_mul(NEW_SCALE as u128) {
180 Some(v) => match v.checked_div(SCALE as u128) {
181 Some(v) => match VarInt::from_u128(v) {
182 Some(varint) => Ok(Timescale(varint)),
183 None => Err(TimeOverflow),
184 },
185 None => Err(TimeOverflow),
186 },
187 None => Err(TimeOverflow),
188 }
189 }
190}
191
192impl<const SCALE: u64> TryFrom<std::time::Duration> for Timescale<SCALE> {
193 type Error = TimeOverflow;
194
195 fn try_from(duration: std::time::Duration) -> Result<Self, Self::Error> {
196 Self::from_scale_u128(duration.as_nanos(), 1_000_000_000)
197 }
198}
199
200impl<const SCALE: u64> From<Timescale<SCALE>> for std::time::Duration {
201 fn from(time: Timescale<SCALE>) -> Self {
202 std::time::Duration::new(time.as_secs(), (time.as_nanos() % 1_000_000_000) as u32)
203 }
204}
205
206impl<const SCALE: u64> std::fmt::Debug for Timescale<SCALE> {
207 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208 let nanos = self.as_nanos();
209
210 if nanos.is_multiple_of(1_000_000_000) {
213 write!(f, "{}s", nanos / 1_000_000_000)
214 } else if nanos.is_multiple_of(1_000_000) {
215 write!(f, "{}ms", nanos / 1_000_000)
216 } else if nanos.is_multiple_of(1_000) {
217 write!(f, "{}µs", nanos / 1_000)
218 } else {
219 write!(f, "{}ns", nanos)
220 }
221 }
222}
223
224impl<const SCALE: u64> std::ops::Add for Timescale<SCALE> {
225 type Output = Self;
226
227 fn add(self, rhs: Self) -> Self {
228 self.checked_add(rhs).expect("time overflow")
229 }
230}
231
232impl<const SCALE: u64> std::ops::AddAssign for Timescale<SCALE> {
233 fn add_assign(&mut self, rhs: Self) {
234 *self = *self + rhs;
235 }
236}
237
238impl<const SCALE: u64> std::ops::Sub for Timescale<SCALE> {
239 type Output = Self;
240
241 fn sub(self, rhs: Self) -> Self {
242 self.checked_sub(rhs).expect("time overflow")
243 }
244}
245
246impl<const SCALE: u64> std::ops::SubAssign for Timescale<SCALE> {
247 fn sub_assign(&mut self, rhs: Self) {
248 *self = *self - rhs;
249 }
250}
251
252static TIME_ANCHOR: LazyLock<(std::time::Instant, SystemTime)> = LazyLock::new(|| {
254 let jitter = std::time::Duration::from_millis(rand::rng().random_range(0..69_420));
258 (std::time::Instant::now(), SystemTime::now() - jitter)
259});
260
261impl<const SCALE: u64> From<std::time::Instant> for Timescale<SCALE> {
263 fn from(instant: std::time::Instant) -> Self {
264 let (anchor_instant, anchor_system) = *TIME_ANCHOR;
265
266 let system = match instant.checked_duration_since(anchor_instant) {
268 Some(forward) => anchor_system + forward,
269 None => anchor_system - anchor_instant.duration_since(instant),
270 };
271
272 system
275 .duration_since(UNIX_EPOCH)
276 .expect("dude your clock is earlier than 1970")
277 .try_into()
278 .expect("dude your clock is later than 2116")
279 }
280}
281
282impl<const SCALE: u64> From<tokio::time::Instant> for Timescale<SCALE> {
283 fn from(instant: tokio::time::Instant) -> Self {
284 instant.into_std().into()
285 }
286}
287
288impl<const SCALE: u64, V> Decode<V> for Timescale<SCALE> {
289 fn decode<R: bytes::Buf>(r: &mut R, version: V) -> Result<Self, DecodeError> {
290 let v = VarInt::decode(r, version)?;
291 Ok(Self(v))
292 }
293}
294
295impl<const SCALE: u64, V> Encode<V> for Timescale<SCALE> {
296 fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) {
297 self.0.encode(w, version)
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 #[test]
306 fn test_from_secs() {
307 let time = Time::from_secs(5).unwrap();
308 assert_eq!(time.as_secs(), 5);
309 assert_eq!(time.as_millis(), 5000);
310 assert_eq!(time.as_micros(), 5_000_000);
311 assert_eq!(time.as_nanos(), 5_000_000_000);
312 }
313
314 #[test]
315 fn test_from_millis() {
316 let time = Time::from_millis(5000).unwrap();
317 assert_eq!(time.as_secs(), 5);
318 assert_eq!(time.as_millis(), 5000);
319 }
320
321 #[test]
322 fn test_from_micros() {
323 let time = Time::from_micros(5_000_000).unwrap();
324 assert_eq!(time.as_secs(), 5);
325 assert_eq!(time.as_millis(), 5000);
326 assert_eq!(time.as_micros(), 5_000_000);
327 }
328
329 #[test]
330 fn test_from_nanos() {
331 let time = Time::from_nanos(5_000_000_000).unwrap();
332 assert_eq!(time.as_secs(), 5);
333 assert_eq!(time.as_millis(), 5000);
334 assert_eq!(time.as_micros(), 5_000_000);
335 assert_eq!(time.as_nanos(), 5_000_000_000);
336 }
337
338 #[test]
339 fn test_zero() {
340 let time = Time::ZERO;
341 assert_eq!(time.as_secs(), 0);
342 assert_eq!(time.as_millis(), 0);
343 assert_eq!(time.as_micros(), 0);
344 assert_eq!(time.as_nanos(), 0);
345 assert!(time.is_zero());
346 }
347
348 #[test]
349 fn test_roundtrip_millis() {
350 let values = [0, 1, 100, 1000, 999999, 1_000_000_000];
351 for &val in &values {
352 let time = Time::from_millis(val).unwrap();
353 assert_eq!(time.as_millis(), val as u128);
354 }
355 }
356
357 #[test]
358 fn test_roundtrip_micros() {
359 let values = [0, 1000, 1_000_000, 1_000_000_000];
361 for &val in &values {
362 let time = Time::from_micros(val).unwrap();
363 assert_eq!(time.as_micros(), val as u128);
364 }
365 }
366
367 #[test]
368 fn test_different_scale_seconds() {
369 type TimeInSeconds = Timescale<1>;
370 let time = TimeInSeconds::from_secs(5).unwrap();
371 assert_eq!(time.as_secs(), 5);
372 assert_eq!(time.as_millis(), 5000);
373 }
374
375 #[test]
376 fn test_different_scale_microseconds() {
377 type TimeInMicros = Timescale<1_000_000>;
378 let time = TimeInMicros::from_micros(5_000_000).unwrap();
379 assert_eq!(time.as_secs(), 5);
380 assert_eq!(time.as_micros(), 5_000_000);
381 }
382
383 #[test]
384 fn test_scale_conversion() {
385 let time = Time::from_scale(5000, 1000).unwrap();
387 assert_eq!(time.as_millis(), 5000);
388 assert_eq!(time.as_secs(), 5);
389
390 let time = Time::from_scale(5, 1).unwrap();
392 assert_eq!(time.as_millis(), 5000);
393 assert_eq!(time.as_secs(), 5);
394 }
395
396 #[test]
397 fn test_add() {
398 let a = Time::from_secs(3).unwrap();
399 let b = Time::from_secs(2).unwrap();
400 let c = a + b;
401 assert_eq!(c.as_secs(), 5);
402 assert_eq!(c.as_millis(), 5000);
403 }
404
405 #[test]
406 fn test_sub() {
407 let a = Time::from_secs(5).unwrap();
408 let b = Time::from_secs(2).unwrap();
409 let c = a - b;
410 assert_eq!(c.as_secs(), 3);
411 assert_eq!(c.as_millis(), 3000);
412 }
413
414 #[test]
415 fn test_checked_add() {
416 let a = Time::from_millis(1000).unwrap();
417 let b = Time::from_millis(2000).unwrap();
418 let c = a.checked_add(b).unwrap();
419 assert_eq!(c.as_millis(), 3000);
420 }
421
422 #[test]
423 fn test_checked_sub() {
424 let a = Time::from_millis(5000).unwrap();
425 let b = Time::from_millis(2000).unwrap();
426 let c = a.checked_sub(b).unwrap();
427 assert_eq!(c.as_millis(), 3000);
428 }
429
430 #[test]
431 fn test_checked_sub_underflow() {
432 let a = Time::from_millis(1000).unwrap();
433 let b = Time::from_millis(2000).unwrap();
434 assert!(a.checked_sub(b).is_err());
435 }
436
437 #[test]
438 fn test_max() {
439 let a = Time::from_secs(5).unwrap();
440 let b = Time::from_secs(10).unwrap();
441 assert_eq!(a.max(b), b);
442 assert_eq!(b.max(a), b);
443 }
444
445 #[test]
446 fn test_duration_conversion() {
447 let duration = std::time::Duration::from_secs(5);
448 let time: Time = duration.try_into().unwrap();
449 assert_eq!(time.as_secs(), 5);
450 assert_eq!(time.as_millis(), 5000);
451
452 let duration_back: std::time::Duration = time.into();
453 assert_eq!(duration_back.as_secs(), 5);
454 }
455
456 #[test]
457 fn test_duration_with_nanos() {
458 let duration = std::time::Duration::new(5, 500_000_000); let time: Time = duration.try_into().unwrap();
460 assert_eq!(time.as_millis(), 5500);
461
462 let duration_back: std::time::Duration = time.into();
463 assert_eq!(duration_back.as_millis(), 5500);
464 }
465
466 #[test]
467 fn test_fractional_conversion() {
468 let time = Time::from_millis(1500).unwrap();
470 assert_eq!(time.as_secs(), 1); assert_eq!(time.as_millis(), 1500);
472 assert_eq!(time.as_micros(), 1_500_000);
473 }
474
475 #[test]
476 fn test_precision_loss() {
477 let time = Time::from_micros(1234).unwrap();
481 assert_eq!(time.as_millis(), 1); assert_eq!(time.as_micros(), 1000); }
484
485 #[test]
486 fn test_scale_boundaries() {
487 let time = Time::from_millis(999).unwrap();
489 assert_eq!(time.as_secs(), 0);
490 assert_eq!(time.as_millis(), 999);
491
492 let time = Time::from_millis(1000).unwrap();
493 assert_eq!(time.as_secs(), 1);
494 assert_eq!(time.as_millis(), 1000);
495
496 let time = Time::from_millis(1001).unwrap();
497 assert_eq!(time.as_secs(), 1);
498 assert_eq!(time.as_millis(), 1001);
499 }
500
501 #[test]
502 fn test_large_values() {
503 let large_secs = 1_000_000_000u64; let time = Time::from_secs(large_secs).unwrap();
506 assert_eq!(time.as_secs(), large_secs);
507 }
508
509 #[test]
510 fn test_new() {
511 let time = Time::new(5000); assert_eq!(time.as_millis(), 5000);
513 assert_eq!(time.as_secs(), 5);
514 }
515
516 #[test]
517 fn test_new_u64() {
518 let time = Time::new_u64(5000).unwrap();
519 assert_eq!(time.as_millis(), 5000);
520 }
521
522 #[test]
523 fn test_ordering() {
524 let a = Time::from_secs(1).unwrap();
525 let b = Time::from_secs(2).unwrap();
526 assert!(a < b);
527 assert!(b > a);
528 assert_eq!(a, a);
529 }
530
531 #[test]
532 fn test_unchecked_variants() {
533 let time = Time::from_secs_unchecked(5);
534 assert_eq!(time.as_secs(), 5);
535
536 let time = Time::from_millis_unchecked(5000);
537 assert_eq!(time.as_millis(), 5000);
538
539 let time = Time::from_micros_unchecked(5_000_000);
540 assert_eq!(time.as_micros(), 5_000_000);
541
542 let time = Time::from_nanos_unchecked(5_000_000_000);
543 assert_eq!(time.as_nanos(), 5_000_000_000);
544
545 let time = Time::from_scale_unchecked(5000, 1000);
546 assert_eq!(time.as_millis(), 5000);
547 }
548
549 #[test]
550 fn test_as_scale() {
551 let time = Time::from_secs(1).unwrap();
552 assert_eq!(time.as_scale(1000), 1000);
554 assert_eq!(time.as_scale(1), 1);
556 assert_eq!(time.as_scale(1_000_000), 1_000_000);
558 }
559
560 #[test]
561 fn test_convert_to_finer() {
562 type TimeInMillis = Timescale<1_000>;
564 type TimeInMicros = Timescale<1_000_000>;
565
566 let time_millis = TimeInMillis::from_millis(5000).unwrap();
567 let time_micros: TimeInMicros = time_millis.convert().unwrap();
568
569 assert_eq!(time_micros.as_millis(), 5000);
570 assert_eq!(time_micros.as_micros(), 5_000_000);
571 }
572
573 #[test]
574 fn test_convert_to_coarser() {
575 type TimeInMillis = Timescale<1_000>;
577 type TimeInSeconds = Timescale<1>;
578
579 let time_millis = TimeInMillis::from_millis(5000).unwrap();
580 let time_secs: TimeInSeconds = time_millis.convert().unwrap();
581
582 assert_eq!(time_secs.as_secs(), 5);
583 assert_eq!(time_secs.as_millis(), 5000);
584 }
585
586 #[test]
587 fn test_convert_precision_loss() {
588 type TimeInMillis = Timescale<1_000>;
590 type TimeInSeconds = Timescale<1>;
591
592 let time_millis = TimeInMillis::from_millis(1234).unwrap();
593 let time_secs: TimeInSeconds = time_millis.convert().unwrap();
594
595 assert_eq!(time_secs.as_secs(), 1);
597 assert_eq!(time_secs.as_millis(), 1000); }
599
600 #[test]
601 fn test_convert_roundtrip() {
602 type TimeInMillis = Timescale<1_000>;
604 type TimeInMicros = Timescale<1_000_000>;
605
606 let original = TimeInMillis::from_millis(5000).unwrap();
607 let as_micros: TimeInMicros = original.convert().unwrap();
608 let back_to_millis: TimeInMillis = as_micros.convert().unwrap();
609
610 assert_eq!(original.as_millis(), back_to_millis.as_millis());
611 }
612
613 #[test]
614 fn test_convert_same_scale() {
615 type TimeInMillis = Timescale<1_000>;
617
618 let time = TimeInMillis::from_millis(5000).unwrap();
619 let converted: TimeInMillis = time.convert().unwrap();
620
621 assert_eq!(time.as_millis(), converted.as_millis());
622 }
623
624 #[test]
625 fn test_convert_microseconds_to_nanoseconds() {
626 type TimeInMicros = Timescale<1_000_000>;
627 type TimeInNanos = Timescale<1_000_000_000>;
628
629 let time_micros = TimeInMicros::from_micros(5_000_000).unwrap();
630 let time_nanos: TimeInNanos = time_micros.convert().unwrap();
631
632 assert_eq!(time_nanos.as_micros(), 5_000_000);
633 assert_eq!(time_nanos.as_nanos(), 5_000_000_000);
634 }
635
636 #[test]
637 fn test_convert_custom_scales() {
638 type TimeScale60 = Timescale<60>; type TimeScale90 = Timescale<90>; let time60 = TimeScale60::from_scale(120, 60).unwrap(); let time90: TimeScale90 = time60.convert().unwrap();
644
645 assert_eq!(time60.as_secs(), 2);
647 assert_eq!(time90.as_secs(), 2);
648 }
649
650 #[test]
651 fn test_debug_format_units() {
652 let t = Time::from_millis(100000).unwrap();
656 assert_eq!(format!("{:?}", t), "100s");
657
658 let t = Time::from_millis(1000).unwrap();
659 assert_eq!(format!("{:?}", t), "1s");
660
661 let t = Time::from_millis(100).unwrap();
663 assert_eq!(format!("{:?}", t), "100ms");
664
665 let t = Time::from_millis(5500).unwrap();
666 assert_eq!(format!("{:?}", t), "5500ms");
667
668 let t = Time::ZERO;
670 assert_eq!(format!("{:?}", t), "0s");
671
672 type TimeMicros = Timescale<1_000_000>;
674 let t = TimeMicros::from_micros(1500).unwrap();
675 assert_eq!(format!("{:?}", t), "1500µs");
676
677 let t = TimeMicros::from_micros(1000).unwrap();
678 assert_eq!(format!("{:?}", t), "1ms");
679 }
680}