antelope/chain/
key_type.rs

1use std::fmt::{Display, Formatter};
2
3use serde::{Deserialize, Serialize};
4
5use crate::chain::{Encoder, Packer};
6
7#[derive(Clone, Debug, Copy, Eq, PartialEq, Default, Serialize, Deserialize)]
8pub enum KeyType {
9    #[default]
10    K1,
11    R1,
12    // ... other variants ...
13}
14
15pub trait KeyTypeTrait {
16    fn from_string(s: &str) -> Result<KeyType, String>;
17    fn from_index(i: u8) -> Result<KeyType, String>;
18    fn to_index(&self) -> u8;
19}
20
21impl KeyTypeTrait for KeyType {
22    fn from_string(s: &str) -> Result<KeyType, String> {
23        if s == "K1" {
24            return Ok(KeyType::K1);
25        }
26
27        if s == "R1" {
28            return Ok(KeyType::R1);
29        }
30
31        Err(format!("Unknown key type {s}"))
32    }
33
34    fn from_index(i: u8) -> Result<KeyType, String> {
35        if i == 0 {
36            return Ok(KeyType::K1);
37        }
38
39        if i == 1 {
40            return Ok(KeyType::R1);
41        }
42        Err(format!("Unknown KeyType index {i}"))
43    }
44
45    fn to_index(&self) -> u8 {
46        match self {
47            KeyType::K1 => 0,
48            KeyType::R1 => 1,
49        }
50    }
51}
52
53impl Display for KeyType {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        match self {
56            KeyType::K1 => {
57                write!(f, "K1")
58            }
59            KeyType::R1 => {
60                write!(f, "R1")
61            }
62        }
63    }
64}
65
66impl Packer for KeyType {
67    fn size(&self) -> usize {
68        1usize
69    }
70
71    fn pack(&self, enc: &mut Encoder) -> usize {
72        let data = enc.alloc(self.size());
73        match self {
74            KeyType::K1 => data[0] = 0u8,
75            KeyType::R1 => data[0] = 1u8,
76        }
77        self.size()
78    }
79
80    fn unpack(&mut self, data: &[u8]) -> usize {
81        assert!(
82            data.len() >= self.size(),
83            "KeyType::unpack: buffer overflow"
84        );
85        *self = KeyType::from_index(data[0]).unwrap();
86        self.size()
87    }
88}