rsfn_file/header/fields/
protocol_version.rs1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum ProtocolVersion {
6 Plain,
7 Version2,
8 Version3,
9 Unknown(u8),
10}
11
12impl From<[u8; 1]> for ProtocolVersion {
13 fn from(value: [u8; 1]) -> Self {
14 value[0].into()
15 }
16}
17
18impl From<u8> for ProtocolVersion {
19 fn from(value: u8) -> Self {
20 match value {
21 0x00 => Self::Plain,
22 0x02 => Self::Version2,
23 0x03 => Self::Version3,
24 n => Self::Unknown(n),
25 }
26 }
27}
28
29impl ProtocolVersion {
30 pub fn value(&self) -> u8 {
31 match self {
32 Self::Plain => 0x00,
33 Self::Version2 => 0x02,
34 Self::Version3 => 0x03,
35 Self::Unknown(n) => *n,
36 }
37 }
38
39 pub fn describe_value(&self) -> String {
40 match self {
41 Self::Plain => "Em claro".to_string(),
42 Self::Version2 => "Segunda versão".to_string(),
43 Self::Version3 => "Terceira versão".to_string(),
44 Self::Unknown(_) => "DESCONHECIDO".to_string(),
45 }
46 }
47
48 pub fn is_valid(&self) -> bool {
49 !matches!(self, Self::Unknown(_))
50 }
51
52 pub fn to_bytes(&self) -> [u8; 1] {
53 [self.value()]
54 }
55}
56
57impl fmt::Display for ProtocolVersion {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 let value = self.value();
60 let desc = self.describe_value();
61 write!(f, "0x{value:02x} [{desc}]")
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68
69 #[test]
70 fn value_plain() {
71 let sut: ProtocolVersion = [0x00].into();
72
73 assert_eq!(sut, ProtocolVersion::Plain);
74 assert_eq!(sut, 0x00.into());
75 assert_eq!(sut.value(), 0x00);
76 assert_eq!(sut.describe_value(), "Em claro");
77 assert!(sut.is_valid());
78 assert_eq!(sut.to_bytes(), [0x00]);
79 assert_eq!(sut.to_string(), "0x00 [Em claro]");
80 }
81
82 #[test]
83 fn value_version_2() {
84 let sut: ProtocolVersion = [0x02].into();
85
86 assert_eq!(sut, ProtocolVersion::Version2);
87 assert_eq!(sut, 0x02.into());
88 assert_eq!(sut.value(), 0x02);
89 assert_eq!(sut.describe_value(), "Segunda versão");
90 assert!(sut.is_valid());
91 assert_eq!(sut.to_bytes(), [0x02]);
92 assert_eq!(sut.to_string(), "0x02 [Segunda versão]");
93 }
94
95 #[test]
96 fn value_version_3() {
97 let sut: ProtocolVersion = [0x03].into();
98
99 assert_eq!(sut, ProtocolVersion::Version3);
100 assert_eq!(sut, 0x03.into());
101 assert_eq!(sut.value(), 0x03);
102 assert_eq!(sut.describe_value(), "Terceira versão");
103 assert!(sut.is_valid());
104 assert_eq!(sut.to_bytes(), [0x03]);
105 assert_eq!(sut.to_string(), "0x03 [Terceira versão]");
106 }
107
108 #[test]
109 fn value_unknown() {
110 let sut: ProtocolVersion = [0x04].into();
111
112 assert_eq!(sut, ProtocolVersion::Unknown(0x04));
113 assert_eq!(sut, 0x04.into());
114 assert_eq!(sut.value(), 0x04);
115 assert_eq!(sut.describe_value(), "DESCONHECIDO");
116 assert!(!sut.is_valid());
117 assert_eq!(sut.to_bytes(), [0x04]);
118 assert_eq!(sut.to_string(), "0x04 [DESCONHECIDO]");
119 }
120}