Alexander Medvedev 2025-11-27 17:31:39 +01:00
parent 2e4ffa96ba
commit 5e8d7221e3
7 changed files with 45 additions and 46 deletions

View File

@ -48,12 +48,13 @@ mod world_event;
pub const OUT_DIR: &str = "src/generated";
pub fn main() {
let path = Path::new(OUT_DIR);
if !path.exists() {
let _ = fs::create_dir(OUT_DIR);
if let Err(e) = fs::create_dir_all(OUT_DIR) {
eprintln!("Failed to create output directory {}: {}", OUT_DIR, e);
}
#[allow(clippy::type_complexity)]
let build_functions: Vec<(fn() -> TokenStream, &str)> = vec![
type BuilderFn = fn() -> TokenStream;
let build_functions: Vec<(BuilderFn, &str)> = vec![
(packet::build, "packet.rs"),
(screen::build, "screen.rs"),
(particle::build, "particle.rs"),
@ -97,22 +98,21 @@ pub fn main() {
];
build_functions.par_iter().for_each(|(build_fn, file)| {
let formatted_code = format_code(&build_fn().to_string());
write_generated_file(&formatted_code, file);
let raw_code = build_fn().to_string();
let final_code = format_code(&raw_code);
write_generated_file(&final_code.unwrap_or(raw_code), file);
});
}
pub fn array_to_tokenstream(array: &[String]) -> TokenStream {
let mut variants = TokenStream::new();
for item in array.iter() {
let variants = array.iter().map(|item| {
let name = format_ident!("{}", item.to_pascal_case());
variants.extend([quote! {
#name,
}]);
quote! { #name, }
});
quote! {
#(#variants)*
}
variants
}
pub fn write_generated_file(new_code: &str, out_file: &str) {
@ -122,39 +122,38 @@ pub fn write_generated_file(new_code: &str, out_file: &str) {
&& let Ok(existing_code) = fs::read_to_string(&path)
&& existing_code == new_code
{
return; // No changes, so we skip writing.
return;
}
fs::write(&path, new_code)
.unwrap_or_else(|_| panic!("Failed to write to file: {}", path.display()));
}
pub fn format_code(unformatted_code: &str) -> String {
let mut child = Command::new("rustfmt")
pub struct RustFmtError;
pub fn format_code(unformatted_code: &str) -> Result<String, RustFmtError> {
let child_result = Command::new("rustfmt")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("Failed to spawn rustfmt process.");
.stderr(Stdio::null())
.spawn();
child
.stdin
.take()
.expect("Failed to take rustfmt stdin")
.write_all(unformatted_code.as_bytes())
.expect("Failed to write to rustfmt stdin.");
let mut child = match child_result {
Ok(c) => c,
Err(_) => return Err(RustFmtError),
};
let output = child
.wait_with_output()
.expect("Failed to wait for rustfmt process.");
// Write the code to rustfmt's stdin
if let Some(mut stdin) = child.stdin.take()
&& stdin.write_all(unformatted_code.as_bytes()).is_err()
{
return Err(RustFmtError);
}
if output.status.success() {
String::from_utf8(output.stdout).expect("rustfmt output was not valid UTF-8.")
} else {
panic!(
"rustfmt failed with status: {}\n--- stderr ---\n{}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
match child.wait_with_output() {
Ok(output) if output.status.success() => {
String::from_utf8(output.stdout).map_err(|_| RustFmtError)
}
_ => Err(RustFmtError),
}
}

View File

@ -6,13 +6,13 @@ use std::io::{Error, Read, Write};
pub trait PacketWrite {
fn write<W: Write>(&self, writer: &mut W) -> Result<(), Error>;
fn write_be<W: Write>(&self, _writer: &mut W) -> Result<(), Error> {
panic!("not implemented")
todo!()
}
}
pub trait PacketRead: Sized {
fn read<R: Read>(reader: &mut R) -> Result<Self, Error>;
fn read_be<R: Read>(_reader: &mut R) -> Result<Self, Error> {
panic!("not implemented")
todo!()
}
}

View File

@ -54,7 +54,7 @@ pub async fn send_c_commands_packet(player: &Arc<Player>, dispatcher: &CommandDi
#[derive(Debug)]
struct ProtoNodeBuilder<'a> {
child_nodes: Vec<ProtoNodeBuilder<'a>>,
child_nodes: Vec<Self>,
node_type: ProtoNodeType<'a>,
}

View File

@ -73,7 +73,7 @@ impl NodeBuilder for LeafNodeBuilder {
pub struct NonLeafNodeBuilder {
node_type: NodeType,
child_nodes: Vec<NonLeafNodeBuilder>,
child_nodes: Vec<Self>,
leaf_nodes: Vec<LeafNodeBuilder>,
}

View File

@ -66,7 +66,7 @@ pub struct BedrockClient {
pub player: Mutex<Option<Arc<Player>>>,
/// All Bedrock clients
/// This list is used to remove the client if the connection gets closed
pub be_clients: Arc<Mutex<HashMap<SocketAddr, Arc<BedrockClient>>>>,
pub be_clients: Arc<Mutex<HashMap<SocketAddr, Arc<Self>>>>,
tasks: TaskTracker,
outgoing_packet_queue_send: Sender<Bytes>,

View File

@ -137,7 +137,7 @@ pub struct PluginManager {
handlers: Arc<RwLock<HandlerMap>>,
unloaded_files: RwLock<HashSet<PathBuf>>,
// Self-reference for sharing with contexts
self_ref: RwLock<Option<Arc<PluginManager>>>,
self_ref: RwLock<Option<Arc<Self>>>,
services: Arc<RwLock<HashMap<String, Arc<dyn Payload>>>>,
// Plugin state tracking
plugin_states: RwLock<HashMap<String, PluginState>>,

View File

@ -366,7 +366,7 @@ pub async fn spawn_category_for_position(
let mut random_group_size = (rng().random::<f32>() * 4.).ceil() as i32;
let mut inc = 0;
#[allow(unused_variables)]
let mut group_size = 0;
let group_size = 0;
'outer: while inc < random_group_size {
new_x += rng().random_range(0..6) - rng().random_range(0..6);
new_z += rng().random_range(0..6) - rng().random_range(0..6);
@ -419,7 +419,7 @@ pub async fn spawn_category_for_position(
// TODO isValidPositionForMob(level, mob, f)
// TODO spawnGroupData = mob.finalizeSpawn(level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.NATURAL, spawnGroupData);
spawn_cluster_size += 1;
group_size += 1;
//group_size += 1;
world.spawn_entity(entity).await;
spawn_state.after_spawn(entity_type, &new_pos, world).await;
if spawn_cluster_size >= entity_type.limit_per_chunk {