Refactor VarInt and VarLong

- Less duplicate code
- Cleaner Code :D
This commit is contained in:
Snowiiii committed 2024-12-10 16:17:53 +01:00
1 parent 33c5f4124a
commit bab92b39ca
6 files changed
+56 -132

No files matched your search

+25 -67
View File
@@ -1,15 +1,13 @@
use crate::{BitSet, FixedBitSet, VarInt, VarLongType};
use bytes::{Buf, BufMut, BytesMut};
use core::str; use core::str;
use crate::{BitSet, FixedBitSet, VarInt, VarLong};
use bytes::{Buf, BufMut, BytesMut};
mod deserializer; mod deserializer;
pub use deserializer::DeserializerError; pub use deserializer::DeserializerError;
pub mod packet_id; pub mod packet_id;
mod serializer; mod serializer;
const SEGMENT_BITS: u8 = 0x7F;
const CONTINUE_BIT: u8 = 0x80;
#[derive(Debug)] #[derive(Debug)]
pub struct ByteBuffer { pub struct ByteBuffer {
buffer: BytesMut, buffer: BytesMut,
@@ -26,49 +24,31 @@ impl ByteBuffer {
} }
pub fn get_var_int(&mut self) -> Result<VarInt, DeserializerError> { pub fn get_var_int(&mut self) -> Result<VarInt, DeserializerError> {
let mut value: i32 = 0; match VarInt::decode(&mut self.buffer) {
let mut position: i32 = 0; Ok(var_int) => Ok(var_int),
Err(error) => match error {
loop { crate::VarIntDecodeError::Incomplete => Err(DeserializerError::Message(
let read = self.get_u8()?; "VarInt is Incomplete".to_string(),
)),
value |= ((read & SEGMENT_BITS) as i32) << position; crate::VarIntDecodeError::TooLarge => {
Err(DeserializerError::Message("VarInt is too big".to_string()))
if read & CONTINUE_BIT == 0 { }
break; },
}
position += 7;
if position >= 32 {
return Err(DeserializerError::Message("VarInt is too big".to_string()));
}
} }
Ok(VarInt(value))
} }
pub fn get_var_long(&mut self) -> Result<VarLongType, DeserializerError> { pub fn get_var_long(&mut self) -> Result<VarLong, DeserializerError> {
let mut value: i64 = 0; match VarLong::decode(&mut self.buffer) {
let mut position: i64 = 0; Ok(var_long) => Ok(var_long),
Err(error) => match error {
loop { crate::VarLongDecodeError::Incomplete => Err(DeserializerError::Message(
let read = self.get_u8()?; "VarLong is Incomplete".to_string(),
)),
value |= ((read & SEGMENT_BITS) as i64) << position; crate::VarLongDecodeError::TooLarge => {
Err(DeserializerError::Message("VarLong is too big".to_string()))
if read & CONTINUE_BIT == 0 { }
break; },
}
position += 7;
if position >= 64 {
return Err(DeserializerError::Message("VarLong is too big".to_string()));
}
} }
Ok(value)
} }
pub fn get_string(&mut self) -> Result<String, DeserializerError> { pub fn get_string(&mut self) -> Result<String, DeserializerError> {
@@ -144,18 +124,7 @@ impl ByteBuffer {
} }
pub fn put_var_int(&mut self, value: &VarInt) { pub fn put_var_int(&mut self, value: &VarInt) {
let mut val = value.0; value.encode(&mut self.buffer);
for _ in 0..5 {
let mut b: u8 = val as u8 & 0b01111111;
val >>= 7;
if val != 0 {
b |= 0b10000000;
}
self.buffer.put_u8(b);
if val == 0 {
break;
}
}
} }
pub fn put_bit_set(&mut self, set: &BitSet) { pub fn put_bit_set(&mut self, set: &BitSet) {
@@ -209,17 +178,6 @@ impl ByteBuffer {
self.put_list(v, |p, &v| p.put_var_int(&v.into())) self.put_list(v, |p, &v| p.put_var_int(&v.into()))
} }
/* pub fn get_nbt(&mut self) -> Option<fastnbt::value::Value> {
match crab_nbt::NbtTag::deserialize(self.buf()) {
Ok(v) => Some(v),
Err(err) => None,
}
}
pub fn put_nbt(&mut self, nbt: N) {
self.buffer.put_slice(&nbt.serialize());
}
*/
pub fn buf(&mut self) -> &mut BytesMut { pub fn buf(&mut self) -> &mut BytesMut {
&mut self.buffer &mut self.buffer
} }
+1 -5
View File
@@ -209,7 +209,6 @@ mod tests {
use cfb8::cipher::AsyncStreamCipher; use cfb8::cipher::AsyncStreamCipher;
use cfb8::Encryptor as Cfb8Encryptor; use cfb8::Encryptor as Cfb8Encryptor;
use libdeflater::{CompressionLvl, Compressor}; use libdeflater::{CompressionLvl, Compressor};
use std::io::Cursor;
/// Helper function to compress data using libdeflater's Zlib compressor /// Helper function to compress data using libdeflater's Zlib compressor
fn compress_zlib(data: &[u8]) -> Vec<u8> { fn compress_zlib(data: &[u8]) -> Vec<u8> {
@@ -265,10 +264,7 @@ mod tests {
let packet_len_varint = VarInt(packet_len); let packet_len_varint = VarInt(packet_len);
let mut packet_length_encoded = Vec::new(); let mut packet_length_encoded = Vec::new();
{ {
let mut cursor = Cursor::new(&mut packet_length_encoded); packet_len_varint.encode(&mut packet_length_encoded);
packet_len_varint
.encode(&mut cursor)
.expect("VarInt encoding failed");
} }
// Create a new buffer for the entire packet // Create a new buffer for the entire packet
+8 -33
View File
@@ -1,5 +1,3 @@
use std::io::Write;
use aes::cipher::{generic_array::GenericArray, BlockEncryptMut, BlockSizeUser, KeyIvInit}; use aes::cipher::{generic_array::GenericArray, BlockEncryptMut, BlockSizeUser, KeyIvInit};
use bytes::{BufMut, BytesMut}; use bytes::{BufMut, BytesMut};
use pumpkin_config::compression::CompressionInfo; use pumpkin_config::compression::CompressionInfo;
@@ -39,17 +37,12 @@ impl Default for PacketEncoder {
impl PacketEncoder { impl PacketEncoder {
pub fn append_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketEncodeError> { pub fn append_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketEncodeError> {
let start_len = self.buf.len(); let start_len = self.buf.len();
let mut writer = (&mut self.buf).writer();
let mut packet_buf = ByteBuffer::empty(); let mut packet_buf = ByteBuffer::empty();
VarInt(P::PACKET_ID) VarInt(P::PACKET_ID).encode(&mut self.buf);
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeID)?;
packet.write(&mut packet_buf); packet.write(&mut packet_buf);
writer self.buf.put(packet_buf.buf());
.write(packet_buf.buf())
.map_err(|_| PacketEncodeError::EncodeFailedWrite)?;
let data_len = self.buf.len() - start_len; let data_len = self.buf.len() - start_len;
@@ -87,14 +80,8 @@ impl PacketEncoder {
self.buf.truncate(start_len); self.buf.truncate(start_len);
let mut writer = (&mut self.buf).writer(); VarInt(packet_len as i32).encode(&mut self.buf);
VarInt(data_len as i32).encode(&mut self.buf);
VarInt(packet_len as i32)
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeLength)?;
VarInt(data_len as i32)
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeData)?;
self.buf.extend_from_slice(&self.compress_buf); self.buf.extend_from_slice(&self.compress_buf);
} else { } else {
let data_len_size = 1; let data_len_size = 1;
@@ -114,13 +101,9 @@ impl PacketEncoder {
let mut front = &mut self.buf[start_len..]; let mut front = &mut self.buf[start_len..];
VarInt(packet_len as i32) VarInt(packet_len as i32).encode(&mut front);
.encode(&mut front)
.map_err(|_| PacketEncodeError::EncodeLength)?;
// Zero for no compression on this packet. // Zero for no compression on this packet.
VarInt(0) VarInt(0).encode(&mut front);
.encode(front)
.map_err(|_| PacketEncodeError::EncodeData)?;
} }
return Ok(()); return Ok(());
@@ -138,10 +121,8 @@ impl PacketEncoder {
self.buf self.buf
.copy_within(start_len..start_len + data_len, start_len + packet_len_size); .copy_within(start_len..start_len + data_len, start_len + packet_len_size);
let front = &mut self.buf[start_len..]; let mut front = &mut self.buf[start_len..];
VarInt(packet_len as i32) VarInt(packet_len as i32).encode(&mut front);
.encode(front)
.map_err(|_| PacketEncodeError::EncodeID)?;
Ok(()) Ok(())
} }
@@ -188,18 +169,12 @@ impl PacketEncoder {
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum PacketEncodeError { pub enum PacketEncodeError {
#[error("failed to encode packet ID")]
EncodeID,
#[error("failed to encode packet Length")]
EncodeLength,
#[error("failed to encode packet data")] #[error("failed to encode packet data")]
EncodeData, EncodeData,
#[error("failed to write encoded packet")] #[error("failed to write encoded packet")]
EncodeFailedWrite, EncodeFailedWrite,
#[error("packet exceeds maximum length")] #[error("packet exceeds maximum length")]
TooLong, TooLong,
#[error("invalid compression level")]
InvalidCompressionLevel,
#[error("compression failed")] #[error("compression failed")]
CompressionFailed, CompressionFailed,
} }
+13 -15
View File
@@ -1,6 +1,4 @@
use std::io::{self, Write}; use bytes::{Buf, BufMut};
use bytes::Buf;
use thiserror::Error; use thiserror::Error;
use crate::VarIntType; use crate::VarIntType;
@@ -22,7 +20,7 @@ impl VarInt {
} }
} }
pub fn decode_partial(r: &mut &[u8]) -> Result<i32, VarIntDecodeError> { pub fn decode_partial(r: &mut impl Buf) -> Result<i32, VarIntDecodeError> {
let mut val = 0; let mut val = 0;
for i in 0..Self::MAX_SIZE { for i in 0..Self::MAX_SIZE {
if !r.has_remaining() { if !r.has_remaining() {
@@ -34,25 +32,25 @@ impl VarInt {
return Ok(val); return Ok(val);
} }
} }
Err(VarIntDecodeError::TooLarge) Err(VarIntDecodeError::TooLarge)
} }
pub fn encode(&self, mut w: impl Write) -> Result<(), io::Error> { pub fn encode(&self, w: &mut impl BufMut) {
let mut x = self.0 as u64; let mut val = self.0;
loop { for _ in 0..Self::MAX_SIZE {
let byte = (x & 0x7F) as u8; let mut b: u8 = val as u8 & 0b01111111;
x >>= 7; val >>= 7;
if x == 0 { if val != 0 {
w.write_all(&[byte])?; b |= 0b10000000;
}
w.put_u8(b);
if val == 0 {
break; break;
} }
w.write_all(&[byte | 0x80])?;
} }
Ok(())
} }
pub fn decode(r: &mut &[u8]) -> Result<Self, VarIntDecodeError> { pub fn decode(r: &mut impl Buf) -> Result<Self, VarIntDecodeError> {
let mut val = 0; let mut val = 0;
for i in 0..Self::MAX_SIZE { for i in 0..Self::MAX_SIZE {
if !r.has_remaining() { if !r.has_remaining() {
+7 -10
View File
@@ -1,6 +1,4 @@
use std::io::{self, Write}; use bytes::{Buf, BufMut};
use bytes::Buf;
use thiserror::Error; use thiserror::Error;
use crate::VarLongType; use crate::VarLongType;
@@ -22,21 +20,20 @@ impl VarLong {
} }
} }
pub fn encode(&self, mut w: impl Write) -> Result<(), io::Error> { pub fn encode(&self, w: &mut impl BufMut) {
let mut x = self.0 as u64; let mut x = self.0;
loop { for _ in 0..Self::MAX_SIZE {
let byte = (x & 0x7F) as u8; let byte = (x & 0x7F) as u8;
x >>= 7; x >>= 7;
if x == 0 { if x == 0 {
w.write_all(&[byte])?; w.put_slice(&[byte]);
break; break;
} }
w.write_all(&[byte | 0x80])?; w.put_slice(&[byte | 0x80]);
} }
Ok(())
} }
pub fn decode(r: &mut &[u8]) -> Result<Self, VarLongDecodeError> { pub fn decode(r: &mut impl Buf) -> Result<Self, VarLongDecodeError> {
let mut val = 0; let mut val = 0;
for i in 0..Self::MAX_SIZE { for i in 0..Self::MAX_SIZE {
if !r.has_remaining() { if !r.has_remaining() {
+2 -2
View File
@@ -60,8 +60,8 @@ impl CachedBranding {
} }
fn build_brand() -> Vec<u8> { fn build_brand() -> Vec<u8> {
let brand = "Pumpkin"; let brand = "Pumpkin";
let mut buf = vec![]; let mut buf = Vec::new();
let _ = VarInt(brand.len() as i32).encode(&mut buf); VarInt(brand.len() as i32).encode(&mut buf);
buf.extend_from_slice(brand.as_bytes()); buf.extend_from_slice(brand.as_bytes());
buf buf
} }