Skip to main content

kojacoord_protocol/versions/v1_6_4/status/
mod.rs

1use bytes::{Buf, BufMut, Bytes, BytesMut};
2
3use crate::codec::{Decode, Encode, PacketId};
4use crate::error::ProtocolError;
5
6fn decode_legacy_string(src: &mut Bytes) -> Result<String, ProtocolError> {
7    if src.len() < 2 {
8        return Err(ProtocolError::UnexpectedEof);
9    }
10    let len = u16::from_be_bytes([src[0], src[1]]) as usize;
11    src.advance(2);
12    let byte_len = len * 2;
13    if src.len() < byte_len {
14        return Err(ProtocolError::UnexpectedEof);
15    }
16    let raw = src.copy_to_bytes(byte_len);
17    let chars: Vec<u16> = raw
18        .chunks(2)
19        .map(|c| u16::from_be_bytes([c[0], c[1]]))
20        .collect();
21    String::from_utf16(&chars).map_err(|_| ProtocolError::UnexpectedEof)
22}
23
24fn encode_legacy_string(s: &str, dst: &mut BytesMut) {
25    let utf16: Vec<u16> = s.encode_utf16().collect();
26    dst.extend_from_slice(&(utf16.len() as u16).to_be_bytes());
27    for ch in &utf16 {
28        dst.extend_from_slice(&ch.to_be_bytes());
29    }
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub struct ClientboundResponse {
34    pub response: String,
35}
36
37impl PacketId for ClientboundResponse {
38    fn packet_id(_ver: u32) -> u8 {
39        0x00
40    }
41}
42
43impl Encode for ClientboundResponse {
44    fn encode(&self, dst: &mut BytesMut) -> Result<(), ProtocolError> {
45        encode_legacy_string(&self.response, dst);
46        Ok(())
47    }
48}
49
50impl Decode for ClientboundResponse {
51    fn decode(src: &mut Bytes) -> Result<Self, ProtocolError> {
52        Ok(Self {
53            response: decode_legacy_string(src)?,
54        })
55    }
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub struct ClientboundPong {
60    pub payload: i64,
61}
62
63impl PacketId for ClientboundPong {
64    fn packet_id(_ver: u32) -> u8 {
65        0x01
66    }
67}
68
69impl Encode for ClientboundPong {
70    fn encode(&self, dst: &mut BytesMut) -> Result<(), ProtocolError> {
71        dst.put_i64(self.payload);
72        Ok(())
73    }
74}
75
76impl Decode for ClientboundPong {
77    fn decode(src: &mut Bytes) -> Result<Self, ProtocolError> {
78        Ok(Self {
79            payload: src.get_i64(),
80        })
81    }
82}