nardol/packet/
packet_kind.rs1use serde::{Deserialize, Serialize};
2
3use crate::bytes::Bytes;
4use crate::error::{Error, ErrorKind};
5use crate::ron::{FromRon, ToRon};
6
7#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9pub enum PacketKind {
10 Empty,
12
13 MetaData,
15
16 MetaDataEnd,
18
19 Content,
21
22 End,
27
28 Unit,
31
32 Unknown,
34}
35
36impl ToRon for PacketKind {}
37impl FromRon<'_> for PacketKind {}
38
39impl TryFrom<Bytes> for PacketKind {
40 type Error = Error;
41
42 fn try_from(value: Bytes) -> Result<Self, Self::Error> {
43 match value.get(1) {
45 Some(_) => &value[0..2],
46 None => {
47 return Err(Error::new(
48 ErrorKind::InvalidBufferSize,
49 Some(
50 concat!(
51 "impl TryFrom<Bytes> for PacketKind requires buffer of length",
52 "of at least 2 bytes.",
53 )
54 .to_string(),
55 ),
56 ))
57 }
58 };
59
60 let kind = match value[0] {
61 0 => PacketKind::Empty,
62 1 => match value[1] {
63 0 => PacketKind::MetaData,
64 1 => PacketKind::MetaDataEnd,
65 _ => PacketKind::Unknown,
66 },
67 2 => PacketKind::Content,
68 3 => PacketKind::End,
69 4 => PacketKind::Unit,
70 _ => PacketKind::Unknown,
71 };
72
73 Ok(kind)
74 }
75}
76
77impl TryFrom<&[u8]> for PacketKind {
78 type Error = Error;
79
80 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
81 match value.get(1) {
83 Some(_) => &value[0..2],
84 None => {
85 return Err(Error::new(
86 ErrorKind::InvalidBufferSize,
87 Some(
88 concat!(
89 "impl TryFrom<&[u8]> for PacketKind requires buffer of length",
90 "of at least 2 bytes.",
91 )
92 .to_string(),
93 ),
94 ))
95 }
96 };
97
98 let kind = match value[0] {
99 0 => PacketKind::Empty,
100 1 => match value[1] {
101 0 => PacketKind::MetaData,
102 1 => PacketKind::MetaDataEnd,
103 _ => PacketKind::Unknown,
104 },
105 2 => PacketKind::Content,
106 3 => PacketKind::End,
107 4 => PacketKind::Unit,
108 _ => PacketKind::Unknown,
109 };
110
111 Ok(kind)
112 }
113}
114
115impl From<PacketKind> for Bytes {
116 fn from(value: PacketKind) -> Self {
117 let mut bytes = Bytes::empty();
118
119 match value {
120 PacketKind::Empty => bytes.append(&mut Bytes::from([0, 0])),
121 PacketKind::MetaData => bytes.append(&mut Bytes::from([1, 0])),
122 PacketKind::MetaDataEnd => bytes.append(&mut Bytes::from([1, 1])),
123 PacketKind::Content => bytes.append(&mut Bytes::from([2, 0])),
124 PacketKind::End => bytes.append(&mut Bytes::from([3, 0])),
125 PacketKind::Unit => bytes.append(&mut Bytes::from([4, 0])),
126 PacketKind::Unknown => bytes.append(&mut Bytes::from([255, 0])),
127 }
128
129 bytes
130 }
131}