Skip to main content

amaru_kernel/cardano/
block_height.rs

1// Copyright 2025 PRAGMA
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{fmt, ops::Add};
16
17use crate::cbor;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
20pub struct BlockHeight(u64);
21
22impl From<u64> for BlockHeight {
23    fn from(value: u64) -> Self {
24        Self(value)
25    }
26}
27
28impl From<BlockHeight> for u64 {
29    fn from(value: BlockHeight) -> Self {
30        value.0
31    }
32}
33
34impl AsRef<BlockHeight> for BlockHeight {
35    fn as_ref(&self) -> &BlockHeight {
36        self
37    }
38}
39
40impl Add<u64> for BlockHeight {
41    type Output = Self;
42
43    fn add(self, rhs: u64) -> Self::Output {
44        Self(self.0 + rhs)
45    }
46}
47
48impl BlockHeight {
49    pub const fn new(value: u64) -> Self {
50        Self(value)
51    }
52
53    pub const fn as_u64(self) -> u64 {
54        self.0
55    }
56}
57
58impl fmt::Display for BlockHeight {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(f, "{}", self.0)
61    }
62}
63
64impl<C> cbor::Encode<C> for BlockHeight {
65    fn encode<W: cbor::encode::Write>(
66        &self,
67        e: &mut cbor::Encoder<W>,
68        ctx: &mut C,
69    ) -> Result<(), cbor::encode::Error<W::Error>> {
70        self.0.encode(e, ctx)
71    }
72}
73
74impl<'b, C> cbor::Decode<'b, C> for BlockHeight {
75    fn decode(d: &mut cbor::Decoder<'b>, ctx: &mut C) -> Result<Self, cbor::decode::Error> {
76        u64::decode(d, ctx).map(BlockHeight)
77    }
78}
79
80#[cfg(any(test, feature = "test-utils"))]
81pub use tests::*;
82
83#[cfg(any(test, feature = "test-utils"))]
84mod tests {
85    use proptest::prop_compose;
86
87    use super::*;
88    use crate::prop_cbor_roundtrip;
89
90    prop_cbor_roundtrip!(BlockHeight, any_block_height());
91
92    prop_compose! {
93        pub fn any_block_height()(h in 1..1000u64) -> BlockHeight {
94            BlockHeight::from(h)
95        }
96    }
97}