fuel_core_interfaces/model/
block_height.rs1use derive_more::{
2 Add,
3 Deref,
4 Display,
5 From,
6 Into,
7 Sub,
8};
9use std::{
10 array::TryFromSliceError,
11 convert::{
12 TryFrom,
13 TryInto,
14 },
15};
16
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[derive(
19 Copy,
20 Clone,
21 Debug,
22 Default,
23 PartialEq,
24 PartialOrd,
25 Ord,
26 Eq,
27 Add,
28 Sub,
29 Display,
30 Into,
31 From,
32 Deref,
33 Hash,
34)]
35#[repr(transparent)]
36pub struct BlockHeight(u32);
37
38impl From<BlockHeight> for Vec<u8> {
39 fn from(height: BlockHeight) -> Self {
40 height.0.to_be_bytes().to_vec()
41 }
42}
43
44impl From<u64> for BlockHeight {
45 fn from(height: u64) -> Self {
46 Self(height as u32)
47 }
48}
49
50impl From<BlockHeight> for u64 {
51 fn from(b: BlockHeight) -> Self {
52 b.0 as u64
53 }
54}
55
56impl TryFrom<Vec<u8>> for BlockHeight {
57 type Error = TryFromSliceError;
58
59 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
60 let block_height_bytes: [u8; 4] = value.as_slice().try_into()?;
61 Ok(BlockHeight(u32::from_be_bytes(block_height_bytes)))
62 }
63}
64
65impl From<usize> for BlockHeight {
66 fn from(n: usize) -> Self {
67 BlockHeight(n as u32)
68 }
69}
70
71impl BlockHeight {
72 pub fn to_bytes(self) -> [u8; 4] {
73 self.0.to_be_bytes()
74 }
75
76 pub fn to_usize(self) -> usize {
77 self.0 as usize
78 }
79
80 pub fn as_usize(&self) -> usize {
81 self.0 as usize
82 }
83}