1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Copyright (c) 2022 MASSA LABS <info@massa.net>
//! Unsigned time management
#![warn(missing_docs)]
#![warn(unused_crate_dependencies)]

mod error;
mod mapping_grpc;
pub use error::TimeError;
use massa_serialization::{Deserializer, Serializer, U64VarIntDeserializer, U64VarIntSerializer};
use nom::error::{context, ContextError, ParseError};
use nom::IResult;
use serde::{Deserialize, Serialize};
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::Bound;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use time::format_description::well_known::Rfc3339;
use time::{Date, OffsetDateTime};

/// Time structure used everywhere.
/// milliseconds since 01/01/1970.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MassaTime(u64);

/// Serializer for `MassaTime`
pub struct MassaTimeSerializer {
    u64_serializer: U64VarIntSerializer,
}

impl MassaTimeSerializer {
    /// Creates a `MassaTimeSerializer`
    pub fn new() -> Self {
        Self {
            u64_serializer: U64VarIntSerializer::new(),
        }
    }
}

impl Default for MassaTimeSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl Serializer<MassaTime> for MassaTimeSerializer {
    /// ```
    /// use std::ops::Bound::Included;
    /// use massa_serialization::Serializer;
    /// use massa_time::{MassaTime, MassaTimeSerializer};
    ///
    /// let time: MassaTime = MassaTime::from_millis(30);
    /// let mut serialized = Vec::new();
    /// let serializer = MassaTimeSerializer::new();
    /// serializer.serialize(&time, &mut serialized).unwrap();
    /// ```
    fn serialize(
        &self,
        value: &MassaTime,
        buffer: &mut Vec<u8>,
    ) -> Result<(), massa_serialization::SerializeError> {
        self.u64_serializer.serialize(&value.as_millis(), buffer)
    }
}

/// Deserializer for `MassaTime`
pub struct MassaTimeDeserializer {
    u64_deserializer: U64VarIntDeserializer,
}

impl MassaTimeDeserializer {
    /// Creates a `MassaTimeDeserializer`
    ///
    /// Arguments:
    /// * range: minimum value for the time to deserialize
    pub fn new(range: (Bound<MassaTime>, Bound<MassaTime>)) -> Self {
        let min = match range.0 {
            Bound::Included(x) => Bound::Included(x.as_millis()),
            Bound::Excluded(x) => Bound::Excluded(x.as_millis()),
            Bound::Unbounded => Bound::Included(0),
        };

        let max = match range.1 {
            Bound::Included(x) => Bound::Included(x.as_millis()),
            Bound::Excluded(x) => Bound::Excluded(x.as_millis()),
            Bound::Unbounded => Bound::Included(MassaTime::max().as_millis()),
        };

        Self {
            u64_deserializer: U64VarIntDeserializer::new(min, max),
        }
    }
}

impl Deserializer<MassaTime> for MassaTimeDeserializer {
    /// ```
    /// use std::ops::Bound::Included;
    /// use massa_serialization::{Serializer, Deserializer, DeserializeError};
    /// use massa_time::{MassaTime, MassaTimeSerializer, MassaTimeDeserializer};
    ///
    /// let time: MassaTime = MassaTime::from_millis(30);
    /// let mut serialized = Vec::new();
    /// let serializer = MassaTimeSerializer::new();
    /// let deserializer = MassaTimeDeserializer::new((Included(MassaTime::from_millis(0)), Included(MassaTime::from_millis(u64::MAX))));
    /// serializer.serialize(&time, &mut serialized).unwrap();
    /// let (rest, time_deser) = deserializer.deserialize::<DeserializeError>(&serialized).unwrap();
    /// assert!(rest.is_empty());
    /// assert_eq!(time, time_deser);
    /// ```
    fn deserialize<'a, E: ParseError<&'a [u8]> + ContextError<&'a [u8]>>(
        &self,
        buffer: &'a [u8],
    ) -> IResult<&'a [u8], MassaTime, E> {
        context("Failed MassaTime deserialization", |input| {
            self.u64_deserializer
                .deserialize(input)
                .map(|(rest, res)| (rest, MassaTime::from_millis(res)))
        })(buffer)
    }
}

impl fmt::Display for MassaTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_millis())
    }
}

impl From<MassaTime> for Duration {
    /// Conversion from `massa_time` to duration, representing timestamp in milliseconds.
    /// ```
    /// # use std::time::Duration;
    /// # use massa_time::*;
    /// # use std::convert::Into;
    /// let duration: Duration = Duration::from_millis(42);
    /// let time : MassaTime = MassaTime::from_millis(42);
    /// let res: Duration = time.into();
    /// assert_eq!(res, duration);
    /// ```
    fn from(value: MassaTime) -> Self {
        value.to_duration()
    }
}

impl MassaTime {
    /// Conversion from `u64`, representing timestamp in milliseconds.
    /// ```
    /// # use massa_time::*;
    /// let time : MassaTime = MassaTime::from_millis(42);
    /// ```
    pub const fn from_millis(value: u64) -> Self {
        MassaTime(value)
    }

    /// Smallest time interval
    pub const EPSILON: MassaTime = MassaTime(1);

    /// Gets current UNIX timestamp (resolution: milliseconds).
    ///
    /// ```
    /// # use std::time::{Duration, SystemTime, UNIX_EPOCH};
    /// # use massa_time::*;
    /// # use std::convert::TryFrom;
    /// # use std::cmp::max;
    /// let now_duration : Duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    /// let now_massa_time : MassaTime = MassaTime::now();
    /// let converted:MassaTime = MassaTime::from_millis(now_duration.as_millis() as u64);
    /// assert!(max(now_massa_time.saturating_sub(converted), converted.saturating_sub(now_massa_time)) < MassaTime::from_millis(100))
    /// ```
    pub fn now() -> Self {
        let now_millis = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("could not get duration since UNIX_EPOCH")
            .as_millis()
            .try_into()
            .expect("could fit current time into its underlying representation");
        MassaTime::from_millis(now_millis)
    }

    /// Conversion to `std::time::Duration`.
    /// ```
    /// # use std::time::Duration;
    /// # use massa_time::*;
    /// let duration: Duration = Duration::from_millis(42);
    /// let time : MassaTime = MassaTime::from_millis(42);
    /// let res: Duration = time.to_duration();
    /// assert_eq!(res, duration);
    /// ```
    pub fn to_duration(&self) -> Duration {
        Duration::from_millis(self.0)
    }

    /// Conversion to `u64`, representing milliseconds.
    /// ```
    /// # use massa_time::*;
    /// let time : MassaTime = MassaTime::from_millis(42);
    /// let res: u64 = time.as_millis();
    /// assert_eq!(res, 42);
    /// ```
    pub const fn as_millis(&self) -> u64 {
        self.0
    }

    /// ```
    /// # use std::time::{Duration, SystemTime, UNIX_EPOCH};
    /// # use massa_time::*;
    /// # use std::convert::TryFrom;
    /// # use std::cmp::max;
    /// # use std::time::Instant;
    /// let (cur_timestamp, cur_instant): (MassaTime, Instant) = (MassaTime::now(), Instant::now());
    /// let massa_time_instant: Instant = cur_timestamp.estimate_instant().unwrap();
    /// assert!(max(
    ///     massa_time_instant.saturating_duration_since(cur_instant),
    ///     cur_instant.saturating_duration_since(massa_time_instant)
    /// ) < std::time::Duration::from_millis(10))
    /// ```
    pub fn estimate_instant(self) -> Result<Instant, TimeError> {
        let (cur_timestamp, cur_instant) = (MassaTime::now(), Instant::now());
        if self >= cur_timestamp {
            cur_instant.checked_add(self.saturating_sub(cur_timestamp).to_duration())
        } else {
            cur_instant.checked_sub(cur_timestamp.saturating_sub(self).to_duration())
        }
        .ok_or(TimeError::TimeOverflowError)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : MassaTime = time_1.saturating_sub(time_2);
    /// assert_eq!(res, MassaTime::from_millis(42-7))
    /// ```
    #[must_use]
    pub fn saturating_sub(self, t: MassaTime) -> Self {
        MassaTime(self.0.saturating_sub(t.0))
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : MassaTime = time_1.saturating_add(time_2);
    /// assert_eq!(res, MassaTime::from_millis(42+7))
    /// ```
    #[must_use]
    pub fn saturating_add(self, t: MassaTime) -> Self {
        MassaTime(self.0.saturating_add(t.0))
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : MassaTime = time_1.checked_sub(time_2).unwrap();
    /// assert_eq!(res, MassaTime::from_millis(42-7))
    /// ```
    pub fn checked_sub(self, t: MassaTime) -> Result<Self, TimeError> {
        self.0
            .checked_sub(t.0)
            .ok_or_else(|| TimeError::CheckedOperationError("subtraction error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : MassaTime = time_1.checked_add(time_2).unwrap();
    /// assert_eq!(res, MassaTime::from_millis(42+7))
    /// ```
    pub fn checked_add(self, t: MassaTime) -> Result<Self, TimeError> {
        self.0
            .checked_add(t.0)
            .ok_or_else(|| TimeError::CheckedOperationError("addition error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : u64 = time_1.checked_div_time(time_2).unwrap();
    /// assert_eq!(res,42/7)
    /// ```
    pub fn checked_div_time(self, t: MassaTime) -> Result<u64, TimeError> {
        self.0
            .checked_div(t.0)
            .ok_or_else(|| TimeError::CheckedOperationError("division error".to_string()))
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let res : MassaTime = time_1.checked_div_u64(7).unwrap();
    /// assert_eq!(res,MassaTime::from_millis(42/7))
    /// ```
    pub fn checked_div_u64(self, n: u64) -> Result<MassaTime, TimeError> {
        self.0
            .checked_div(n)
            .ok_or_else(|| TimeError::CheckedOperationError("division error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let res : MassaTime = time_1.saturating_mul(7);
    /// assert_eq!(res,MassaTime::from_millis(42*7))
    /// ```
    #[must_use]
    pub const fn saturating_mul(self, n: u64) -> MassaTime {
        MassaTime(self.0.saturating_mul(n))
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let res : MassaTime = time_1.checked_mul(7).unwrap();
    /// assert_eq!(res,MassaTime::from_millis(42*7))
    /// ```
    pub fn checked_mul(self, n: u64) -> Result<Self, TimeError> {
        self.0
            .checked_mul(n)
            .ok_or_else(|| TimeError::CheckedOperationError("multiplication error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let time_2 : MassaTime = MassaTime::from_millis(7);
    /// let res : MassaTime = time_1.checked_rem_time(time_2).unwrap();
    /// assert_eq!(res,MassaTime::from_millis(42%7))
    /// ```
    pub fn checked_rem_time(self, t: MassaTime) -> Result<Self, TimeError> {
        self.0
            .checked_rem(t.0)
            .ok_or_else(|| TimeError::CheckedOperationError("remainder error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    /// let time_1 : MassaTime = MassaTime::from_millis(42);
    /// let res : MassaTime = time_1.checked_rem_u64(7).unwrap();
    /// assert_eq!(res,MassaTime::from_millis(42%7))
    /// ```
    pub fn checked_rem_u64(self, n: u64) -> Result<Self, TimeError> {
        self.0
            .checked_rem(n)
            .ok_or_else(|| TimeError::CheckedOperationError("remainder error".to_string()))
            .map(MassaTime)
    }

    /// ```
    /// # use massa_time::*;
    ///
    /// let time1 = MassaTime::from_millis(42);
    /// let time2 = MassaTime::from_millis(84);
    ///
    /// assert_eq!(time1.abs_diff(time2), MassaTime::from_millis(42));
    /// assert_eq!(time2.abs_diff(time1), MassaTime::from_millis(42));
    /// ```
    pub fn abs_diff(&self, t: MassaTime) -> MassaTime {
        MassaTime(self.0.abs_diff(t.0))
    }

    /// ```
    /// # use massa_time::*;
    /// let massa_time : MassaTime = MassaTime::from_millis(1_640_995_200_000);
    /// assert_eq!(massa_time.format_instant(), String::from("2022-01-01T00:00:00Z"))
    /// ```
    pub fn format_instant(&self) -> String {
        OffsetDateTime::from_unix_timestamp((self.as_millis() / 1000) as i64)
            .map(|time| time.format(&Rfc3339).unwrap_or_default())
            .unwrap_or_default()
    }

    /// ```
    /// # use massa_time::*;
    /// let massa_time : MassaTime = MassaTime::from_millis(1000*( 8 * 24*60*60 + 1 * 60*60 + 3 * 60 + 6 ));
    /// assert_eq!(massa_time.format_duration().unwrap(), String::from("8 days, 1 hours, 3 minutes, 6 seconds"))
    /// ```
    pub fn format_duration(&self) -> Result<String, TimeError> {
        let (days, hours, mins, secs) = self.days_hours_mins_secs()?;
        Ok(format!(
            "{} days, {} hours, {} minutes, {} seconds",
            days, hours, mins, secs
        ))
    }

    /// ```
    /// # use massa_time::*;
    /// let massa_time : MassaTime = MassaTime::from_utc_ymd_hms(2022, 2, 5, 22, 50, 40).unwrap();
    /// assert_eq!(massa_time.format_instant(), String::from("2022-02-05T22:50:40Z"))
    /// ```
    pub fn from_utc_ymd_hms(
        year: i32,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
    ) -> Result<MassaTime, TimeError> {
        let month = month.try_into().map_err(|_| TimeError::ConversionError)?;

        let date =
            Date::from_calendar_date(year, month, day).map_err(|_| TimeError::ConversionError)?;

        let date_time = date
            .with_hms(hour, minute, second)
            .map_err(|_| TimeError::ConversionError)?
            .assume_utc();

        Ok(MassaTime::from_millis(
            date_time
                .unix_timestamp_nanos()
                .checked_div(1_000_000)
                .ok_or(TimeError::ConversionError)? as u64,
        ))
    }

    /// ```
    /// # use massa_time::*;
    /// let massa_time = MassaTime::from_millis(1000 * ( 8 * 24*60*60 + 1 * 60*60 + 3 * 60 + 6 ));
    /// let (days, hours, mins, secs) = massa_time.days_hours_mins_secs().unwrap();
    /// assert_eq!(days, 8);
    /// assert_eq!(hours, 1);
    /// assert_eq!(mins, 3);
    /// assert_eq!(secs, 6);
    /// ```
    pub fn days_hours_mins_secs(&self) -> Result<(i64, i64, i64, i64), TimeError> {
        let time: time::Duration = time::Duration::try_from(self.to_duration())
            .map_err(|_| TimeError::TimeOverflowError)?;
        let days = time.whole_days();
        let hours = (time - time::Duration::days(days)).whole_hours();
        let mins =
            (time - time::Duration::days(days) - time::Duration::hours(hours)).whole_minutes();
        let secs = (time
            - time::Duration::days(days)
            - time::Duration::hours(hours)
            - time::Duration::minutes(mins))
        .whole_seconds();
        Ok((days, hours, mins, secs))
    }

    /// Get max MassaTime value
    pub fn max() -> MassaTime {
        MassaTime::from_millis(u64::MAX)
    }
}