co_primitives/types/
co_date.rs1use crate::Date;
5use std::{
6 fmt::{Debug, Formatter},
7 sync::{Arc, Mutex},
8 time::Duration,
9};
10
11pub type CoDateRef = dyn CoDate;
12
13pub trait CoDate: Send + Sync + 'static {
14 fn now(&self) -> Date;
15
16 fn now_duration(&self) -> Duration {
17 Duration::from_millis(self.now())
18 }
19
20 fn boxed(self) -> DynamicCoDate
21 where
22 Self: Sized,
23 {
24 DynamicCoDate::new(self)
25 }
26}
27
28#[derive(Clone)]
29pub struct DynamicCoDate(Arc<dyn CoDate>);
30impl Debug for DynamicCoDate {
31 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
32 f.debug_tuple("DynamicCoDate").field(&self.0.now()).finish()
33 }
34}
35impl DynamicCoDate {
36 pub fn new(date: impl CoDate) -> Self {
37 Self(Arc::new(date))
38 }
39}
40impl CoDate for DynamicCoDate {
41 fn now(&self) -> Date {
42 self.0.now()
43 }
44
45 fn boxed(self) -> DynamicCoDate
46 where
47 Self: Sized,
48 {
49 self
50 }
51}
52
53#[derive(Debug, Clone)]
54pub struct StaticCoDate(pub Date);
55impl CoDate for StaticCoDate {
56 fn now(&self) -> Date {
57 self.0
58 }
59}
60
61#[derive(Debug, Default, Clone)]
62pub struct MonotonicCoDate(Arc<Mutex<Date>>);
63impl CoDate for MonotonicCoDate {
64 fn now(&self) -> Date {
65 let mut time = self.0.lock().unwrap();
66 let result = *time;
67 *time += 1;
68 result
69 }
70}