fix some typos

This commit is contained in:
Snowiiii
2024-12-11 16:15:31 +01:00
parent 874b116cac
commit 2ee2cc06dd
35 changed files with 102 additions and 137 deletions

View File

@@ -29,6 +29,8 @@ There are several ways you can contribute to Pumpkin:
The Documentation of Pumpkin can be found at <https://snowiiii.github.io/Pumpkin/>
**Tip: [typos](https://github.com/crate-ci/typos) is a great Project to detect and automatically fix typos
### Coding Guidelines
- **Working with Tokio and Rayon:**

View File

@@ -21,7 +21,7 @@ impl Default for CompressionConfig {
#[derive(Deserialize, Serialize, Clone)]
#[serde(default)]
/// We have this in a Seperate struct so we can use it outside of the Config
/// We have this in a Separate struct so we can use it outside of the Config
pub struct CompressionInfo {
/// The compression threshold used when compression is enabled
pub threshold: u32,

View File

@@ -254,7 +254,7 @@ mod tests {
-1992287231i32,
),
("求同存异", 847053876),
// This might look wierd because hebrew is text is right to left
// This might look weird because hebrew is text is right to left
("אבְּרֵאשִׁ֖ית בָּרָ֣א אֱלֹהִ֑ים אֵ֥ת הַשָּׁמַ֖יִם וְאֵ֥ת הָאָֽרֶץ:", 1372570871),
("संस्कृत-", 1748614838),
("minecraft:offset", -920384768i32),

View File

@@ -2,7 +2,7 @@ use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use super::Text;
use super::TextComponent;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(tag = "action", content = "contents", rename_all = "snake_case")]
@@ -28,6 +28,6 @@ pub enum HoverEvent<'a> {
kind: Option<Cow<'a, str>>,
/// Optional custom name for the entity
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<Text<'a>>,
name: Option<Box<TextComponent<'a>>>,
},
}

View File

@@ -14,11 +14,7 @@ pub mod color;
pub mod hover;
pub mod style;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct Text<'a>(pub Box<TextComponent<'a>>);
// Represents a Text component
/// Represents a Text component
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub struct TextComponent<'a> {
@@ -29,6 +25,7 @@ pub struct TextComponent<'a> {
/// Also has `ClickEvent
#[serde(flatten)]
pub style: Style<'a>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
/// Extra text components
pub extra: Vec<TextComponent<'a>>,
}
@@ -228,7 +225,7 @@ pub enum TextContent<'a> {
Translate {
translate: Cow<'a, str>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
with: Vec<Text<'a>>,
with: Vec<TextComponent<'a>>,
},
/// Displays the name of one or more entities found by a selector.
EntityNames {

View File

@@ -55,7 +55,7 @@ impl ser::Error for SerializerError {
// Enums are written as a varint of the index
// Structs are ignored
// Iterables' values are written in order, but NO information (e.g. size) about the
// iterable itself is written (list sizes should be a seperate field)
// iterable itself is written (list sizes should be a separate field)
impl ser::Serializer for &mut Serializer {
type Ok = ();
type Error = SerializerError;
@@ -137,7 +137,7 @@ impl ser::Serializer for &mut Serializer {
Ok(())
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
// here is where all arrays/list getting written, usally we prefix the length of every length with an var int. The problem is
// here is where all arrays/list getting written, usually we prefix the length of every length with an var int. The problem is
// that byte arrays also getting thrown in here, and we don't want to prefix them
Ok(self)
}

View File

@@ -69,10 +69,10 @@ impl ProtoNode<'_> {
name: _,
is_executable,
parser: _,
override_suggestion_type: override_suggestion_tpye,
override_suggestion_type,
} => {
let mut n = 2;
if override_suggestion_tpye.is_some() {
if override_suggestion_type.is_some() {
n |= Self::FLAG_HAS_SUGGESTION_TYPE
}
if is_executable {

View File

@@ -4,7 +4,7 @@ use pumpkin_macros::client_packet;
use crate::{ClientPacket, PositionFlag, VarInt};
#[client_packet("play:teleport_entity")]
pub struct CTeleportEntitiy<'a> {
pub struct CTeleportEntity<'a> {
entity_id: VarInt,
position: Vector3<f64>,
delta: Vector3<f64>,
@@ -14,7 +14,7 @@ pub struct CTeleportEntitiy<'a> {
on_ground: bool,
}
impl<'a> CTeleportEntitiy<'a> {
impl<'a> CTeleportEntity<'a> {
pub fn new(
entity_id: VarInt,
position: Vector3<f64>,
@@ -36,7 +36,7 @@ impl<'a> CTeleportEntitiy<'a> {
}
}
impl ClientPacket for CTeleportEntitiy<'_> {
impl ClientPacket for CTeleportEntity<'_> {
fn write(&self, bytebuf: &mut crate::bytebuf::ByteBuffer) {
bytebuf.put_var_int(&self.entity_id);
bytebuf.put_f64(self.position.x);

View File

@@ -22,7 +22,7 @@ pub const CURRENT_MC_PROTOCOL: u32 = 769;
pub const MAX_PACKET_SIZE: i32 = 2097152;
/// usally uses a namespace like "minecraft:thing"
/// usually uses a namespace like "minecraft:thing"
pub type Identifier = String;
pub type VarIntType = i32;
pub type VarLongType = i64;

View File

@@ -9,7 +9,7 @@ type Cipher = cfb8::Decryptor<aes::Aes128>;
// Decoder: Client -> Server
// Supports ZLib decoding/decompression
// Supports Aes128 Encyption
// Supports Aes128 Encryption
pub struct PacketDecoder {
buf: BytesMut,
decompress_buf: BytesMut,
@@ -135,7 +135,7 @@ impl PacketDecoder {
}
}
/// Sets ZLib Deompression
/// Sets ZLib Decompression
pub fn set_compression(&mut self, compression: bool) {
self.compression = compression;
}
@@ -183,10 +183,6 @@ impl PacketDecoder {
pub enum PacketDecodeError {
#[error("failed to decode packet ID")]
DecodeID,
#[error("failed to write into decoder: {0}")]
FailedWrite(String),
#[error("failed to flush decoder")]
FailedFinish,
#[error("packet exceeds maximum length")]
TooLong,
#[error("packet length is out of bounds")]

View File

@@ -11,7 +11,7 @@ type Cipher = cfb8::Encryptor<aes::Aes128>;
// Encoder: Server -> Client
// Supports ZLib endecoding/compression
// Supports Aes128 Encyption
// Supports Aes128 Encryption
pub struct PacketEncoder {
buf: BytesMut,
compress_buf: Vec<u8>,
@@ -65,7 +65,7 @@ impl PacketEncoder {
let compressed_size = self
.compressor
.zlib_compress(data_to_compress, &mut self.compress_buf)
.map_err(|_| PacketEncodeError::CompressionFailed)?;
.map_err(|e| PacketEncodeError::CompressionFailed(e.to_string()))?;
// Resize compress_buf to actual compressed size
self.compress_buf.resize(compressed_size, 0);
@@ -169,21 +169,10 @@ impl PacketEncoder {
#[derive(Error, Debug)]
pub enum PacketEncodeError {
#[error("failed to encode packet data")]
EncodeData,
#[error("failed to write encoded packet")]
EncodeFailedWrite,
#[error("packet exceeds maximum length")]
TooLong,
#[error("compression failed")]
CompressionFailed,
}
impl PacketEncodeError {
pub fn kickable(&self) -> bool {
// We no longer have a connection, so dont try to kick the player, just close
!matches!(self, Self::EncodeData | Self::EncodeFailedWrite)
}
#[error("compression failed {0}")]
CompressionFailed(String),
}
#[cfg(test)]

View File

@@ -24,7 +24,7 @@ impl RawQueryPacket {
match reader.read_u16().await.map_err(|_| ())? {
// Magic should always equal 65277
// Since it denotes the protocl being used
// 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(|_| ())?)
@@ -52,7 +52,7 @@ impl SHandshake {
#[derive(PartialEq, Debug)]
pub struct SStatusRequest {
pub session_id: i32,
pub challange_token: i32,
pub challenge_token: i32,
// Full status request and basic status request are pretty much similar
// So might as just use the same struct
pub is_full_request: bool,
@@ -62,7 +62,7 @@ impl SStatusRequest {
pub async fn decode(packet: &mut RawQueryPacket) -> Result<Self, ()> {
Ok(Self {
session_id: packet.reader.read_i32().await.map_err(|_| ())?,
challange_token: packet.reader.read_i32().await.map_err(|_| ())?,
challenge_token: packet.reader.read_i32().await.map_err(|_| ())?,
is_full_request: {
let mut buf = [0; 4];
@@ -74,7 +74,7 @@ impl SStatusRequest {
Ok(0) => false,
Ok(4) => true,
_ => {
// Just ingnore malformed packets or errors
// Just ignore malformed packets or errors
return Err(());
}
}
@@ -88,7 +88,7 @@ pub struct CHandshake {
// For simplicity use a number type
// Should be encoded as string here
// Will be converted in encoding
pub challange_token: i32,
pub challenge_token: i32,
}
impl CHandshake {
@@ -99,10 +99,10 @@ impl CHandshake {
buf.write_u8(9).await.unwrap();
// Session ID
buf.write_i32(self.session_id).await.unwrap();
// Challange token
// Challenge token
// Use CString to add null terminator and ensure no null bytes in the middle of data
// Unwrap here since there should be no errors with nulls in the middle of data
let token = CString::new(self.challange_token.to_string()).unwrap();
let token = CString::new(self.challenge_token.to_string()).unwrap();
buf.extend_from_slice(token.as_bytes_with_nul());
buf
@@ -249,7 +249,7 @@ async fn test_handshake_response() {
let packet = CHandshake {
session_id: 1,
challange_token: 9513307,
challenge_token: 9513307,
};
assert_eq!(bytes, packet.encode().await)
@@ -265,7 +265,7 @@ async fn test_basic_stat_request() {
let actual_packet = SStatusRequest {
session_id: 1,
challange_token: 9513307,
challenge_token: 9513307,
is_full_request: false,
};
@@ -304,7 +304,7 @@ async fn test_full_stat_request() {
let actual_packet = SStatusRequest {
session_id: 1,
challange_token: 9513307,
challenge_token: 9513307,
is_full_request: true,
};

View File

@@ -146,11 +146,10 @@ impl Registry {
.wolf_variant
.iter()
.map(|s| {
// I present to you, A ugly hack which is done because Mojang developers decited to put is_<biome> instead of just <biome> on 3 wolf varients while all others have just the biome, this causes the client to not find the biome and disconnect
let varient = s.1.clone();
let variant = s.1.clone();
RegistryEntry {
entry_id: s.0,
data: pumpkin_nbt::serializer::to_bytes_unnamed(&varient).unwrap(),
data: pumpkin_nbt::serializer::to_bytes_unnamed(&variant).unwrap(),
}
})
.collect();

View File

@@ -273,22 +273,22 @@ impl ChunkData {
Some(d) => d,
};
// How many bits each block has in one of the pallete u64s
// How many bits each block has in one of the palette u64s
let block_bit_size = {
let size = 64 - (palette.len() as i64 - 1).leading_zeros();
max(4, size)
};
// How many blocks there are in one of the palletes u64s
let blocks_in_pallete = 64 / block_bit_size;
// How many blocks there are in one of the palettes u64s
let blocks_in_palette = 64 / block_bit_size;
let mask = (1 << block_bit_size) - 1;
'block_loop: for block in block_data.iter() {
for i in 0..blocks_in_pallete {
for i in 0..blocks_in_palette {
let index = (block >> (i * block_bit_size)) & mask;
let block = &palette[index as usize];
// TODO allow indexing blocks directly so we can just use block_index and save some time?
// this is fine because we initalized the heightmap of `blocks`
// this is fine because we initialized the heightmap of `blocks`
// from the cached value in the world file
blocks.set_block_no_heightmap_update(
ChunkRelativeBlockCoordinates {
@@ -301,7 +301,7 @@ impl ChunkData {
block_index += 1;
// if `SUBCHUNK_VOLUME `is not divisible by `blocks_in_pallete` the block_data
// if `SUBCHUNK_VOLUME `is not divisible by `blocks_in_palette` the block_data
// can sometimes spill into other subchunks. We avoid that by aborting early
if (block_index % SUBCHUNK_VOLUME) == 0 {
break 'block_loop;

View File

@@ -271,7 +271,7 @@ impl BaseRouter {
.clone()
.min(ConstantFunction::new(5f64).mul(CAVES_ENTRANCES_OVERWORLD.clone()));
let mapped_cave_entraces_overworld = RangeFunction::<
let mapped_cave_entrances_overworld = RangeFunction::<
NoEnvironment,
SharedComponentReference,
SharedComponentReference,
@@ -286,7 +286,7 @@ impl BaseRouter {
let blended_cave_entrances_overworld = apply_blend_density(apply_surface_slides(
amplified,
mapped_cave_entraces_overworld.into(),
mapped_cave_entrances_overworld.into(),
))
.min(CAVES_NOODLE_OVERWORLD.clone());

View File

@@ -120,7 +120,7 @@ impl ProtoChunk {
let horizontal_cell_block_count = self.sampler.horizontal_cell_block_count();
let vertical_cell_block_count = self.sampler.vertical_cell_block_count();
let horizonal_cells = CHUNK_DIM / horizontal_cell_block_count;
let horizontal_cells = CHUNK_DIM / horizontal_cell_block_count;
let min_y = self.sampler.min_y();
let minimum_cell_y = min_y / vertical_cell_block_count as i8;
@@ -133,10 +133,10 @@ impl ProtoChunk {
// - All unsafe functions are encapsulated and no mutable references are leaked
unsafe {
self.sampler.sample_start_density();
for cell_x in 0..horizonal_cells {
for cell_x in 0..horizontal_cells {
self.sampler.sample_end_density(cell_x);
for cell_z in 0..horizonal_cells {
for cell_z in 0..horizontal_cells {
for cell_y in (0..cell_height).rev() {
self.sampler.on_sampled_cell_corners(cell_y, cell_z);
for local_y in (0..vertical_cell_block_count).rev() {

View File

@@ -314,15 +314,9 @@ impl Player {
let find_condition = |(slot_number, slot): (usize, &mut Option<ItemStack>)| {
// TODO: Check for max item count here
match slot {
Some(item) => {
if item.item_id == item_in_pressed_slot.item_id
&& item.item_count != 64
{
Some(slot_number)
} else {
None
}
}
Some(item) => (item.item_id == item_in_pressed_slot.item_id
&& item.item_count != 64)
.then_some(slot_number),
None => Some(slot_number),
}
};
@@ -496,11 +490,7 @@ impl Player {
None
} else {
let entity_id = player.entity_id();
if player_ids.contains(&entity_id) {
Some(player.clone())
} else {
None
}
player_ids.contains(&entity_id).then(|| player.clone())
}
})
.collect_vec();
@@ -560,13 +550,11 @@ impl Player {
let slots = inventory.slots_with_hotbar_first();
let matching_slots = slots.filter_map(|slot| {
if let Some(item_slot) = slot.as_ref() {
if item_slot.item_id == item.id && item_slot.item_count < max_stack {
if let Some(item_slot) = slot.as_mut() {
(item_slot.item_id == item.id && item_slot.item_count < max_stack).then(|| {
let item_count = item_slot.item_count;
Some((slot, item_count))
} else {
None
}
(item_slot, item_count)
})
} else {
None
}
@@ -579,15 +567,15 @@ impl Player {
let amount_to_add = max_stack - item_count;
if let Some(amount_left) = amount.checked_sub(u32::from(amount_to_add)) {
amount = amount_left;
*slot = Some(ItemStack {
*slot = ItemStack {
item_id: item.id,
item_count: item.components.max_stack_size,
});
};
} else {
*slot = Some(ItemStack {
*slot = ItemStack {
item_id: item.id,
item_count: max_stack - (amount_to_add - amount as u8),
});
};
return;
}
}

View File

@@ -222,9 +222,7 @@ impl Client {
let mut enc = self.enc.lock().await;
if let Err(error) = enc.append_packet(packet) {
if error.kickable() {
self.kick(&error.to_string()).await;
}
self.kick(&error.to_string()).await;
return;
}
@@ -445,7 +443,6 @@ impl Client {
"Failed to handle client packet id {} in Login State",
packet.id.0
);
return Ok(());
}
};
Ok(())

View File

@@ -722,7 +722,7 @@ impl Player {
let block_bounding_box = BoundingBox::from_block(&world_pos);
let bounding_box = entity.bounding_box.load();
//TODO: Make this check for every entity in that posistion
//TODO: Make this check for every entity in that position
if !bounding_box.intersects(&block_bounding_box) {
world
.set_block_state(world_pos, block.default_state_id)

View File

@@ -14,7 +14,7 @@ use crate::server::Server;
use super::super::args::ArgumentConsumer;
use super::{Arg, DefaultNameArgConsumer, FindArg, GetClientSideArgParser};
/// todo: implement for entitites that aren't players
/// todo: implement for entities that aren't players
///
/// For selecting a single entity, eg. using @s, a player name or entity uuid.
///

View File

@@ -39,7 +39,7 @@ impl ArgumentConsumer for Position2DArgumentConsumer {
) -> Option<Arg<'a>> {
let pos = MaybeRelativePosition2D::try_new(args.pop()?, args.pop()?)?;
let vec2 = pos.try_to_abolute(src.position())?;
let vec2 = pos.try_to_absolute(src.position())?;
Some(Arg::Pos2D(vec2))
}
@@ -64,7 +64,7 @@ impl MaybeRelativePosition2D {
Some(Self(x.try_into().ok()?, z.try_into().ok()?))
}
fn try_to_abolute(self, origin: Option<Vector3<f64>>) -> Option<Vector2<f64>> {
fn try_to_absolute(self, origin: Option<Vector3<f64>>) -> Option<Vector2<f64>> {
Some(Vector2::new(
self.0.into_absolute(origin.map(|o| o.x))?,
self.1.into_absolute(origin.map(|o| o.z))?,

View File

@@ -32,7 +32,7 @@ pub(crate) mod arg_message;
pub(crate) mod arg_players;
pub(crate) mod arg_position_2d;
pub(crate) mod arg_position_3d;
pub(crate) mod arg_postition_block;
pub(crate) mod arg_position_block;
pub(crate) mod arg_resource_location;
pub(crate) mod arg_rotation;
pub(crate) mod arg_simple;
@@ -50,7 +50,7 @@ pub(crate) trait ArgumentConsumer: Sync + GetClientSideArgParser {
/// Used for tab completion (but only if argument suggestion type is "minecraft:ask_server"!).
///
/// NOTE: This is called after this consumer's [`ArgumentConsumer::consume`] method returnd None, so if args is used here, make sure [`ArgumentConsumer::consume`] never returns None after mutating args.
/// NOTE: This is called after this consumer's [`ArgumentConsumer::consume`] method returned None, so if args is used here, make sure [`ArgumentConsumer::consume`] never returns None after mutating args.
async fn suggest<'a>(
&self,
sender: &CommandSender<'a>,

View File

@@ -463,7 +463,7 @@ impl CommandExecutor for BossbarSetExecuter {
.bossbars
.lock()
.await
.update_visibilty(server, namespace.to_string(), visibility)
.update_visibility(server, namespace.to_string(), visibility)
.await
{
Ok(()) => {}

View File

@@ -1,5 +1,5 @@
use crate::command::args::arg_block::BlockArgumentConsumer;
use crate::command::args::arg_postition_block::BlockPosArgumentConsumer;
use crate::command::args::arg_position_block::BlockPosArgumentConsumer;
use crate::command::args::{ConsumedArgs, FindArg};
use crate::command::tree::CommandTree;
use crate::command::tree_builder::{argument, literal, require};

View File

@@ -3,7 +3,7 @@ use pumpkin_core::text::color::NamedColor;
use pumpkin_core::text::TextComponent;
use crate::command::args::arg_block::BlockArgumentConsumer;
use crate::command::args::arg_postition_block::BlockPosArgumentConsumer;
use crate::command::args::arg_position_block::BlockPosArgumentConsumer;
use crate::command::args::{ConsumedArgs, FindArg};
use crate::command::tree::CommandTree;
use crate::command::tree_builder::{argument, literal, require};

View File

@@ -70,7 +70,7 @@ impl<'a> CommandDispatcher<'a> {
}
Err(pumpkin_error) => {
pumpkin_error.log();
sender.send_message(TextComponent::text("Unknown internal error occured while running command. Please see server log").color(Color::Named(NamedColor::Red))).await;
sender.send_message(TextComponent::text("Unknown internal error occurred while running command. Please see server log").color(Color::Named(NamedColor::Red))).await;
}
}
}

View File

@@ -11,7 +11,7 @@ use pumpkin_core::math::{
};
use pumpkin_entity::{entity_type::EntityType, pose::EntityPose, EntityId};
use pumpkin_protocol::{
client::play::{CSetEntityMetadata, CTeleportEntitiy, Metadata},
client::play::{CSetEntityMetadata, CTeleportEntity, Metadata},
VarInt,
};
@@ -134,7 +134,7 @@ impl Entity {
pub async fn teleport(&self, position: Vector3<f64>, yaw: f32, pitch: f32) {
self.world
.broadcast_packet_all(&CTeleportEntitiy::new(
.broadcast_packet_all(&CTeleportEntity::new(
self.entity_id.into(),
position,
Vector3::new(0.0, 0.0, 0.0),

View File

@@ -86,7 +86,7 @@ pub struct Player {
/// The item currently being held by the player.
pub carried_item: AtomicCell<Option<ItemStack>>,
/// send `send_abilties_update` when changed
/// send `send_abilities_update` when changed
/// The player's abilities and special powers.
///
/// This field represents the various abilities that the player possesses, such as flight, invulnerability, and other special effects.
@@ -390,7 +390,7 @@ impl Player {
}
/// Updates the current abilities the Player has
pub async fn send_abilties_update(&self) {
pub async fn send_abilities_update(&self) {
let mut b = 0i8;
let abilities = &self.abilities.lock().await;

View File

@@ -2,6 +2,7 @@
#![deny(clippy::pedantic)]
// #![warn(clippy::restriction)]
#![deny(clippy::cargo)]
#![deny(clippy::if_then_some_else_none)]
// REMOVE SOME WHEN RELEASE
#![expect(clippy::cargo_common_metadata)]
#![expect(clippy::multiple_crate_versions)]

View File

@@ -34,7 +34,7 @@ pub enum VelocityError {
#[error("Failed to read address")]
FailedReadAddress,
#[error("Failed to parse address")]
FailedParseAddres,
FailedParseAddress,
#[error("Failed to read game profile name")]
FailedReadProfileName,
#[error("Failed to read game profile UUID")]
@@ -129,7 +129,7 @@ pub fn receive_velocity_plugin_response(
let socket_addr: SocketAddr = SocketAddr::new(
addr.parse::<IpAddr>()
.map_err(|_| VelocityError::FailedParseAddres)?,
.map_err(|_| VelocityError::FailedParseAddress)?,
port,
);
let profile = read_game_profile(&mut buf)?;

View File

@@ -27,16 +27,16 @@ pub async fn start_query_handler(server: Arc<Server>, bound_addr: SocketAddr) {
.expect("Unable to bind to address"),
);
// Challange tokens are bound to the IP address and port
let valid_challange_tokens = Arc::new(RwLock::new(HashMap::new()));
let valid_challange_tokens_clone = valid_challange_tokens.clone();
// All challange tokens ever created are expired every 30 seconds
// Challenge tokens are bound to the IP address and port
let valid_challenge_tokens = Arc::new(RwLock::new(HashMap::new()));
let valid_challenge_tokens_clone = valid_challenge_tokens.clone();
// All challenge tokens ever created are expired every 30 seconds
tokio::spawn(async move {
let mut interval = time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
valid_challange_tokens_clone.write().await.clear();
valid_challenge_tokens_clone.write().await.clear();
}
});
@@ -49,7 +49,7 @@ pub async fn start_query_handler(server: Arc<Server>, bound_addr: SocketAddr) {
loop {
let socket = socket.clone();
let valid_challange_tokens = valid_challange_tokens.clone();
let valid_challenge_tokens = valid_challenge_tokens.clone();
let server = server.clone();
let mut buf = vec![0; 1024];
let (_, addr) = socket.recv_from(&mut buf).await.unwrap();
@@ -57,7 +57,7 @@ pub async fn start_query_handler(server: Arc<Server>, bound_addr: SocketAddr) {
tokio::spawn(async move {
if let Err(err) = handle_packet(
buf,
valid_challange_tokens,
valid_challenge_tokens,
server,
socket,
addr,
@@ -87,10 +87,10 @@ async fn handle_packet(
match raw_packet.packet_type {
PacketType::Handshake => {
if let Ok(packet) = SHandshake::decode(&mut raw_packet).await {
let challange_token = rand::thread_rng().gen_range(1..=i32::MAX);
let challenge_token = rand::thread_rng().gen_range(1..=i32::MAX);
let response = CHandshake {
session_id: packet.session_id,
challange_token,
challenge_token,
};
// Ignore all errors since we don't want the query handler to crash
@@ -99,7 +99,7 @@ async fn handle_packet(
.send_to(response.encode().await.as_slice(), addr)
.await;
clients.write().await.insert(challange_token, addr);
clients.write().await.insert(challenge_token, addr);
}
}
PacketType::Status => {
@@ -107,7 +107,7 @@ async fn handle_packet(
if clients
.read()
.await
.get(&packet.challange_token)
.get(&packet.challenge_token)
.is_some_and(|token_bound_ip: &SocketAddr| token_bound_ip == &addr)
{
if packet.is_full_request {
@@ -150,7 +150,7 @@ async fn handle_packet(
.send_to(response.encode().await.as_slice(), addr)
.await;
} else {
let resposne = CBasicStatus {
let response = CBasicStatus {
session_id: packet.session_id,
motd: CString::new(BASIC_CONFIG.motd.as_str())?,
map: CString::new("world")?,
@@ -161,7 +161,7 @@ async fn handle_packet(
};
let _ = socket
.send_to(resposne.encode().await.as_slice(), addr)
.send_to(response.encode().await.as_slice(), addr)
.await;
}
}

View File

@@ -73,16 +73,12 @@ impl Server {
pub fn new() -> Self {
// TODO: only create when needed
let auth_client = if BASIC_CONFIG.online_mode {
Some(
reqwest::Client::builder()
.timeout(Duration::from_millis(5000))
.build()
.expect("Failed to to make reqwest client"),
)
} else {
None
};
let auth_client = BASIC_CONFIG.online_mode.then(|| {
reqwest::Client::builder()
.timeout(Duration::from_millis(5000))
.build()
.expect("Failed to to make reqwest client")
});
// First register default command, after that plugins can put in their own
let command_dispatcher = default_dispatcher();

View File

@@ -189,7 +189,7 @@ impl CustomBossbars {
))
}
pub async fn update_visibilty(
pub async fn update_visibility(
&mut self,
server: &Server,
resource_location: String,
@@ -365,7 +365,7 @@ impl CustomBossbars {
) -> Result<(), BossbarUpdateError> {
let bossbar = self.custom_bossbars.get_mut(&resource_location);
if let Some(bossbar) = bossbar {
// Get differnce between old and new player list and remove bossbars from old players
// Get difference between old and new player list and remove bossbars from old players
let removed_players: Vec<Uuid> = bossbar
.player
.iter()

View File

@@ -150,16 +150,16 @@ impl World {
&self,
sound_id: u16,
category: SoundCategory,
posistion: &Vector3<f64>,
position: &Vector3<f64>,
) {
let seed = thread_rng().gen::<f64>();
self.broadcast_packet_all(&CSoundEffect::new(
VarInt(i32::from(sound_id)),
None,
category,
posistion.x,
posistion.y,
posistion.z,
position.x,
position.y,
position.z,
1.0,
1.0,
seed,
@@ -442,7 +442,7 @@ impl World {
.await;
log::debug!("Sending player abilities to {}", player.gameprofile.name);
player.send_abilties_update().await;
player.send_abilities_update().await;
player.send_permission_lvl_update().await;