Potato/potato-protocol/build.rs
2025-03-05 12:21:53 +01:00

65 lines
1.8 KiB
Rust

use std::collections::HashMap;
const PACKETS_STR: &'static str = include_str!("packets.json");
fn main() {
println!("cargo::rerun-if-changed=packets.json");
let out_dir = std::env::var_os("OUT_DIR").unwrap();
let out_path = std::path::Path::new(&out_dir).join("ids.rs");
let packets: Packets = serde_json::from_str(PACKETS_STR).unwrap();
let out_string = &mut String::new();
write_phase("handshake", &packets.handshake, out_string);
write_phase("status", &packets.status, out_string);
write_phase("login", &packets.login, out_string);
write_phase("configuration", &packets.configuration, out_string);
write_phase("play", &packets.play, out_string);
std::fs::write(&out_path, out_string).unwrap();
}
fn write_phase(name: &str, phase: &Phase, out: &mut String) {
out.push_str(&format!("pub mod {} {{\n", name));
if let Some(packets) = &phase.clientbound {
write_side("clientbound", packets, out);
}
if let Some(packets) = &phase.serverbound {
write_side("serverbound", packets, out);
}
out.push_str("}\n");
}
fn write_side(side: &str, packets: &HashMap<String, Packet>, out: &mut String) {
out.push_str(&format!("pub mod {} {{\n", side.to_lowercase()));
for (name, packet) in packets {
out.push_str(&format!(
"pub const {}: i32 = 0x{:02X};\n",
name.replace("minecraft:", "").to_uppercase(),
packet.protocol_id
));
}
out.push_str("}\n");
}
#[derive(serde::Deserialize)]
struct Packets {
handshake: Phase,
status: Phase,
login: Phase,
configuration: Phase,
play: Phase,
}
#[derive(serde::Deserialize)]
struct Phase {
clientbound: Option<HashMap<String, Packet>>,
serverbound: Option<HashMap<String, Packet>>,
}
#[derive(serde::Deserialize)]
struct Packet {
protocol_id: i32,
}