snops_common/state/
node_type.rs

1use crate::{format::DataFormat, prelude::MaskBit};
2
3#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
4#[serde(rename_all = "lowercase")]
5pub enum NodeType {
6    Client = 0,
7    Validator = 1,
8    Prover = 2,
9}
10
11impl AsRef<str> for NodeType {
12    fn as_ref(&self) -> &str {
13        match self {
14            Self::Client => "client",
15            Self::Validator => "validator",
16            Self::Prover => "prover",
17        }
18    }
19}
20
21impl NodeType {
22    pub fn flag(self) -> &'static str {
23        match self {
24            Self::Client => "--client",
25            Self::Validator => "--validator",
26            Self::Prover => "--prover",
27        }
28    }
29
30    pub fn bit(self) -> usize {
31        (match self {
32            Self::Validator => MaskBit::Validator,
33            Self::Prover => MaskBit::Prover,
34            Self::Client => MaskBit::Client,
35        }) as usize
36    }
37}
38
39impl std::fmt::Display for NodeType {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.write_str(self.as_ref())
42    }
43}
44
45impl std::str::FromStr for NodeType {
46    type Err = &'static str;
47
48    fn from_str(s: &str) -> Result<Self, Self::Err> {
49        match s {
50            "client" => Ok(Self::Client),
51            "validator" => Ok(Self::Validator),
52            "prover" => Ok(Self::Prover),
53            _ => Err("invalid node type string"),
54        }
55    }
56}
57
58impl DataFormat for NodeType {
59    type Header = u8;
60    const LATEST_HEADER: Self::Header = 1;
61
62    fn write_data<W: std::io::Write>(
63        &self,
64        writer: &mut W,
65    ) -> Result<usize, crate::format::DataWriteError> {
66        Ok(writer.write(&[match self {
67            Self::Client => 0,
68            Self::Validator => 1,
69            Self::Prover => 2,
70        }])?)
71    }
72
73    fn read_data<R: std::io::Read>(
74        reader: &mut R,
75        header: &Self::Header,
76    ) -> Result<Self, crate::format::DataReadError> {
77        if *header != Self::LATEST_HEADER {
78            return Err(crate::format::DataReadError::unsupported(
79                "NodeType",
80                Self::LATEST_HEADER,
81                *header,
82            ));
83        }
84
85        let mut byte = [0u8; 1];
86        reader.read_exact(&mut byte)?;
87        match byte[0] {
88            0 => Ok(Self::Client),
89            1 => Ok(Self::Validator),
90            2 => Ok(Self::Prover),
91            n => Err(crate::format::DataReadError::Custom(format!(
92                "invalid NodeType tag {n}, expected 0, 1, or 2"
93            ))),
94        }
95    }
96}