mcproto_types/lib.rs
1//! Minecraft protocol types and their wire-codec interface.
2//!
3//! The crate models protocol values and provides their encoding and decoding
4//! through [`TypeCodec`] and [`ContextualCodec`].
5
6pub mod basic;
7pub mod component;
8pub mod contextual;
9pub mod json_text_component;
10pub mod nbt;
11pub mod text_component;
12
13/// Encodes and decodes a value whose wire representation depends on external
14/// protocol context.
15///
16/// Unlike [`TypeCodec`], this trait receives a [`Context`](contextual::Context)
17/// supplied by the enclosing packet or data structure. The context itself is
18/// not written to or read from the wire. For an optional field, the caller must
19/// determine whether the field is present from the surrounding protocol data.
20///
21/// # Examples
22///
23/// A generic helper can encode any contextual value using context supplied by
24/// its enclosing packet:
25///
26/// ```
27/// use mcproto_codec::error::CodecError;
28/// use mcproto_types::{ContextualCodec, contextual::Context};
29///
30/// fn encode_contextual<T: ContextualCodec>(
31/// value: &T,
32/// context: &Context,
33/// ) -> Result<Vec<u8>, CodecError> {
34/// let mut encoded = Vec::new();
35/// value.encode_with_context(&mut encoded, context)?;
36/// Ok(encoded)
37/// }
38/// ```
39pub trait ContextualCodec {
40 /// Encodes this value using context supplied by its enclosing structure.
41 fn encode_with_context(
42 &self,
43 writer: &mut impl std::io::Write,
44 context: &contextual::Context,
45 ) -> Result<(), mcproto_codec::error::CodecError>;
46
47 /// Decodes this value using context supplied by its enclosing structure.
48 fn decode_with_context(
49 reader: &mut impl std::io::Read,
50 context: &contextual::Context,
51 ) -> Result<Self, mcproto_codec::error::CodecError>
52 where
53 Self: Sized;
54}
55
56/// Encodes and decodes a value with a context-independent wire representation.
57pub trait TypeCodec {
58 /// Encodes this value to the writer.
59 fn encode(
60 &self,
61 writer: &mut impl std::io::Write,
62 ) -> Result<(), mcproto_codec::error::CodecError>;
63
64 /// Decodes this value from the reader.
65 fn decode(reader: &mut impl std::io::Read) -> Result<Self, mcproto_codec::error::CodecError>
66 where
67 Self: Sized;
68}