1#[cfg(feature="random")]
5use crate::random::FromRandom;
6
7#[cfg(feature="random")]
8use rand::Rng;
9
10use std::fmt;
11
12#[cfg(feature = "pybindings")]
13use pyo3::pyclass;
14
15#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
23#[repr(u8)]
24#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
25pub enum ProtocolVersion {
26 Unknown = 0u8,
27 V1 = 64u8,
28 V2 = 128u8,
29 V3 = 192u8,
30}
31
32impl fmt::Display for ProtocolVersion {
33 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 let r : &str;
35 match self {
36 ProtocolVersion::Unknown => {r = "Unknown"},
37 ProtocolVersion::V1 => {r = "V1"},
38 ProtocolVersion::V2 => {r = "V2"},
39 ProtocolVersion::V3 => {r = "V3"},
40 }
41 write!(f, "<ProtocolVersion: {}>", r)
42 }
43}
44
45impl ProtocolVersion {
46 pub fn to_u8(&self) -> u8 {
47 match self {
48 ProtocolVersion::Unknown => {
49 return 0;
50 }
51 ProtocolVersion::V1 => {
52 return 64;
53 }
54 ProtocolVersion::V2 => {
55 return 128;
56 }
57 ProtocolVersion::V3 => {
58 return 192;
59 }
60 }
61 }
62}
63
64impl From<u8> for ProtocolVersion {
65 fn from(value: u8) -> Self {
66 match value {
67 0 => ProtocolVersion::Unknown,
68 64 => ProtocolVersion::V1,
69 128 => ProtocolVersion::V2,
70 192 => ProtocolVersion::V3,
71 _ => ProtocolVersion::Unknown
72 }
73 }
74}
75
76#[cfg(feature = "random")]
77impl FromRandom for ProtocolVersion {
78
79 fn from_random() -> Self {
80 let choices = [
81 ProtocolVersion::Unknown,
82 ProtocolVersion::V1,
83 ProtocolVersion::V2,
84 ProtocolVersion::V3,
85 ];
86 let mut rng = rand::rng();
87 let idx = rng.random_range(0..choices.len());
88 choices[idx]
89 }
90}
91
92#[test]
93#[cfg(feature = "random")]
94fn test_protocol_version() {
95 for _ in 0..100 {
96 let pv = ProtocolVersion::from_random();
97 let pv_u8 = pv.to_u8();
98 let u8_pv = ProtocolVersion::from(pv_u8);
99 assert_eq!(pv, u8_pv);
100 }
101}
102