Skip to content

Commit

Permalink
shorten compile times
Browse files Browse the repository at this point in the history
but only by a bit :c
  • Loading branch information
Snowiiii committed Jan 2, 2025
1 parent 4bfbff7 commit fa07af7
Show file tree
Hide file tree
Showing 34 changed files with 259 additions and 152 deletions.
4 changes: 0 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ debug = true
[workspace.dependencies]
log = "0.4"
tokio = { version = "1.42", features = [
"fs",
"io-util",
"macros",
"net",
"rt-multi-thread",
Expand All @@ -45,8 +43,6 @@ tokio = { version = "1.42", features = [
] }

thiserror = "2"
num-traits = "0.2"
num-derive = "0.4"

bytes = "1.9"

Expand Down
4 changes: 2 additions & 2 deletions pumpkin-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pumpkin-nbt = { path = "../pumpkin-nbt" }
serde.workspace = true
bytes.workspace = true
uuid.workspace = true
num-traits.workspace = true
num-derive.workspace = true

num-traits = "0.2"

colored = "2"
md5 = "0.7.0"
16 changes: 14 additions & 2 deletions pumpkin-core/src/gamemode.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use std::str::FromStr;

use num_derive::FromPrimitive;
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Eq)]
pub struct ParseGameModeError;

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, FromPrimitive)]
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[repr(i8)]
pub enum GameMode {
Undefined = -1,
Expand All @@ -16,6 +15,19 @@ pub enum GameMode {
Spectator,
}

impl From<i8> for GameMode {
fn from(value: i8) -> Self {
match value {
-1 => Self::Undefined,
0 => Self::Survival,
1 => Self::Creative,
2 => Self::Adventure,
3 => Self::Spectator,
_ => Self::Undefined,
}
}
}

impl FromStr for GameMode {
type Err = ParseGameModeError;

Expand Down
3 changes: 1 addition & 2 deletions pumpkin-core/src/permission.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use num_derive::{FromPrimitive, ToPrimitive};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Represents the player's permission level
Expand All @@ -10,7 +9,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// - `Two`: `gamemaster`: Player or executor can use more commands and player can use command blocks.
/// - `Three`: `admin`: Player or executor can use commands related to multiplayer management.
/// - `Four`: `owner`: Player or executor can use all of the commands, including commands related to server management.
#[derive(FromPrimitive, ToPrimitive, Clone, Copy, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Default, PartialEq, Eq)]
#[repr(i8)]
pub enum PermissionLvl {
#[default]
Expand Down
2 changes: 0 additions & 2 deletions pumpkin-inventory/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,3 @@ rayon.workspace = true
tokio.workspace = true
thiserror.workspace = true

num-traits.workspace = true
num-derive.workspace = true
10 changes: 6 additions & 4 deletions pumpkin-inventory/src/drag_handler.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::container_click::MouseDragType;
use crate::{Container, InventoryError};
use num_traits::Euclid;
use pumpkin_world::item::ItemStack;
use std::collections::HashMap;
use std::sync::Arc;
Expand Down Expand Up @@ -124,14 +123,17 @@ impl DragHandler {
// TODO: please work lol
(1, 0)
} else {
(carried_item.item_count as usize).div_rem_euclid(&amount_of_slots)
(
carried_item.item_count.div_euclid(amount_of_slots as u8),
carried_item.item_count.rem_euclid(amount_of_slots as u8),
)
};
let mut item_in_each_slot = *carried_item;
item_in_each_slot.item_count = amount_per_slot as u8;
item_in_each_slot.item_count = amount_per_slot;
changing_slots.for_each(|slot| *slots[slot] = Some(item_in_each_slot));

if remainder > 0 {
carried_item.item_count = remainder as u8;
carried_item.item_count = remainder;
} else {
*maybe_carried_item = None
}
Expand Down
3 changes: 1 addition & 2 deletions pumpkin-inventory/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::container_click::MouseClick;
use crate::player::PlayerInventory;
use num_derive::FromPrimitive;
use pumpkin_macros::screen;
use pumpkin_world::item::ItemStack;

Expand All @@ -15,7 +14,7 @@ pub mod window_property;
pub use error::InventoryError;
pub use open_container::*;

#[derive(Debug, FromPrimitive, Clone, Copy, Eq, PartialEq)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub enum WindowType {
// not used
Expand Down
23 changes: 7 additions & 16 deletions pumpkin-inventory/src/window_property.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
use num_derive::ToPrimitive;
use num_traits::ToPrimitive;

pub trait WindowPropertyTrait {
fn to_id(self) -> i16;
}

impl<T: ToPrimitive> WindowPropertyTrait for T {
fn to_id(self) -> i16 {
self.to_i16().unwrap()
}
}

pub struct WindowProperty<T: WindowPropertyTrait> {
window_property: T,
value: i16,
Expand All @@ -28,7 +19,7 @@ impl<T: WindowPropertyTrait> WindowProperty<T> {
(self.window_property.to_id(), self.value)
}
}
#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Furnace {
FireIcon,
MaximumFuelBurnTime,
Expand All @@ -55,35 +46,35 @@ impl WindowPropertyTrait for EnchantmentTable {
}) as i16
}
}
#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Beacon {
PowerLevel,
FirstPotionEffect,
SecondPotionEffect,
}

#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Anvil {
RepairCost,
}

#[derive(ToPrimitive)]
#[repr(u8)]
pub enum BrewingStand {
BrewTime,
FuelTime,
}

#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Stonecutter {
SelectedRecipe,
}

#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Loom {
SelectedPattern,
}

#[derive(ToPrimitive)]
#[repr(u8)]
pub enum Lectern {
PageNumber,
}
2 changes: 0 additions & 2 deletions pumpkin-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ serde.workspace = true
thiserror.workspace = true
log.workspace = true
tokio.workspace = true
num-traits.workspace = true
num-derive.workspace = true
bytes.workspace = true

# encryption
Expand Down
5 changes: 1 addition & 4 deletions pumpkin-protocol/src/bytebuf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,7 @@ impl<T: Buf> ByteBuf for T {
if data.len() > max_size {
return Err(ReadingError::TooLarge("string".to_string()));
}
match str::from_utf8(&data) {
Ok(string_result) => Ok(string_result.to_string()),
Err(e) => Err(ReadingError::Message(e.to_string())),
}
String::from_utf8(data.to_vec()).map_err(|e| ReadingError::Message(e.to_string()))
}

fn try_get_option<G>(
Expand Down
20 changes: 10 additions & 10 deletions pumpkin-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub mod server;
/// Don't forget to change this when porting
pub const CURRENT_MC_PROTOCOL: NonZeroU16 = unsafe { NonZeroU16::new_unchecked(769) };

pub const MAX_PACKET_SIZE: i32 = 2097152;
pub const MAX_PACKET_SIZE: usize = 2097152;

pub type FixedBitSet = bytes::Bytes;

Expand Down Expand Up @@ -49,18 +49,18 @@ pub enum ConnectionState {
Config,
Play,
}
pub struct InvalidConnectionState;

impl From<VarInt> for ConnectionState {
fn from(value: VarInt) -> Self {
impl TryFrom<VarInt> for ConnectionState {
type Error = InvalidConnectionState;

fn try_from(value: VarInt) -> Result<Self, Self::Error> {
let value = value.0;
match value {
1 => Self::Status,
2 => Self::Login,
3 => Self::Transfer,
_ => {
log::info!("Unexpected Status {}", value);
Self::Status
}
1 => Ok(Self::Status),
2 => Ok(Self::Login),
3 => Ok(Self::Transfer),
_ => Err(InvalidConnectionState),
}
}
}
Expand Down
18 changes: 3 additions & 15 deletions pumpkin-protocol/src/packet_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,14 @@ type Cipher = cfb8::Decryptor<aes::Aes128>;
// Decoder: Client -> Server
// Supports ZLib decoding/decompression
// Supports Aes128 Encryption
#[derive(Default)]
pub struct PacketDecoder {
buf: BytesMut,
decompress_buf: BytesMut,
cipher: Option<Cipher>,
decompressor: Option<Decompressor>,
}

// Manual implementation of Default trait for PacketDecoder
// Since decompressor does not implement Default
impl Default for PacketDecoder {
fn default() -> Self {
Self {
buf: BytesMut::new(),
decompress_buf: BytesMut::new(),
cipher: None,
decompressor: None,
}
}
}

impl PacketDecoder {
pub fn decode(&mut self) -> Result<Option<RawPacket>, PacketDecodeError> {
let mut r = &self.buf[..];
Expand All @@ -44,7 +32,7 @@ impl PacketDecoder {
};
let packet_len = packet_len.0;

if !(0..=MAX_PACKET_SIZE).contains(&packet_len) {
if !(0..=MAX_PACKET_SIZE as i32).contains(&packet_len) {
Err(PacketDecodeError::OutOfBounds)?
}

Expand All @@ -63,7 +51,7 @@ impl PacketDecoder {
.map_err(|_| PacketDecodeError::TooLong)?
.0;

if !(0..=MAX_PACKET_SIZE).contains(&data_len) {
if !(0..=MAX_PACKET_SIZE as i32).contains(&data_len) {
Err(PacketDecodeError::OutOfBounds)?
}

Expand Down
20 changes: 4 additions & 16 deletions pumpkin-protocol/src/packet_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Cipher = cfb8::Encryptor<aes::Aes128>;
/// Encoder: Server -> Client
/// Supports ZLib endecoding/compression
/// Supports Aes128 Encryption
#[derive(Default)]
pub struct PacketEncoder {
buf: BytesMut,
compress_buf: Vec<u8>,
Expand All @@ -21,19 +22,6 @@ pub struct PacketEncoder {
compression: Option<(Compressor, CompressionThreshold)>,
}

// Manual implementation of Default trait for PacketEncoder
// Since compressor does not implement Default
impl Default for PacketEncoder {
fn default() -> Self {
Self {
buf: BytesMut::with_capacity(1024),
compress_buf: Vec::with_capacity(1024),
cipher: None,
compression: None, // init compressor with fastest compression level
}
}
}

impl PacketEncoder {
/// Appends a Clientbound `ClientPacket` to the internal buffer and applies compression when needed.
///
Expand Down Expand Up @@ -99,7 +87,7 @@ impl PacketEncoder {

let packet_len = data_len_size + compressed_size;

if packet_len >= MAX_PACKET_SIZE as usize {
if packet_len >= MAX_PACKET_SIZE {
return Err(PacketEncodeError::TooLong(packet_len));
}

Expand All @@ -112,7 +100,7 @@ impl PacketEncoder {
let data_len_size = 1;
let packet_len = data_len_size + data_len;

if packet_len >= MAX_PACKET_SIZE as usize {
if packet_len >= MAX_PACKET_SIZE {
Err(PacketEncodeError::TooLong(packet_len))?
}

Expand All @@ -136,7 +124,7 @@ impl PacketEncoder {

let packet_len = data_len;

if packet_len >= MAX_PACKET_SIZE as usize {
if packet_len >= MAX_PACKET_SIZE {
Err(PacketEncodeError::TooLong(packet_len))?
}

Expand Down
21 changes: 16 additions & 5 deletions pumpkin-protocol/src/query.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use std::{ffi::CString, io::Cursor};

use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[derive(FromPrimitive)]
#[repr(u8)]
pub enum PacketType {
// There could be other types but they are not documented
Expand All @@ -13,6 +10,20 @@ pub enum PacketType {
Status = 0,
}

pub struct InvalidPacketType;

impl TryFrom<u8> for PacketType {
type Error = InvalidPacketType;

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
9 => Ok(Self::Handshake),
0 => Ok(Self::Status),
_ => Err(InvalidPacketType),
}
}
}

pub struct RawQueryPacket {
pub packet_type: PacketType,
reader: Cursor<Vec<u8>>,
Expand All @@ -27,8 +38,8 @@ impl RawQueryPacket {
// Since it denotes the protocol being used
// Should not attempt to decode packets with other magic values
65277 => Ok(Self {
packet_type: PacketType::from_u8(reader.read_u8().await.map_err(|_| ())?)
.ok_or(())?,
packet_type: PacketType::try_from(reader.read_u8().await.map_err(|_| ())?)
.map_err(|_| ())?,
reader,
}),
_ => Err(()),
Expand Down
Loading

0 comments on commit fa07af7

Please sign in to comment.