use std::fmt;
use std::str::FromStr;
use std::num::ParseIntError;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
pub type Milliseconds = u64;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Height(pub u64);
impl Height {
pub fn zero() -> Self {
Height(0)
}
pub fn next(&self) -> Self {
Height(self.0 + 1)
}
pub fn previous(&self) -> Self {
assert_ne!(0, self.0);
Height(self.0 - 1)
}
pub fn increment(&mut self) {
self.0 += 1;
}
pub fn decrement(&mut self) {
assert_ne!(0, self.0);
self.0 -= 1;
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Round(pub u32);
impl Round {
pub fn zero() -> Self {
Round(0)
}
pub fn first() -> Self {
Round(1)
}
pub fn next(&self) -> Self {
Round(self.0 + 1)
}
pub fn previous(&self) -> Self {
assert_ne!(0, self.0);
Round(self.0 - 1)
}
pub fn increment(&mut self) {
self.0 += 1;
}
pub fn decrement(&mut self) {
assert_ne!(0, self.0);
self.0 -= 1;
}
pub fn iter_to(&self, to: Round) -> RoundRangeIter {
RoundRangeIter {
next: *self,
last: to,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ValidatorId(pub u16);
impl ValidatorId {
pub fn zero() -> Self {
ValidatorId(0)
}
}
impl fmt::Display for Height {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<Height> for u64 {
fn from(val: Height) -> Self {
val.0
}
}
impl fmt::Display for Round {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<Round> for u32 {
fn from(val: Round) -> Self {
val.0
}
}
impl From<Round> for u64 {
fn from(val: Round) -> Self {
u64::from(val.0)
}
}
impl fmt::Display for ValidatorId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<ValidatorId> for u16 {
fn from(val: ValidatorId) -> Self {
val.0
}
}
impl From<ValidatorId> for usize {
fn from(val: ValidatorId) -> Self {
val.0 as usize
}
}
impl Serialize for Height {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Height {
fn deserialize<D>(deserializer: D) -> Result<Height, D::Error>
where
D: Deserializer<'de>,
{
Ok(Height(u64::deserialize(deserializer)?))
}
}
impl FromStr for Height {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Height, ParseIntError> {
u64::from_str(s).map(Height)
}
}
#[derive(Debug)]
pub struct RoundRangeIter {
next: Round,
last: Round,
}
impl Iterator for RoundRangeIter {
type Item = Round;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.last {
let res = Some(self.next);
self.next.increment();
res
} else {
None
}
}
}