Refactor VarInt and VarLong

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

View File

@ -1,15 +1,13 @@
use crate::{BitSet, FixedBitSet, VarInt, VarLongType};
use bytes::{Buf, BufMut, BytesMut};
use core::str;
use crate::{BitSet, FixedBitSet, VarInt, VarLong};
use bytes::{Buf, BufMut, BytesMut};
mod deserializer;
pub use deserializer::DeserializerError;
pub mod packet_id;
mod serializer;
const SEGMENT_BITS: u8 = 0x7F;
const CONTINUE_BIT: u8 = 0x80;
#[derive(Debug)]
pub struct ByteBuffer {
buffer: BytesMut,
@ -26,49 +24,31 @@ impl ByteBuffer {
}
pub fn get_var_int(&mut self) -> Result<VarInt, DeserializerError> {
let mut value: i32 = 0;
let mut position: i32 = 0;
loop {
let read = self.get_u8()?;
value |= ((read & SEGMENT_BITS) as i32) << position;
if read & CONTINUE_BIT == 0 {
break;
}
position += 7;
if position >= 32 {
return Err(DeserializerError::Message("VarInt is too big".to_string()));
}
match VarInt::decode(&mut self.buffer) {
Ok(var_int) => Ok(var_int),
Err(error) => match error {
crate::VarIntDecodeError::Incomplete => Err(DeserializerError::Message(
"VarInt is Incomplete".to_string(),
)),
crate::VarIntDecodeError::TooLarge => {
Err(DeserializerError::Message("VarInt is too big".to_string()))
}
},
}
Ok(VarInt(value))
}
pub fn get_var_long(&mut self) -> Result<VarLongType, DeserializerError> {
let mut value: i64 = 0;
let mut position: i64 = 0;
loop {
let read = self.get_u8()?;
value |= ((read & SEGMENT_BITS) as i64) << position;
if read & CONTINUE_BIT == 0 {
break;
}
position += 7;
if position >= 64 {
return Err(DeserializerError::Message("VarLong is too big".to_string()));
}
pub fn get_var_long(&mut self) -> Result<VarLong, DeserializerError> {
match VarLong::decode(&mut self.buffer) {
Ok(var_long) => Ok(var_long),
Err(error) => match error {
crate::VarLongDecodeError::Incomplete => Err(DeserializerError::Message(
"VarLong is Incomplete".to_string(),
)),
crate::VarLongDecodeError::TooLarge => {
Err(DeserializerError::Message("VarLong is too big".to_string()))
}
},
}
Ok(value)
}
pub fn get_string(&mut self) -> Result<String, DeserializerError> {
@ -144,18 +124,7 @@ impl ByteBuffer {
}
pub fn put_var_int(&mut self, value: &VarInt) {
let mut val = value.0;
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;
}
}
value.encode(&mut self.buffer);
}
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()))
}
/* 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 {
&mut self.buffer
}

View File

@ -209,7 +209,6 @@ mod tests {
use cfb8::cipher::AsyncStreamCipher;
use cfb8::Encryptor as Cfb8Encryptor;
use libdeflater::{CompressionLvl, Compressor};
use std::io::Cursor;
/// Helper function to compress data using libdeflater's Zlib compressor
fn compress_zlib(data: &[u8]) -> Vec<u8> {
@ -265,10 +264,7 @@ mod tests {
let packet_len_varint = VarInt(packet_len);
let mut packet_length_encoded = Vec::new();
{
let mut cursor = Cursor::new(&mut packet_length_encoded);
packet_len_varint
.encode(&mut cursor)
.expect("VarInt encoding failed");
packet_len_varint.encode(&mut packet_length_encoded);
}
// Create a new buffer for the entire packet

View File

@ -1,5 +1,3 @@
use std::io::Write;
use aes::cipher::{generic_array::GenericArray, BlockEncryptMut, BlockSizeUser, KeyIvInit};
use bytes::{BufMut, BytesMut};
use pumpkin_config::compression::CompressionInfo;
@ -39,17 +37,12 @@ impl Default for PacketEncoder {
impl PacketEncoder {
pub fn append_packet<P: ClientPacket>(&mut self, packet: &P) -> Result<(), PacketEncodeError> {
let start_len = self.buf.len();
let mut writer = (&mut self.buf).writer();
let mut packet_buf = ByteBuffer::empty();
VarInt(P::PACKET_ID)
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeID)?;
VarInt(P::PACKET_ID).encode(&mut self.buf);
packet.write(&mut packet_buf);
writer
.write(packet_buf.buf())
.map_err(|_| PacketEncodeError::EncodeFailedWrite)?;
self.buf.put(packet_buf.buf());
let data_len = self.buf.len() - start_len;
@ -87,14 +80,8 @@ impl PacketEncoder {
self.buf.truncate(start_len);
let mut writer = (&mut self.buf).writer();
VarInt(packet_len as i32)
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeLength)?;
VarInt(data_len as i32)
.encode(&mut writer)
.map_err(|_| PacketEncodeError::EncodeData)?;
VarInt(packet_len as i32).encode(&mut self.buf);
VarInt(data_len as i32).encode(&mut self.buf);
self.buf.extend_from_slice(&self.compress_buf);
} else {
let data_len_size = 1;
@ -114,13 +101,9 @@ impl PacketEncoder {
let mut front = &mut self.buf[start_len..];
VarInt(packet_len as i32)
.encode(&mut front)
.map_err(|_| PacketEncodeError::EncodeLength)?;
VarInt(packet_len as i32).encode(&mut front);
// Zero for no compression on this packet.
VarInt(0)
.encode(front)
.map_err(|_| PacketEncodeError::EncodeData)?;
VarInt(0).encode(&mut front);
}
return Ok(());
@ -138,10 +121,8 @@ impl PacketEncoder {
self.buf
.copy_within(start_len..start_len + data_len, start_len + packet_len_size);
let front = &mut self.buf[start_len..];
VarInt(packet_len as i32)
.encode(front)
.map_err(|_| PacketEncodeError::EncodeID)?;
let mut front = &mut self.buf[start_len..];
VarInt(packet_len as i32).encode(&mut front);
Ok(())
}
@ -188,18 +169,12 @@ impl PacketEncoder {
#[derive(Error, Debug)]
pub enum PacketEncodeError {
#[error("failed to encode packet ID")]
EncodeID,
#[error("failed to encode packet Length")]
EncodeLength,
#[error("failed to encode packet data")]
EncodeData,
#[error("failed to write encoded packet")]
EncodeFailedWrite,
#[error("packet exceeds maximum length")]
TooLong,
#[error("invalid compression level")]
InvalidCompressionLevel,
#[error("compression failed")]
CompressionFailed,
}

View File

@ -1,6 +1,4 @@
use std::io::{self, Write};
use bytes::Buf;
use bytes::{Buf, BufMut};
use thiserror::Error;
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;
for i in 0..Self::MAX_SIZE {
if !r.has_remaining() {
@ -34,25 +32,25 @@ impl VarInt {
return Ok(val);
}
}
Err(VarIntDecodeError::TooLarge)
}
pub fn encode(&self, mut w: impl Write) -> Result<(), io::Error> {
let mut x = self.0 as u64;
loop {
let byte = (x & 0x7F) as u8;
x >>= 7;
if x == 0 {
w.write_all(&[byte])?;
pub fn encode(&self, w: &mut impl BufMut) {
let mut val = self.0;
for _ in 0..Self::MAX_SIZE {
let mut b: u8 = val as u8 & 0b01111111;
val >>= 7;
if val != 0 {
b |= 0b10000000;
}
w.put_u8(b);
if val == 0 {
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;
for i in 0..Self::MAX_SIZE {
if !r.has_remaining() {

View File

@ -1,6 +1,4 @@
use std::io::{self, Write};
use bytes::Buf;
use bytes::{Buf, BufMut};
use thiserror::Error;
use crate::VarLongType;
@ -22,21 +20,20 @@ impl VarLong {
}
}
pub fn encode(&self, mut w: impl Write) -> Result<(), io::Error> {
let mut x = self.0 as u64;
loop {
pub fn encode(&self, w: &mut impl BufMut) {
let mut x = self.0;
for _ in 0..Self::MAX_SIZE {
let byte = (x & 0x7F) as u8;
x >>= 7;
if x == 0 {
w.write_all(&[byte])?;
w.put_slice(&[byte]);
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;
for i in 0..Self::MAX_SIZE {
if !r.has_remaining() {

View File

@ -60,8 +60,8 @@ impl CachedBranding {
}
fn build_brand() -> Vec<u8> {
let brand = "Pumpkin";
let mut buf = vec![];
let _ = VarInt(brand.len() as i32).encode(&mut buf);
let mut buf = Vec::new();
VarInt(brand.len() as i32).encode(&mut buf);
buf.extend_from_slice(brand.as_bytes());
buf
}