multiversx_chain_core/types/time/
duration_seconds.rs

1use core::ops::{Add, Sub};
2
3use super::DurationMillis;
4
5use crate::codec::*;
6
7/// Represents a duration in seconds.
8#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9#[repr(transparent)]
10pub struct DurationSeconds(pub(crate) u64);
11
12impl DurationSeconds {
13    pub const fn new(seconds: u64) -> Self {
14        DurationSeconds(seconds)
15    }
16
17    pub fn as_u64_seconds(&self) -> u64 {
18        self.0
19    }
20
21    /// Explicit conversion to milliseconds
22    pub fn to_millis(&self) -> DurationMillis {
23        DurationMillis::new(self.0 * 1000)
24    }
25
26    pub const fn zero() -> Self {
27        DurationSeconds(0)
28    }
29}
30
31// DurationSeconds + DurationSeconds = DurationSeconds
32impl Add<DurationSeconds> for DurationSeconds {
33    type Output = DurationSeconds;
34
35    fn add(self, rhs: DurationSeconds) -> Self::Output {
36        DurationSeconds(self.0 + rhs.0)
37    }
38}
39
40// DurationSeconds - DurationSeconds = DurationSeconds
41impl Sub<DurationSeconds> for DurationSeconds {
42    type Output = DurationSeconds;
43
44    fn sub(self, rhs: DurationSeconds) -> Self::Output {
45        DurationSeconds(self.0 - rhs.0)
46    }
47}
48
49impl NestedEncode for DurationSeconds {
50    fn dep_encode_or_handle_err<O, H>(&self, dest: &mut O, h: H) -> Result<(), H::HandledErr>
51    where
52        O: NestedEncodeOutput,
53        H: EncodeErrorHandler,
54    {
55        self.0.dep_encode_or_handle_err(dest, h)
56    }
57}
58
59impl TopEncode for DurationSeconds {
60    fn top_encode_or_handle_err<O, H>(&self, output: O, h: H) -> Result<(), H::HandledErr>
61    where
62        O: TopEncodeOutput,
63        H: EncodeErrorHandler,
64    {
65        self.0.top_encode_or_handle_err(output, h)
66    }
67}
68
69impl NestedDecode for DurationSeconds {
70    fn dep_decode_or_handle_err<I, H>(input: &mut I, h: H) -> Result<Self, H::HandledErr>
71    where
72        I: NestedDecodeInput,
73        H: DecodeErrorHandler,
74    {
75        Ok(DurationSeconds(u64::dep_decode_or_handle_err(input, h)?))
76    }
77}
78
79impl TopDecode for DurationSeconds {
80    fn top_decode_or_handle_err<I, H>(input: I, h: H) -> Result<Self, H::HandledErr>
81    where
82        I: TopDecodeInput,
83        H: DecodeErrorHandler,
84    {
85        Ok(DurationSeconds(u64::top_decode_or_handle_err(input, h)?))
86    }
87}
88
89impl core::fmt::Display for DurationSeconds {
90    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91        write!(f, "{} s", self.0)
92    }
93}