kojacoord_protocol/versions/v1_12_2/handshake/
mod.rs1use bytes::{Buf, BufMut, Bytes, BytesMut};
2
3use crate::codec::{Decode, Encode, PacketId};
4use crate::error::ProtocolError;
5use crate::types::VarInt;
6
7#[derive(Debug, Clone, PartialEq)]
8pub struct ServerboundHandshake {
9 pub protocol_version: VarInt,
10 pub server_address: String,
11 pub server_port: u16,
12 pub next_state: VarInt,
13}
14
15impl PacketId for ServerboundHandshake {
16 fn packet_id(_ver: u32) -> u8 {
17 0x00
18 }
19}
20
21impl Encode for ServerboundHandshake {
22 fn encode(&self, dst: &mut BytesMut) -> Result<(), ProtocolError> {
23 self.protocol_version.encode(dst)?;
24
25 let addr_bytes = self.server_address.as_bytes();
26 VarInt(addr_bytes.len() as i32).encode(dst)?;
27 dst.put_slice(addr_bytes);
28
29 dst.put_u16(self.server_port);
30 self.next_state.encode(dst)
31 }
32}
33
34impl Decode for ServerboundHandshake {
35 fn decode(src: &mut Bytes) -> Result<Self, ProtocolError> {
36 let protocol_version = VarInt::decode(src)?;
37 let addr_len = VarInt::decode(src)?.0 as usize;
38 if src.remaining() < addr_len {
39 return Err(ProtocolError::Io(std::io::Error::new(
40 std::io::ErrorKind::UnexpectedEof,
41 "Missing bytes while reading ServerboundHandshake address",
42 )));
43 }
44 let mut addr_bytes = vec![0u8; addr_len];
45 src.copy_to_slice(&mut addr_bytes);
46 let server_address = String::from_utf8(addr_bytes).map_err(|_| {
47 ProtocolError::Io(std::io::Error::new(
48 std::io::ErrorKind::InvalidData,
49 "Invalid UTF-8 string in ServerboundHandshake address",
50 ))
51 })?;
52
53 if src.remaining() < 2 {
54 return Err(ProtocolError::Io(std::io::Error::new(
55 std::io::ErrorKind::UnexpectedEof,
56 "Missing bytes for ServerboundHandshake port",
57 )));
58 }
59 let server_port = src.get_u16();
60
61 let next_state = VarInt::decode(src)?;
62
63 Ok(Self {
64 protocol_version,
65 server_address,
66 server_port,
67 next_state,
68 })
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75
76 #[test]
77 fn roundtrip() {
78 let p = ServerboundHandshake {
79 protocol_version: VarInt(340),
80 server_address: "localhost".to_string(),
81 server_port: 25565,
82 next_state: VarInt(2),
83 };
84 let mut buf = BytesMut::new();
85 p.encode(&mut buf).unwrap();
86 let mut b = buf.freeze();
87 assert_eq!(ServerboundHandshake::decode(&mut b).unwrap(), p);
88 }
89}