celestia_tendermint/vote/
validator_index.rs1use core::{
2 convert::{TryFrom, TryInto},
3 fmt::{self, Debug, Display},
4 str::FromStr,
5};
6
7use crate::{error::Error, prelude::*};
8
9#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
11pub struct ValidatorIndex(u32);
12
13impl TryFrom<i32> for ValidatorIndex {
14 type Error = Error;
15
16 fn try_from(value: i32) -> Result<Self, Self::Error> {
17 Ok(ValidatorIndex(
18 value.try_into().map_err(Error::negative_validator_index)?,
19 ))
20 }
21}
22
23impl From<ValidatorIndex> for i32 {
24 fn from(value: ValidatorIndex) -> Self {
25 value.value() as i32 }
27}
28
29impl TryFrom<u32> for ValidatorIndex {
30 type Error = Error;
31
32 fn try_from(value: u32) -> Result<Self, Self::Error> {
33 let _val: i32 = value.try_into().map_err(Error::integer_overflow)?;
34 Ok(ValidatorIndex(value))
35 }
36}
37
38impl From<ValidatorIndex> for u32 {
39 fn from(value: ValidatorIndex) -> Self {
40 value.value()
41 }
42}
43
44impl TryFrom<usize> for ValidatorIndex {
45 type Error = Error;
46
47 fn try_from(value: usize) -> Result<Self, Self::Error> {
48 Ok(ValidatorIndex(
49 value.try_into().map_err(Error::integer_overflow)?,
50 ))
51 }
52}
53
54impl From<ValidatorIndex> for usize {
55 fn from(value: ValidatorIndex) -> Self {
56 value
57 .value()
58 .try_into()
59 .expect("Integer overflow: system usize maximum smaller than i32 maximum")
60 }
61}
62
63impl ValidatorIndex {
64 pub fn value(&self) -> u32 {
66 self.0
67 }
68}
69
70impl Debug for ValidatorIndex {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "vote::ValidatorIndex({})", self.0)
73 }
74}
75
76impl Display for ValidatorIndex {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "{}", self.0)
79 }
80}
81
82impl FromStr for ValidatorIndex {
83 type Err = Error;
84
85 fn from_str(s: &str) -> Result<Self, Error> {
86 ValidatorIndex::try_from(
87 s.parse::<u32>()
88 .map_err(|e| Error::parse_int("validator index decode".to_string(), e))?,
89 )
90 }
91}