yog_network/lib.rs
1//! Networking — mods' packets over named channels, as Yog Data.
2//!
3//! A packet's payload is bytes; a typed packet is any [`Schema`] type, sent
4//! and read the way everything else Yog sends is (`yog_data::to_bytes` /
5//! `read_bytes`). NBT is only ever built when something must be handed to
6//! the game itself.
7//!
8//! ```
9//! use yog_data::Schema;
10//! use yog_network::Packet;
11//!
12//! #[derive(Schema, Debug, PartialEq)]
13//! pub struct Teleport {
14//! x: f64,
15//! y: f64,
16//! z: f64,
17//! player: String,
18//! }
19//!
20//! let pkt = Teleport { x: 0.0, y: 64.0, z: 0.0, player: "Steve".into() };
21//! assert_eq!(Teleport::from_payload(&pkt.to_payload()), Some(pkt));
22//! ```
23
24use yog_data::Schema;
25
26/// A packet's payload as bytes and back — every [`Schema`] type is one.
27pub trait Packet: Sized {
28 fn to_payload(&self) -> Vec<u8>;
29 /// `None` for bytes that aren't this packet.
30 fn from_payload(bytes: &[u8]) -> Option<Self>;
31}
32
33impl<T: Schema> Packet for T {
34 fn to_payload(&self) -> Vec<u8> {
35 yog_data::to_bytes(self)
36 }
37
38 fn from_payload(bytes: &[u8]) -> Option<Self> {
39 yog_data::read_bytes(bytes).ok()
40 }
41}