azalea_protocol/packets/
mod.rs

1pub mod common;
2pub mod config;
3pub mod game;
4pub mod handshake;
5pub mod login;
6pub mod status;
7
8use std::io::{Cursor, Write};
9
10use azalea_buf::{AzaleaReadVar, AzaleaWrite, AzaleaWriteVar, BufReadError};
11
12use crate::read::ReadPacketError;
13
14pub const PROTOCOL_VERSION: i32 = 769;
15pub const VERSION_NAME: &str = "1.21.4";
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum ConnectionProtocol {
19    Handshake = -1,
20    Game = 0,
21    Status = 1,
22    Login = 2,
23    Configuration = 3,
24}
25
26impl ConnectionProtocol {
27    #[must_use]
28    pub fn from_i32(i: i32) -> Option<Self> {
29        match i {
30            -1 => Some(ConnectionProtocol::Handshake),
31            0 => Some(ConnectionProtocol::Game),
32            1 => Some(ConnectionProtocol::Status),
33            2 => Some(ConnectionProtocol::Login),
34            3 => Some(ConnectionProtocol::Configuration),
35            _ => None,
36        }
37    }
38}
39
40/// An enum of packets for a certain protocol.
41pub trait ProtocolPacket
42where
43    Self: Sized,
44{
45    fn id(&self) -> u32;
46
47    /// Returns Mojang's resource name for the packet.
48    ///
49    /// This doesn't include the "minecraft:" prefix, it just returns a string
50    /// like `pong`.
51    fn name(&self) -> &'static str;
52
53    /// Read a packet by its id, `ConnectionProtocol`, and flow
54    fn read(id: u32, buf: &mut Cursor<&[u8]>) -> Result<Self, Box<ReadPacketError>>;
55
56    fn write(&self, buf: &mut impl Write) -> Result<(), std::io::Error>;
57}
58
59pub trait Packet<Protocol> {
60    fn into_variant(self) -> Protocol;
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub enum ClientIntention {
65    Status = 1,
66    Login = 2,
67    Transfer = 3,
68}
69
70impl TryFrom<i32> for ClientIntention {
71    type Error = ();
72
73    fn try_from(value: i32) -> Result<Self, Self::Error> {
74        match value {
75            1 => Ok(ClientIntention::Status),
76            2 => Ok(ClientIntention::Login),
77            3 => Ok(ClientIntention::Transfer),
78            _ => Err(()),
79        }
80    }
81}
82
83impl From<ClientIntention> for ConnectionProtocol {
84    fn from(intention: ClientIntention) -> Self {
85        match intention {
86            ClientIntention::Status => ConnectionProtocol::Status,
87            ClientIntention::Login | ClientIntention::Transfer => ConnectionProtocol::Login,
88        }
89    }
90}
91
92impl azalea_buf::AzaleaRead for ClientIntention {
93    fn azalea_read(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
94        let id = i32::azalea_read_var(buf)?;
95        id.try_into()
96            .map_err(|_| BufReadError::UnexpectedEnumVariant { id })
97    }
98}
99
100impl AzaleaWrite for ClientIntention {
101    fn azalea_write(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
102        (*self as i32).azalea_write_var(buf)
103    }
104}