casper_types/
block_time.rs

1use alloc::vec::Vec;
2
3use crate::bytesrepr::{Error, FromBytes, ToBytes, U64_SERIALIZED_LENGTH};
4
5/// The number of bytes in a serialized [`BlockTime`].
6pub const BLOCKTIME_SERIALIZED_LENGTH: usize = U64_SERIALIZED_LENGTH;
7
8/// A newtype wrapping a [`u64`] which represents the block time.
9#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd)]
10pub struct BlockTime(u64);
11
12impl BlockTime {
13    /// Constructs a `BlockTime`.
14    pub fn new(value: u64) -> Self {
15        BlockTime(value)
16    }
17
18    /// Saturating integer subtraction. Computes `self - other`, saturating at `0` instead of
19    /// overflowing.
20    #[must_use]
21    pub fn saturating_sub(self, other: BlockTime) -> Self {
22        BlockTime(self.0.saturating_sub(other.0))
23    }
24}
25
26impl From<BlockTime> for u64 {
27    fn from(blocktime: BlockTime) -> Self {
28        blocktime.0
29    }
30}
31
32impl ToBytes for BlockTime {
33    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
34        self.0.to_bytes()
35    }
36
37    fn serialized_length(&self) -> usize {
38        BLOCKTIME_SERIALIZED_LENGTH
39    }
40}
41
42impl FromBytes for BlockTime {
43    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
44        let (time, rem) = FromBytes::from_bytes(bytes)?;
45        Ok((BlockTime::new(time), rem))
46    }
47}