Skip to content

Commit

Permalink
pumpkin-protocol: added codecs
Browse files Browse the repository at this point in the history
  • Loading branch information
Snowiiii committed Dec 21, 2024
1 parent 55e8cd6 commit 0633197
Show file tree
Hide file tree
Showing 61 changed files with 307 additions and 611 deletions.
24 changes: 12 additions & 12 deletions pumpkin-protocol/src/bytebuf/deserializer.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::fmt::Display;

use super::{ByteBuf, ReadingError};
use bytes::Bytes;
use bytes::Buf;
use serde::de::{self, DeserializeSeed, SeqAccess};

pub struct Deserializer<'a> {
inner: &'a mut Bytes,
pub struct Deserializer<'a, B: Buf> {
inner: &'a mut B,
}

impl de::Error for ReadingError {
Expand All @@ -14,13 +14,13 @@ impl de::Error for ReadingError {
}
}

impl<'a> Deserializer<'a> {
pub fn new(buf: &'a mut Bytes) -> Self {
impl<'a, B: Buf> Deserializer<'a, B> {
pub fn new(buf: &'a mut B) -> Self {
Self { inner: buf }
}
}

impl<'de> de::Deserializer<'de> for Deserializer<'_> {
impl<'de, B: Buf> de::Deserializer<'de> for Deserializer<'_, B> {
type Error = ReadingError;

fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
Expand Down Expand Up @@ -184,11 +184,11 @@ impl<'de> de::Deserializer<'de> for Deserializer<'_> {
where
V: de::Visitor<'de>,
{
struct Access<'a, 'b> {
deserializer: &'a mut Deserializer<'b>,
struct Access<'a, 'b, B: Buf> {
deserializer: &'a mut Deserializer<'b, B>,
}

impl<'de, 'a, 'b: 'a> SeqAccess<'de> for Access<'a, 'b> {
impl<'de, 'a, 'b: 'a, B: Buf> SeqAccess<'de> for Access<'a, 'b, B> {
type Error = ReadingError;

fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
Expand Down Expand Up @@ -216,12 +216,12 @@ impl<'de> de::Deserializer<'de> for Deserializer<'_> {
where
V: de::Visitor<'de>,
{
struct Access<'a, 'b> {
deserializer: &'a mut Deserializer<'b>,
struct Access<'a, 'b, B: Buf> {
deserializer: &'a mut Deserializer<'b, B>,
len: usize,
}

impl<'de, 'a, 'b: 'a> SeqAccess<'de> for Access<'a, 'b> {
impl<'de, 'a, 'b: 'a, B: Buf> SeqAccess<'de> for Access<'a, 'b, B> {
type Error = ReadingError;

fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
Expand Down
91 changes: 50 additions & 41 deletions pumpkin-protocol/src/bytebuf/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
use core::str;

use crate::{BitSet, FixedBitSet, VarInt, VarLong};
use crate::{
codec::{
bit_set::BitSet, identifier::Identifier, var_int::VarInt, var_long::VarLong, Codec,
DecodeError,
},
FixedBitSet,
};
use bytes::{Buf, BufMut};

mod deserializer;
Expand Down Expand Up @@ -54,9 +60,11 @@ pub trait ByteBuf: Buf {

fn try_get_var_long(&mut self) -> Result<VarLong, ReadingError>;

fn try_get_identifer(&mut self) -> Result<Identifier, ReadingError>;

fn try_get_string(&mut self) -> Result<String, ReadingError>;

fn try_get_string_len(&mut self, max_size: u32) -> Result<String, ReadingError>;
fn try_get_string_len(&mut self, max_size: usize) -> Result<String, ReadingError>;

/// Reads a boolean. If true, the closure is called, and the returned value is
/// wrapped in Some. Otherwise, this returns None.
Expand Down Expand Up @@ -181,41 +189,33 @@ impl<T: Buf> ByteBuf for T {
match VarInt::decode(self) {
Ok(var_int) => Ok(var_int),
Err(error) => match error {
crate::VarIntDecodeError::Incomplete => {
Err(ReadingError::Incomplete("varint".to_string()))
}
crate::VarIntDecodeError::TooLarge => {
Err(ReadingError::TooLarge("varint".to_string()))
}
DecodeError::Incomplete => Err(ReadingError::Incomplete("varint".to_string())),
DecodeError::TooLarge => Err(ReadingError::TooLarge("varint".to_string())),
},
}
}
fn try_get_var_long(&mut self) -> Result<VarLong, ReadingError> {
match VarLong::decode(self) {
Ok(var_long) => Ok(var_long),
Err(error) => match error {
crate::VarLongDecodeError::Incomplete => {
Err(ReadingError::Incomplete("varint".to_string()))
}
crate::VarLongDecodeError::TooLarge => {
Err(ReadingError::TooLarge("varlong".to_string()))
}
DecodeError::Incomplete => Err(ReadingError::Incomplete("varint".to_string())),
DecodeError::TooLarge => Err(ReadingError::TooLarge("varlong".to_string())),
},
}
}

fn try_get_string(&mut self) -> Result<String, ReadingError> {
self.try_get_string_len(i16::MAX as u32)
self.try_get_string_len(i16::MAX as usize)
}

fn try_get_string_len(&mut self, max_size: u32) -> Result<String, ReadingError> {
fn try_get_string_len(&mut self, max_size: usize) -> Result<String, ReadingError> {
let size = self.try_get_var_int()?.0;
if size as u32 > max_size {
if size as usize > max_size {
return Err(ReadingError::TooLarge("string".to_string()));
}

let data = self.try_copy_to_bytes(size as usize)?;
if data.len() as u32 > max_size {
if data.len() > max_size {
return Err(ReadingError::TooLarge("string".to_string()));
}
match str::from_utf8(&data) {
Expand Down Expand Up @@ -256,6 +256,16 @@ impl<T: Buf> ByteBuf for T {
fn try_get_fixed_bitset(&mut self, bits: usize) -> Result<FixedBitSet, ReadingError> {
self.try_copy_to_bytes(bits.div_ceil(8))
}

fn try_get_identifer(&mut self) -> Result<Identifier, ReadingError> {
match Identifier::decode(self) {
Ok(identifer) => Ok(identifer),
Err(error) => match error {
DecodeError::Incomplete => Err(ReadingError::Incomplete("identifer".to_string())),
DecodeError::TooLarge => Err(ReadingError::TooLarge("identifer".to_string())),
},
}
}
}

pub trait ByteBufMut {
Expand All @@ -265,7 +275,7 @@ pub trait ByteBufMut {

fn put_string(&mut self, val: &str);

fn put_string_len(&mut self, val: &str, max_size: u32);
fn put_string_len(&mut self, val: &str, max_size: usize);

fn put_string_array(&mut self, array: &[String]);

Expand All @@ -277,6 +287,8 @@ pub trait ByteBufMut {

fn put_list<G>(&mut self, list: &[G], write: impl Fn(&mut Self, &G));

fn put_identifier(&mut self, val: &Identifier);

fn put_var_int(&mut self, value: &VarInt);

fn put_varint_arr(&mut self, v: &[i32]);
Expand All @@ -299,11 +311,11 @@ impl<T: BufMut> ByteBufMut for T {
}

fn put_string(&mut self, val: &str) {
self.put_string_len(val, i16::MAX as u32);
self.put_string_len(val, i16::MAX as usize);
}

fn put_string_len(&mut self, val: &str, max_size: u32) {
if val.len() as u32 > max_size {
fn put_string_len(&mut self, val: &str, max_size: usize) {
if val.len() > max_size {
// Should be panic?, I mean its our fault
panic!("String is too big");
}
Expand All @@ -317,15 +329,12 @@ impl<T: BufMut> ByteBufMut for T {
}
}

fn put_var_int(&mut self, value: &VarInt) {
value.encode(self);
fn put_var_int(&mut self, var_int: &VarInt) {
var_int.encode(self);
}

fn put_bit_set(&mut self, set: &BitSet) {
self.put_var_int(&set.0);
for b in set.1 {
self.put_i64(*b);
}
fn put_bit_set(&mut self, bit_set: &BitSet) {
bit_set.encode(self);
}

fn put_option<G>(&mut self, val: &Option<G>, write: impl FnOnce(&mut Self, &G)) {
Expand All @@ -345,6 +354,10 @@ impl<T: BufMut> ByteBufMut for T {
fn put_varint_arr(&mut self, v: &[i32]) {
self.put_list(v, |p, &v| p.put_var_int(&v.into()))
}

fn put_identifier(&mut self, val: &Identifier) {
val.encode(self);
}
}

#[cfg(test)]
Expand All @@ -364,14 +377,12 @@ mod test {
bar: i32,
}
let foo = Foo { bar: 69 };
let mut serializer = serializer::Serializer::new(BytesMut::new());
let mut bytes = BytesMut::new();
let mut serializer = serializer::Serializer::new(&mut bytes);
foo.serialize(&mut serializer).unwrap();

let serialized: BytesMut = serializer.into();
let deserialized: Foo = Foo::deserialize(deserializer::Deserializer::new(
&mut Bytes::from(serialized),
))
.unwrap();
let deserialized: Foo =
Foo::deserialize(deserializer::Deserializer::new(&mut Bytes::from(bytes))).unwrap();

assert_eq!(foo, deserialized);
}
Expand All @@ -383,14 +394,12 @@ mod test {
bar: VarInt,
}
let foo = Foo { bar: 69.into() };
let mut serializer = serializer::Serializer::new(BytesMut::new());
let mut bytes = BytesMut::new();
let mut serializer = serializer::Serializer::new(&mut bytes);
foo.serialize(&mut serializer).unwrap();

let serialized: BytesMut = serializer.into();
let deserialized: Foo = Foo::deserialize(deserializer::Deserializer::new(
&mut Bytes::from(serialized),
))
.unwrap();
let deserialized: Foo =
Foo::deserialize(deserializer::Deserializer::new(&mut Bytes::from(bytes))).unwrap();

assert_eq!(foo, deserialized);
}
Expand Down
14 changes: 5 additions & 9 deletions pumpkin-protocol/src/bytebuf/packet_id.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use bytes::{BufMut, Bytes, BytesMut};
use bytes::{Buf, BufMut};
use serde::{de::DeserializeOwned, Serialize};

use crate::{ClientPacket, ServerPacket, VarIntType};
use crate::{codec::var_int::VarIntType, ClientPacket, ServerPacket};

use super::{deserializer, serializer, ReadingError};

Expand All @@ -13,22 +13,18 @@ impl<P> ClientPacket for P
where
P: Packet + Serialize,
{
fn write(&self, bytebuf: &mut BytesMut) {
let mut serializer = serializer::Serializer::new(BytesMut::new());
fn write(&self, bytebuf: &mut impl BufMut) {
let mut serializer = serializer::Serializer::new(bytebuf);
self.serialize(&mut serializer)
.expect("Could not serialize packet");
// We write the packet in an empty bytebuffer and then put it into our current one.
// In the future we may do packet batching thats the reason i don't let every packet create a new bytebuffer and use
// an existing instead
bytebuf.put(serializer.output);
}
}

impl<P> ServerPacket for P
where
P: Packet + DeserializeOwned,
{
fn read(bytebuf: &mut Bytes) -> Result<P, ReadingError> {
fn read(bytebuf: &mut impl Buf) -> Result<P, ReadingError> {
let deserializer = deserializer::Deserializer::new(bytebuf);
P::deserialize(deserializer)
}
Expand Down
Loading

0 comments on commit 0633197

Please sign in to comment.