minecraft_net/
fields.rs

1pub mod nbt;
2pub mod slot;
3pub mod block_predicate;
4pub mod particles;
5pub mod chunk_and_light;
6pub mod general;
7
8use crate::errors::Errors;
9use std::io::Read;
10use crate::Field;
11use crate::fields::types::PrefixedArray;
12
13pub mod types {
14    pub type Byte = i8;
15    pub type UByte = u8;
16    pub type Short = i16;
17    pub type UShort = u16;
18    pub type Int = i32;
19    pub type UInt = u32;
20    pub type Long = i64;
21    pub type UUID = u128;
22    pub type Float = f32;
23    pub type Double = f64;
24    pub type Identifier = String;
25    pub type Angle = u8;
26    pub type VarInt = Int;
27    pub type VarLong = Long;
28    pub type PrefixedArray<T> = Vec<T>;
29    pub type PrefixedOptional<T> = Option<T>;
30    pub type Position = crate::fields::general::Position;
31    pub type NBT = super::nbt::NetworkNBT;
32    pub type TextComponent = super::nbt::TextComponent;
33}
34
35const SEGMENT_BITS: u8 = 0x7F;
36const CONTINUE_BIT: u8 = 0x80;
37
38pub fn encode_bool(boolean: bool) -> Vec<u8> {
39    vec![if boolean {1} else {0}]
40}
41pub fn encode_ubyte(ubyte: u8) -> Vec<u8> {vec![ubyte]}
42pub fn encode_byte(byte: i8) -> Vec<u8> {vec![byte as u8]}
43pub fn encode_short(short: i16) -> Vec<u8> {vec![(short >> 8) as u8, short as u8]}
44pub fn encode_ushort(ushort: u16) -> Vec<u8> {
45    vec![(ushort >> 8) as u8, ushort as u8]
46}
47pub fn encode_int(int: i32) -> Vec<u8> {
48    vec![
49        (int >> 24) as u8,
50        (int >> 16) as u8,
51        (int >> 8) as u8,
52        int as u8,
53    ]
54}
55pub fn encode_uint(uint: u32) -> Vec<u8> {
56    vec![
57        (uint >> 24) as u8,
58        (uint >> 16) as u8,
59        (uint >> 8) as u8,
60        uint as u8,
61    ]
62}
63pub fn encode_long(long: i64) -> Vec<u8> {
64    vec![
65        (long >> 56) as u8,
66        (long >> 48) as u8,
67        (long >> 40) as u8,
68        (long >> 32) as u8,
69        (long >> 24) as u8,
70        (long >> 16) as u8,
71        (long >> 8) as u8,
72        long as u8,
73    ]
74}
75pub fn encode_uuid(uuid: u128) -> Vec<u8> {
76    let mut res = Vec::new();
77    for i in 0..16 {
78        res.push((uuid >> ((15 - i) * 8) ) as u8)
79    }
80    res
81}
82
83pub fn encode_float(float: f32) -> Vec<u8> {
84    encode_uint(float.to_bits())
85}
86pub fn encode_double(double: f64) -> Vec<u8> {
87    encode_long(double.to_bits() as i64)
88}
89
90pub fn read_var_int_from_stream(stream: &mut impl Read) -> Result<i32, Errors> {
91    let mut value: i32 = 0;
92    let mut buff: Vec<u8> = Vec::new();
93    buff.resize(1, 0);
94    let mut position = 0;
95    loop {
96        stream.read(&mut *buff).map_err(|e| Errors::IOError(e))?;
97        let byte = buff[0];
98        value |= ((byte & SEGMENT_BITS) as i32) << position;
99        if (byte & CONTINUE_BIT) == 0 {
100            return Ok(value);
101        }
102        position += 7;
103        if position >= 32 {
104            return Err(Errors::InvalidField("Invalid VarInt".into()));
105        }
106    }
107}
108pub fn encode_var_int(int: i32) -> Vec<u8> {
109    if int == 0 {
110        return vec![0];
111    }
112    let mut result = Vec::new();
113    let mut remaining = int;
114    loop {
115        let mut segment = (remaining as u8) & SEGMENT_BITS;
116        let cont = (segment as i32) != remaining;
117        if cont {
118            segment |= CONTINUE_BIT;
119        }
120        result.push(segment);
121        if !cont {
122            return result;
123        }
124        remaining >>= 7;
125    }
126}
127pub fn encode_var_long(long: i64) -> Vec<u8> {
128    if long == 0 {
129        return vec![0];
130    }
131    let mut result = Vec::new();
132    let mut remaining = long;
133    loop {
134        let mut segment = (remaining as u8) & SEGMENT_BITS;
135        let cont = (segment as i64) != remaining;
136        if cont {
137            segment |= CONTINUE_BIT;
138        }
139        result.push(segment);
140        if !cont {
141            return result;
142        }
143        remaining >>= 7;
144    }
145}
146pub fn var_int_size(var_int: i32) -> usize {
147    encode_var_int(var_int).len()
148}
149
150pub fn encode_string(string: String) -> Vec<u8> {
151    let mut bytes = string.into_bytes();
152    let mut res = encode_var_int(bytes.len() as i32);
153    res.append(&mut bytes);
154    res
155}
156pub fn encode_identifier(ident: String) -> Vec<u8> {
157    encode_string(ident)
158}
159pub fn encode_angle(angle: u8) -> Vec<u8> {encode_ubyte(angle)}
160pub fn encode_prefixed_array<T: Field>(array: &Vec<T>) -> Vec<u8> {
161    let mut res = encode_var_int(array.len() as i32);
162    res.append(&mut array.iter().flat_map(|e| e.to_bytes()).collect::<Vec<u8>>());
163    res
164}
165pub fn encode_prefixed_optional<T: Field + Clone>(optional: &Option<T>) -> Vec<u8> {
166    let mut res = encode_bool(optional.is_some());
167    match optional {
168        Some(v) => res.append(&mut T::to_bytes(v)),
169        None => (),
170    }
171    res
172}
173
174
175
176pub struct PacketReader {
177    data: Vec<u8>,
178    position: usize,
179}
180
181impl PacketReader {
182    pub fn get_rest(&self) -> Vec<u8> {
183        self.data[self.position..].into()
184    }
185}
186
187impl PacketReader {
188    pub fn read_bool(&mut self) -> Result<bool, Errors> {
189        match self.read_() {
190            0x00 => Ok(false),
191            0x01 => Ok(true),
192            val => Err(Errors::InvalidField(format!("boolean isn't 0x00 or 0x01 but {}", val))),
193        }
194    }
195    pub fn read_ubyte(&mut self) -> u8 { self.read_() }
196    pub fn read_byte(&mut self) -> i8 { self.read_() as i8 }
197    pub fn read_ushort(&mut self) -> u16 {
198        let arr: [u8; 2] = [self.read_(), self.read_()];
199        u16::from_be_bytes(arr)
200    }
201    pub fn read_short(&mut self) -> i16 {
202        i16::from_be_bytes([self.read_(), self.read_()])
203    }
204    pub fn read_uint(&mut self) -> u32 {
205        self.concat(4) as u32
206    }
207    pub fn read_int(&mut self) -> i32 {
208        let arr = self.read_n(4);
209        (arr[0] as i32) << 24 |
210            (arr[1] as i32) << 16 |
211            (arr[2] as i32) << 8 |
212            (arr[3] as i32)
213    }
214    pub fn read_long(&mut self) -> i64 {
215        let arr = self.read_n(8);
216        assert_eq!(arr.len(), 8);
217        let mut res = 0;
218        for i in 0..8 {
219            res |= (arr[i] as i64) << ((7 - i) * 8) 
220        }
221        res
222    }
223    pub fn read_uuid(&mut self) -> u128 {
224        self.concat(16)
225    }
226    
227    pub fn read_float(&mut self) -> f32 {f32::from_bits(self.read_uint())}
228    pub fn read_double(&mut self) -> f64 {
229        f64::from_bits(self.read_long() as u64)
230    }
231    
232    pub fn read_var_int(&mut self) -> Result<i32, Errors> {
233        let mut value: i32 = 0;
234        let mut position = 0;
235        loop {
236            let byte = self.read_();
237            value |= ((byte & SEGMENT_BITS) as i32) << position;
238            if (byte & CONTINUE_BIT) == 0 {
239                return Ok(value);
240            }
241            position += 7;
242            if position >= 32 {
243                return Err(Errors::InvalidField("Invalid VarInt".into()));
244            }
245        }
246    }
247    pub fn read_var_long(&mut self) -> Result<i64, Errors> {
248        let mut value: i64 = 0;
249        let mut position = 0;
250        loop {
251            let byte = self.read_();
252            value |= ((byte & SEGMENT_BITS) as i64) << position;
253            if (byte & CONTINUE_BIT) == 0 {
254                return Ok(value);
255            }
256            position += 7;
257            if position >= 64 {
258                return Err(Errors::InvalidField("Invalid VarInt".into()));
259            }
260        }
261    }
262    pub fn read_string(&mut self) -> Result<String, Errors> {
263        let length = self.read_var_int()?;
264        let data = self.read_n(length as usize);
265        let string = String::from_utf8(data)?;
266        println!("{}", string);
267        Ok(string)
268    }
269    pub fn read_identifier(&mut self) -> Result<String, Errors> {
270        self.read_string()
271    }
272    pub fn read_byte_array(&mut self, length: usize) -> Vec<u8> {
273        self.read_n(length)
274    }
275    pub fn read_rest(&mut self) -> Vec<u8> {
276        let res = self.data[self.position..].iter().cloned().collect();
277        self.position = self.data.len();
278        res
279    }
280    pub fn read_angle(&mut self) -> u8 {self.read_ubyte()}
281    pub fn read_prefixed_array<T: Field>(&mut self) -> Result<PrefixedArray<T>, Errors> {
282        let len = self.read_var_int()?;
283        let mut vector = Vec::new();
284        for _ in 0..len {
285            vector.push(T::from_reader(self)?);
286        }
287        Ok(vector)
288    }
289    pub fn read_prefixed_optional<T: Field>(&mut self) -> Result<Option<T>, Errors> {
290        let present = self.read_bool()?;
291        if present {
292            Ok(Some(T::from_reader(self)?))
293        } else {
294            Ok(None)
295        }
296    }
297    pub fn read<T: Field>(&mut self) -> Result<T, Errors> {
298        T::from_reader(self)
299    }
300}
301impl PacketReader {
302    fn read_(&mut self) -> u8 {
303        let value = self.data[self.position];
304        self.position += 1;
305        value
306    }
307    fn read_n(&mut self, n: usize) -> Vec<u8> {
308        let value: Vec<u8> = self.data[self.position..(self.position + n)].iter().cloned().collect();
309        self.position += n;
310        value
311    }
312    fn concat(&mut self, size: usize) -> u128 {
313        let mut result: u128 = 0;
314        for i in 0..size {
315            result |= (self.read_() as u128) << ((size - i - 1) * 8)
316        }
317        result
318    }
319}
320impl PacketReader {
321    pub fn total_len(&self) -> usize {
322        self.data.len()
323    }
324    pub fn len(&self) -> usize {
325        self.data.len() - self.position
326    }
327    pub fn new(data: Vec<u8>) -> Self {
328        Self {
329            data,
330            position: 0,
331        }
332    }
333}