swarm_bot_packets/
types.rs

1use std::{
2    fmt::{Display, Formatter},
3    pin::Pin,
4};
5
6use tokio::io::{AsyncRead, AsyncReadExt};
7
8use crate::{
9    read::{ByteReadable, ByteReadableLike, ByteReader},
10    write::{ByteWritable, ByteWriter},
11};
12
13pub trait Packet {
14    const ID: u32;
15    const STATE: PacketState;
16}
17
18#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
19pub enum PacketState {
20    Handshake,
21    Status,
22    Login,
23    Play,
24}
25
26impl Display for PacketState {
27    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
28        let res = match self {
29            PacketState::Handshake => "handshake",
30            PacketState::Status => "status",
31            PacketState::Login => "login",
32            PacketState::Play => "play",
33        };
34        f.write_str(res)
35    }
36}
37
38#[derive(Copy, Clone, Debug)]
39pub struct VarInt(pub i32);
40
41pub type Angle = u8;
42pub type Identifier = String;
43pub type Chat = String;
44
45pub struct BitField {
46    pub values: [bool; 8],
47}
48
49impl From<VarInt> for u32 {
50    fn from(elem: VarInt) -> Self {
51        elem.0 as u32
52    }
53}
54
55impl From<VarInt> for i32 {
56    fn from(elem: VarInt) -> Self {
57        elem.0
58    }
59}
60
61impl From<u8> for BitField {
62    fn from(mut byte: u8) -> BitField {
63        let mut values = [false; 8];
64        let mut i = 0;
65        while byte != 0 {
66            let val = byte & 0b10000000 != 0;
67            values[i] = val;
68            byte <<= 1;
69            i += 1;
70        }
71        BitField { values }
72    }
73}
74
75#[derive(Copy, Clone, Debug)]
76pub struct VarUInt(pub usize);
77
78impl From<i32> for VarInt {
79    fn from(input: i32) -> Self {
80        VarInt(input)
81    }
82}
83
84/// Writes like a Vec but without len
85#[derive(Debug)]
86pub struct RawVec<T = u8>(pub Vec<T>);
87
88impl<T> RawVec<T> {
89    #[inline]
90    pub fn len(&self) -> usize {
91        self.0.len()
92    }
93
94    pub fn is_empty(&self) -> bool {
95        self.0.len() == 0
96    }
97
98    // TODO: how does ownership inference work here
99    #[inline]
100    pub fn inner(self) -> Vec<T> {
101        self.0
102    }
103}
104
105impl ByteReadable for RawVec {
106    fn read_from_bytes(byte_reader: &mut ByteReader) -> Self {
107        let mut inner = Vec::new();
108        while !byte_reader.empty() {
109            let value: u8 = byte_reader.read();
110            inner.push(value);
111        }
112        RawVec(inner)
113    }
114}
115
116impl From<Vec<u8>> for RawVec {
117    fn from(data: Vec<u8>) -> Self {
118        RawVec(data)
119    }
120}
121
122impl ByteWritable for RawVec {
123    fn write_to_bytes(self, writer: &mut ByteWriter) {
124        for value in self.inner() {
125            writer.write(value);
126        }
127    }
128}
129
130impl<T: ByteReadable> ByteReadableLike for RawVec<T> {
131    type Param = usize;
132
133    fn read_from_bytes(byte_reader: &mut ByteReader, param: &usize) -> Self {
134        let len = *param;
135        let mut inner: Vec<T> = Vec::with_capacity(len);
136        for _ in 0..len {
137            inner.push(byte_reader.read());
138        }
139        RawVec(inner)
140    }
141}
142
143#[derive(Debug, Copy, Clone)]
144pub struct UUIDHyphenated(pub u128);
145
146impl ByteReadable for UUIDHyphenated {
147    fn read_from_bytes(byte_reader: &mut ByteReader) -> Self {
148        let mut str: String = byte_reader.read();
149        str = str.replace('-', "");
150        UUIDHyphenated(u128::from_str_radix(&str, 16).unwrap())
151    }
152}
153
154impl From<UUIDHyphenated> for UUID {
155    fn from(hyph: UUIDHyphenated) -> Self {
156        UUID(hyph.0)
157    }
158}
159
160#[derive(Debug, Copy, Clone, Default)]
161pub struct UUID(pub u128);
162
163impl From<&String> for UUID {
164    fn from(s: &String) -> Self {
165        let inner = u128::from_str_radix(s, 16).unwrap();
166        UUID(inner)
167    }
168}
169
170impl Display for UUID {
171    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
172        f.write_fmt(format_args!("{:032x}", self.0))
173    }
174}
175
176impl ByteWritable for UUID {
177    fn write_to_bytes(self, writer: &mut ByteWriter) {
178        writer.write(self.0);
179    }
180}
181
182impl ByteReadable for UUID {
183    fn read_from_bytes(byte_reader: &mut ByteReader) -> Self {
184        let inner: u128 = byte_reader.read();
185        UUID(inner)
186    }
187}
188
189impl From<usize> for VarInt {
190    fn from(input: usize) -> Self {
191        VarInt(input as i32)
192    }
193}
194
195impl From<u32> for VarInt {
196    fn from(input: u32) -> Self {
197        VarInt(input as i32)
198    }
199}
200
201// pub type NBT = nbt::Blob;
202
203impl ByteWritable for VarInt {
204    fn write_to_bytes(self, writer: &mut ByteWriter) {
205        const PART: u32 = 0x7F;
206        let mut val = self.0 as u32;
207        loop {
208            if (val & !PART) == 0 {
209                writer.write(val as u8);
210                return;
211            }
212            writer.write(((val & PART) | 0x80) as u8);
213            val >>= 7;
214        }
215    }
216}
217
218impl ByteReadable for VarInt {
219    fn read_from_bytes(byte_reader: &mut ByteReader) -> Self {
220        const PART: u32 = 0x7F;
221        let mut size = 0;
222        let mut val = 0u32;
223        loop {
224            let b: u8 = byte_reader.read();
225            let b = b as u32;
226            val |= (b & PART) << (size * 7);
227            size += 1;
228            if size > 5 {
229                panic!("oop");
230            }
231            if (b & 0x80) == 0 {
232                break;
233            }
234        }
235        VarInt(val as i32)
236    }
237}
238
239impl VarInt {
240    pub async fn read_async<R: AsyncRead>(mut reader: Pin<&mut R>) -> VarInt {
241        const PART: u32 = 0x7F;
242        let mut size = 0;
243        let mut val = 0u32;
244        loop {
245            let b = reader.read_u8().await.unwrap() as u32;
246            val |= (b & PART) << (size * 7);
247            size += 1;
248            if size > 5 {
249                panic!("oop");
250            }
251            if (b & 0x80) == 0 {
252                break;
253            }
254        }
255        VarInt(val as i32)
256    }
257}
258
259impl ByteReadable for VarUInt {
260    fn read_from_bytes(byte_reader: &mut ByteReader) -> Self {
261        let VarInt(contents) = byte_reader.read();
262        VarUInt(contents as usize)
263    }
264}