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
use crate::error::{Error, Kind};
use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryInto;
use std::{
convert::TryFrom,
fmt::{self, Debug, Display},
str::FromStr,
};
use tendermint_proto::Protobuf;
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct Height(u64);
impl Protobuf<i64> for Height {}
impl TryFrom<i64> for Height {
type Error = Error;
fn try_from(value: i64) -> Result<Self, Self::Error> {
Ok(Height(value.try_into().map_err(|_| Kind::NegativeHeight)?))
}
}
impl From<Height> for i64 {
fn from(value: Height) -> Self {
value.value() as i64
}
}
impl TryFrom<u64> for Height {
type Error = Error;
fn try_from(value: u64) -> Result<Self, Self::Error> {
if value > i64::MAX as u64 {
return Err(Kind::IntegerOverflow.into());
}
Ok(Height(value))
}
}
impl From<Height> for u64 {
fn from(value: Height) -> Self {
value.value()
}
}
impl From<u32> for Height {
fn from(value: u32) -> Self {
Height(value as u64)
}
}
impl From<u16> for Height {
fn from(value: u16) -> Self {
Height(value as u64)
}
}
impl From<u8> for Height {
fn from(value: u8) -> Self {
Height(value as u64)
}
}
impl Height {
pub fn value(&self) -> u64 {
self.0
}
pub fn increment(self) -> Self {
Height::try_from(self.0.checked_add(1).expect("height overflow")).unwrap()
}
}
impl Debug for Height {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "block::Height({})", self.0)
}
}
impl Default for Height {
fn default() -> Self {
Height(1)
}
}
impl Display for Height {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for Height {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
Height::try_from(
s.parse::<u64>()
.map_err(|_| Kind::Parse.context("height decode"))?,
)
}
}
impl<'de> Deserialize<'de> for Height {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::from_str(&String::deserialize(deserializer)?)
.map_err(|e| D::Error::custom(format!("{}", e)))
}
}
impl Serialize for Height {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
i64::from(*self).to_string().serialize(serializer)
}
}
pub trait ParseHeight {
fn parse_block_height(&self) -> Result<Height, Error>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn increment_by_one() {
assert_eq!(Height::default().increment().value(), 2);
}
#[test]
fn avoid_try_unwrap_dance() {
assert_eq!(
Height::try_from(2_u64).unwrap().value(),
Height::from(2_u32).value()
);
}
}