valence 0.1.0+mc1.19.2

A framework for building Minecraft servers in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Packet definitions and related types.
//!
//! See <https://wiki.vg/Protocol> for more packet documentation.

#![macro_use]

use std::fmt;
use std::io::{Read, Write};

use anyhow::{bail, ensure, Context};
use bitvec::prelude::BitVec;
use num::{One, Zero};
use paste::paste;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use vek::Vec3;

// use {def_bitfield, def_enum, def_struct};
use crate::block_pos::BlockPos;
use crate::ident::Ident;
use crate::nbt::Compound;
use crate::protocol::{
    BoundedArray, BoundedInt, BoundedString, ByteAngle, Decode, Encode, NbtBridge, RawBytes,
    VarInt, VarLong,
};
use crate::text::Text;

/// Trait for types that can be written to the Minecraft protocol as a complete
/// packet.
///
/// A complete packet is one that starts with a `VarInt` packet ID, followed by
/// the body of the packet.
pub trait EncodePacket: fmt::Debug {
    /// Writes a packet to the Minecraft protocol, including its packet ID.
    fn encode_packet(&self, w: &mut impl Write) -> anyhow::Result<()>;
}

/// Trait for types that can be read from the Minecraft protocol as a complete
/// packet.
///
/// A complete packet is one that starts with a `VarInt` packet ID, followed by
/// the body of the packet.
pub trait DecodePacket: Sized + fmt::Debug {
    /// Reads a packet from the Minecraft protocol, including its packet ID.
    fn decode_packet(r: &mut impl Read) -> anyhow::Result<Self>;
}

/// Defines a struct which implements [`Encode`] and [`Decode`].
///
/// The fields of the struct are encoded and decoded in the order they are
/// defined.
macro_rules! def_struct {
    (
        $(#[$struct_attrs:meta])*
        $name:ident {
            $(
                $(#[$field_attrs:meta])*
                $field:ident: $typ:ty
            ),* $(,)?
        }
    ) => {
        #[derive(Clone, Debug)]
        $(#[$struct_attrs])*
        pub struct $name {
            $(
                $(#[$field_attrs])*
                pub $field: $typ,
            )*
        }

        impl Encode for $name {
            fn encode(&self, _w: &mut impl Write) -> anyhow::Result<()> {
                $(
                    Encode::encode(&self.$field, _w)
                        .context(concat!("failed to write field `", stringify!($field), "` from struct `", stringify!($name), "`"))?;
                )*
                Ok(())
            }
        }

        impl Decode for $name {
            fn decode(_r: &mut impl Read) -> anyhow::Result<Self> {
                $(
                    let $field: $typ = Decode::decode(_r)
                        .context(concat!("failed to read field `", stringify!($field), "` from struct `", stringify!($name), "`"))?;
                )*

                Ok(Self {
                    $(
                        $field,
                    )*
                })
            }
        }

        // TODO: https://github.com/rust-lang/rust/issues/48214
        //impl Copy for $name
        //where
        //    $(
        //        $typ: Copy
        //    )*
        //{}
    }
}

/// Defines an enum which implements [`Encode`] and [`Decode`].
///
/// The enum tag is encoded and decoded first, followed by the appropriate
/// variant.
macro_rules! def_enum {
    (
        $(#[$enum_attrs:meta])*
        $name:ident: $tag_ty:ty {
            $(
                $(#[$variant_attrs:meta])*
                $variant:ident$(: $typ:ty)? = $lit:literal
            ),* $(,)?
        }
    ) => {
        #[derive(Clone, Debug)]
        $(#[$enum_attrs])*
        pub enum $name {
            $(
                $(#[$variant_attrs])*
                $variant$(($typ))?,
            )*
        }

        impl Encode for $name {
            fn encode(&self, _w: &mut impl Write) -> anyhow::Result<()> {
                match self {
                    $(
                        if_typ_is_empty_pat!($($typ)?, $name::$variant, $name::$variant(val)) => {
                            <$tag_ty>::encode(&$lit.into(), _w)
                                .context(concat!("failed to write enum tag for `", stringify!($name), "`"))?;

                            if_typ_is_empty_expr!($($typ)?, Ok(()), {
                                Encode::encode(val, _w)
                                    .context(concat!("failed to write variant `", stringify!($variant), "` from enum `", stringify!($name), "`"))
                            })
                        },
                    )*

                    // Need this because references to uninhabited enums are considered inhabited.
                    #[allow(unreachable_patterns)]
                    _ => unreachable!("uninhabited enum?")
                }
            }
        }

        impl Decode for $name {
            fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
                let tag_ctx = concat!("failed to read enum tag for `", stringify!($name), "`");
                let tag = <$tag_ty>::decode(r).context(tag_ctx)?.into();
                match tag {
                    $(
                        $lit => {
                            if_typ_is_empty_expr!($($typ)?, Ok($name::$variant), {
                                $(
                                    let res: $typ = Decode::decode(r)
                                        .context(concat!("failed to read variant `", stringify!($variant), "` from enum `", stringify!($name), "`"))?;
                                    Ok($name::$variant(res))
                                )?
                            })
                        }
                    )*
                    _ => bail!(concat!("bad tag value for enum `", stringify!($name), "`"))
                }
            }
        }
    }
}

macro_rules! if_typ_is_empty_expr {
    (, $t:expr, $f:expr) => {
        $t
    };
    ($typ:ty, $t:expr, $f:expr) => {
        $f
    };
}

macro_rules! if_typ_is_empty_pat {
    (, $t:pat, $f:pat) => {
        $t
    };
    ($typ:ty, $t:pat, $f:pat) => {
        $f
    };
}

/// Defines a bitfield struct which implements [`Encode`] and [`Decode`].
macro_rules! def_bitfield {
    (
        $(#[$struct_attrs:meta])*
        $name:ident: $inner_ty:ty {
            $(
                $(#[$bit_attrs:meta])*
                $bit:ident = $offset:literal
            ),* $(,)?
        }
    ) => {
        #[derive(Clone, Copy, PartialEq, Eq)]
        $(#[$struct_attrs])*
        pub struct $name($inner_ty);

        impl $name {
            pub fn new(
                $(
                    $bit: bool,
                )*
            ) -> Self {
                let mut res = Self(Default::default());
                paste! {
                    $(
                        res = res.[<set_ $bit:snake>]($bit);
                    )*
                }
                res
            }

            paste! {
                $(
                    #[doc = "Gets the " $bit " bit on this bitfield.\n"]
                    $(#[$bit_attrs])*
                    pub fn $bit(self) -> bool {
                        self.0 & <$inner_ty>::one() << <$inner_ty>::from($offset) != <$inner_ty>::zero()
                    }

                    #[doc = "Sets the " $bit " bit on this bitfield.\n"]
                    $(#[$bit_attrs])*
                    #[must_use]
                    pub fn [<set_ $bit:snake>](self, $bit: bool) -> Self {
                        let mask = <$inner_ty>::one() << <$inner_ty>::from($offset);
                        if $bit {
                            Self(self.0 | mask)
                        } else {
                            Self(self.0 & !mask)
                        }
                    }
                )*
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let mut s = f.debug_struct(stringify!($name));
                paste! {
                    $(
                        s.field(stringify!($bit), &self. $bit());
                    )*
                }
                s.finish()
            }
        }

        impl Encode for $name {
            fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
                self.0.encode(w)
            }
        }

        impl Decode for $name {
            fn decode(r: &mut impl Read) -> anyhow::Result<Self> {
                <$inner_ty>::decode(r).map(Self)
            }
        }
    }
}

/// Defines an enum of packets.
///
/// An impl for [`EncodePacket`] and [`DecodePacket`] is defined for each
/// supplied packet.
macro_rules! def_packet_group {
    (
        $(#[$attrs:meta])*
        $group_name:ident {
            $($packet:ident = $id:literal),* $(,)?
        }
    ) => {
        #[derive(Clone)]
        $(#[$attrs])*
        pub enum $group_name {
            $($packet($packet)),*
        }

        $(
            impl From<$packet> for $group_name {
                fn from(p: $packet) -> Self {
                    Self::$packet(p)
                }
            }

            impl EncodePacket for $packet {
                fn encode_packet(&self, w: &mut impl Write) -> anyhow::Result<()> {
                    VarInt($id).encode(w).context("failed to write packet ID")?;
                    self.encode(w)
                }
            }

            impl DecodePacket for $packet {
                fn decode_packet(r: &mut impl Read) -> anyhow::Result<Self> {
                    let packet_id = VarInt::decode(r).context("failed to read packet ID")?.0;

                    ensure!(
                        $id == packet_id,
                        "bad packet ID (expected {}, got {packet_id}",
                        $id
                    );
                    Self::decode(r)
                }
            }
        )*

        impl DecodePacket for $group_name {
            fn decode_packet(r: &mut impl Read) -> anyhow::Result<Self> {
                let packet_id = VarInt::decode(r)
                    .context(concat!("failed to read ", stringify!($group_name), " packet ID"))?.0;

                match packet_id {
                    $(
                        $id => {
                            let pkt = $packet::decode(r)?;
                            Ok(Self::$packet(pkt))
                        }
                    )*
                    id => bail!(concat!("unknown ", stringify!($group_name), " packet ID {}"), id),
                }
            }
        }

        impl EncodePacket for $group_name {
            fn encode_packet(&self, w: &mut impl Write) -> anyhow::Result<()> {
                match self {
                    $(
                        Self::$packet(pkt) => {
                            VarInt($id)
                                .encode(w)
                                .context(concat!(
                                    "failed to write ",
                                    stringify!($group_name),
                                    " packet ID for ",
                                    stringify!($packet_name)
                                ))?;
                            pkt.encode(w)
                        }
                    )*
                }
            }
        }

        impl fmt::Debug for $group_name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let mut t = f.debug_tuple(stringify!($group_name));
                match self {
                    $(
                        Self::$packet(pkt) => t.field(pkt),
                    )*
                };
                t.finish()
            }
        }
    }
}

// Must be below the macro_rules!.
pub mod c2s;
pub mod s2c;

def_struct! {
    #[derive(PartialEq, Serialize, Deserialize)]
    Property {
        name: String,
        value: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        signature: Option<String>
    }
}

def_struct! {
    PublicKeyData {
        timestamp: u64,
        public_key: Vec<u8>,
        signature: Vec<u8>,
    }
}

#[cfg(test)]
pub(crate) mod test {
    use super::*;

    def_struct! {
        TestPacket {
            first: String,
            second: Vec<u16>,
            third: u64
        }
    }

    def_packet_group! {
        TestPacketGroup {
            TestPacket = 12345,
        }
    }
}