#packet-stream #packet #codec #websocket #tcp #minecraft #decoding

nightly no-std packetize

encode and decode your packet with stream channel

94 breaking releases

new 0.101.0 Dec 15, 2024
0.99.0 Nov 30, 2024
0.98.0 Nov 30, 2024
0.51.0 Jul 30, 2024

#797 in Encoding

Download history 141/week @ 2024-08-26 147/week @ 2024-09-16 101/week @ 2024-09-23 47/week @ 2024-09-30 196/week @ 2024-10-21 4/week @ 2024-10-28 3/week @ 2024-11-04 196/week @ 2024-11-25 57/week @ 2024-12-02 342/week @ 2024-12-09

595 downloads per month

MIT license

10KB
71 lines

packetize

  • Supports fast packet encoding and decoding for network packets.
  • Features packet framing with macros.
  • Designed for multiple packet formats (e.g., WebSocket, Minecraft, TCP)

#[packet_stream]
#[derive(Default)]
pub enum ConnectionState {
    #[default]
    HandShake(#[change_state_to(Idle)] HandShakeC2s),
    Idle(
        RoomListRequestC2s,
        RoomListResponseS2c<'_>,
        RoomJoinRequestC2s,
        RoomCreateRequestC2s,
        RoomJoinResponseS2c<'_>,
        RoomCreateResponseS2c<'_>,
        #[change_state_to(Conf)] RoomJoinedAckC2s,
    ),
    Conf(
        #[change_state_to(Disconnected)] DisconnectedConfS2c,
        ChatConfS2c,
        ChatConfC2s,
        GameStartS2c,
        #[change_state_to(Play)] GameStartAckC2s,
        LeaveRoomConfC2s,
        LeaveRoomConfS2c,
        #[change_state_to(Idle)] LeaveRoomConfAckS2c,
        #[change_state_to(Idle)] LeaveRoomConfAckC2s,
    ),
    Play(
        #[change_state_to(Disconnected)] DisconnectedPlayS2c,
        ChatPlayC2s,
        ChatPlayS2c,
        LeaveRoomPlayC2s,
        LeaveRoomPlayS2c,
        #[change_state_to(Idle)] LeaveRoomPlayAckS2c,
        #[change_state_to(Idle)] LeaveRoomPlayAckC2s,
    ),
    Disconnected,
}

use fastbuf::Buffer;
use packetize::ClientBoundPacketStream;
use packetize::{streaming_packets, Decode, Encode, SimplePacketStreamFormat};

#[streaming_packets]
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum PacketStreamState {
    #[default]
    HandShake(#[change_state_to(Login)] HandShakeS2c),
    Login(LoginRequestS2c, #[id(1)] LoginSuccessC2s),
    //...
}

#[derive(Encode, Decode)]
pub struct HandShakeS2c {
    protocol_version: i32,
}

#[derive(Encode, Decode)]
pub struct LoginRequestS2c {}

#[derive(Encode, Decode)]
pub struct LoginSuccessC2s {}

let buf = &mut Buffer::<100>::new();
let mut state = PacketStreamState::HandShake;
state
    .encode_client_bound_packet(
        &HandShakeS2c {
            protocol_version: 123,
        }
        .into(),
        buf,
        &mut SimplePacketStreamFormat,
    )
    .unwrap();
assert_eq!(state, PacketStreamState::Login);

Dependencies

~1.1–2MB
~39K SLoC