mcproto-types 0.3.0

Minecraft protocol types.
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Basic Minecraft protocol types and their wire encodings.
//!
//! This module includes primitive numeric values, booleans, variable-length
//! integers, length-prefixed strings, and resource identifiers.

use crate::TypeCodec;
use mcproto_codec::{
    error::{CodecError, CodecKind, CodecOperation, InvalidEncodingReason},
    io::{read_exact_counted, write_all_counted},
    varint::{VarIntRead, VarIntWrite},
    varlong::{VarLongRead, VarLongWrite},
};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
use std::{
    fmt,
    io::{Read, Write},
};

/// A boolean encoded as `0x00` for false or `0x01` for true.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Boolean(
    /// The boolean value.
    pub bool,
);

impl TypeCodec for Boolean {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        let byte = if self.0 { 1u8 } else { 0u8 };
        write_all_counted(writer, &[byte], CodecKind::Boolean, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError>
    where
        Self: Sized,
    {
        let mut buf = [0u8; 1];
        read_exact_counted(reader, &mut buf, CodecKind::Boolean, 0)?;
        match buf[0] {
            0 => Ok(Boolean(false)),
            1 => Ok(Boolean(true)),
            _ => Err(CodecError::invalid_encoding(
                CodecKind::Boolean,
                1,
                InvalidEncodingReason::InvalidBooleanValue { value: buf[0] },
            )),
        }
    }
}

/// A two's-complement signed 8-bit integer from -128 through 127.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Byte(
    /// The integer value.
    pub i8,
);

impl TypeCodec for Byte {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::Byte, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 1];
        read_exact_counted(reader, &mut bytes, CodecKind::Byte, 0)?;
        Ok(Self(i8::from_be_bytes(bytes)))
    }
}

/// An unsigned 8-bit integer from 0 through 255.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct UnsignedByte(
    /// The integer value.
    pub u8,
);

impl TypeCodec for UnsignedByte {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::UnsignedByte, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 1];
        read_exact_counted(reader, &mut bytes, CodecKind::UnsignedByte, 0)?;
        Ok(Self(u8::from_be_bytes(bytes)))
    }
}

/// A two's-complement signed 16-bit integer from -32,768 through 32,767.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Short(
    /// The integer value.
    pub i16,
);

impl TypeCodec for Short {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::Short, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 2];
        read_exact_counted(reader, &mut bytes, CodecKind::Short, 0)?;
        Ok(Self(i16::from_be_bytes(bytes)))
    }
}

/// An unsigned 16-bit integer from 0 through 65,535.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct UnsignedShort(
    /// The integer value.
    pub u16,
);

impl TypeCodec for UnsignedShort {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::UnsignedShort, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 2];
        read_exact_counted(reader, &mut bytes, CodecKind::UnsignedShort, 0)?;
        Ok(Self(u16::from_be_bytes(bytes)))
    }
}

/// A two's-complement signed 32-bit integer from -2,147,483,648 through
/// 2,147,483,647.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Int(
    /// The integer value.
    pub i32,
);

impl TypeCodec for Int {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::Int, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 4];
        read_exact_counted(reader, &mut bytes, CodecKind::Int, 0)?;
        Ok(Self(i32::from_be_bytes(bytes)))
    }
}

/// A two's-complement signed 64-bit integer from -9,223,372,036,854,775,808
/// through 9,223,372,036,854,775,807.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Long(
    /// The integer value.
    pub i64,
);

impl TypeCodec for Long {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        write_all_counted(writer, &self.0.to_be_bytes(), CodecKind::Long, 0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let mut bytes = [0; 8];
        read_exact_counted(reader, &mut bytes, CodecKind::Long, 0)?;
        Ok(Self(i64::from_be_bytes(bytes)))
    }
}

/// A UTF-8 string prefixed by its byte length as a VarInt.
///
/// The protocol limits both the UTF-8 payload size and the number of UTF-16
/// code units. Supplementary [Unicode scalar values] count as two UTF-16
/// code units. The general protocol limit is 32,767 UTF-16 code units and
/// three UTF-8 bytes per permitted code unit; a particular field may impose
/// a lower limit.
///
/// [Unicode scalar values]: https://www.unicode.org/glossary/#unicode_scalar_value
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct PrefixedString(
    /// The string value.
    pub String,
);

impl PrefixedString {
    /// The maximum number of UTF-16 code units permitted in the string.
    pub const MAX_UTF16_CODE_UNITS: usize = 0x7fff;
    /// The maximum size of the UTF-8 payload, excluding its VarInt length prefix.
    pub const MAX_BYTES: usize = Self::MAX_UTF16_CODE_UNITS * 3;

    fn encode_value(value: &str, writer: &mut impl Write) -> Result<(), CodecError> {
        encode_prefixed_string(
            value,
            writer,
            CodecKind::String,
            Self::MAX_BYTES,
            Self::MAX_UTF16_CODE_UNITS,
        )
    }

    fn decode_value(reader: &mut impl Read) -> Result<(String, usize), CodecError> {
        decode_prefixed_string(
            reader,
            CodecKind::String,
            Self::MAX_BYTES,
            Self::MAX_UTF16_CODE_UNITS,
        )
    }
}

/// Encodes `value` as a VarInt-length-prefixed string.
///
/// `codec` identifies the codec in errors, `max_bytes` limits the UTF-8
/// payload, and `max_code_units` limits the number of UTF-16 code units.
/// Supplementary Unicode scalar values count as two UTF-16 code units.
///
/// # Errors
///
/// Returns a [`CodecError`] if the string exceeds `max_bytes` or
/// `max_code_units`, or if the underlying writer fails while writing the length
/// prefix or payload.
pub(crate) fn encode_prefixed_string(
    value: &str,
    writer: &mut impl Write,
    codec: CodecKind,
    max_bytes: usize,
    max_code_units: usize,
) -> Result<(), CodecError> {
    if value.len() > max_bytes {
        return Err(CodecError::invalid_encoding_for_operation(
            codec,
            CodecOperation::Write,
            0,
            InvalidEncodingReason::StringTooLong { max_bytes },
        ));
    }
    if value.encode_utf16().count() > max_code_units {
        return Err(CodecError::invalid_encoding_for_operation(
            codec,
            CodecOperation::Write,
            0,
            InvalidEncodingReason::TooManyUtf16CodeUnits { max_code_units },
        ));
    }

    let bytes = value.as_bytes();
    let prefix_size = writer
        .write_varint_with_size(bytes.len() as i32)
        .map_err(|error| error.with_context(codec))?;
    write_all_counted(writer, bytes, codec, prefix_size)
}

/// Decodes a VarInt-length-prefixed string and returns its value and the total
/// number of bytes processed, including the length prefix.
///
/// `codec` is the codec in errors, `max_bytes` limits the UTF-8 payload, and
/// `max_code_units` limits the number of UTF-16 code units.
///
/// # Errors
///
/// Returns a [`CodecError`] if the length prefix is negative, the payload
/// exceeds `max_bytes`, the payload contains invalid UTF-8 or more than
/// `max_code_units` UTF-16 code units, or the reader reaches an unexpected end
/// of input.
pub(crate) fn decode_prefixed_string(
    reader: &mut impl Read,
    codec: CodecKind,
    max_bytes: usize,
    max_code_units: usize,
) -> Result<(String, usize), CodecError> {
    let (byte_length, prefix_size) = reader
        .read_varint_with_size()
        .map_err(|error| error.with_context(codec))?;
    let byte_length = usize::try_from(byte_length).map_err(|_| {
        CodecError::invalid_encoding(
            codec,
            prefix_size,
            InvalidEncodingReason::NegativeLength { value: byte_length },
        )
    })?;

    if byte_length > max_bytes {
        return Err(CodecError::invalid_encoding(
            codec,
            prefix_size,
            InvalidEncodingReason::StringTooLong { max_bytes },
        ));
    }

    let mut bytes = vec![0; byte_length];
    read_exact_counted(reader, &mut bytes, codec, prefix_size)?;
    let bytes_processed = prefix_size + byte_length;
    let value = String::from_utf8(bytes).map_err(|error| {
        let utf8_error = error.utf8_error();
        CodecError::invalid_encoding(
            codec,
            bytes_processed,
            InvalidEncodingReason::InvalidUtf8 {
                valid_up_to: utf8_error.valid_up_to(),
                error_len: utf8_error.error_len(),
            },
        )
    })?;
    if value.len() > max_bytes {
        return Err(CodecError::invalid_encoding(
            codec,
            bytes_processed,
            InvalidEncodingReason::StringTooLong { max_bytes },
        ));
    }
    if value.encode_utf16().count() > max_code_units {
        return Err(CodecError::invalid_encoding(
            codec,
            bytes_processed,
            InvalidEncodingReason::TooManyUtf16CodeUnits { max_code_units },
        ));
    }
    Ok((value, bytes_processed))
}

impl TypeCodec for PrefixedString {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        Self::encode_value(&self.0, writer)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        Self::decode_value(reader).map(|(value, _)| Self(value))
    }
}

/// A resource identifier encoded as a [`PrefixedString`].
///
/// The namespace permits `[a-z0-9._-]`; the value permits
/// `[a-z0-9._/-]`. See the protocol's [identifier format] for details.
///
/// [identifier format]: https://minecraft.wiki/w/Java_Edition_protocol/Packets#Identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Identifier(String);

impl Identifier {
    /// The maximum number of UTF-16 code units permitted in the identifier.
    pub const MAX_UTF16_CODE_UNITS: usize = PrefixedString::MAX_UTF16_CODE_UNITS;
    /// The maximum size of the UTF-8 payload, excluding its VarInt length prefix.
    pub const MAX_BYTES: usize = PrefixedString::MAX_BYTES;
    /// The maximum encoded size, including the VarInt length prefix.
    pub const MAX_ENCODED_BYTES: usize = Self::MAX_BYTES + 3;

    /// Creates an identifier after validating its namespace and path.
    ///
    /// An identifier without an explicit namespace is validated as belonging
    /// to the `minecraft` namespace, but its original spelling is preserved.
    ///
    /// # Errors
    ///
    /// Returns [`InvalidIdentifier`] if the namespace or path is empty or
    /// contains a character not permitted by the identifier format.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidIdentifier> {
        let value = value.into();
        validate_identifier(&value)?;
        Ok(Self(value))
    }

    /// Returns the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the owned identifier string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl fmt::Display for Identifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl Serialize for Identifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Identifier {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

impl TypeCodec for Identifier {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        PrefixedString::encode_value(&self.0, writer)
            .map_err(|error| error.with_context(CodecKind::Identifier))
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        let (value, bytes_processed) = PrefixedString::decode_value(reader)
            .map_err(|error| error.with_context(CodecKind::Identifier))?;
        Self::new(value).map_err(|_| {
            CodecError::invalid_encoding(
                CodecKind::Identifier,
                bytes_processed,
                InvalidEncodingReason::InvalidIdentifier,
            )
        })
    }
}

/// Returns whether a string is a valid Minecraft resource identifier.
///
/// An identifier without an explicit namespace is validated as belonging to
/// the `minecraft` namespace. The namespace permits `[a-z0-9._-]`; the path
/// permits `[a-z0-9._/-]`. See the protocol's [identifier format].
///
/// [identifier format]: https://minecraft.wiki/w/Java_Edition_protocol/Packets#Identifier
pub(crate) fn is_valid_identifier(value: &str) -> bool {
    let (namespace, path) = match value.split_once(':') {
        Some((namespace, path)) => (namespace, path),
        None => ("minecraft", value),
    };
    let namespace_is_valid = !namespace.is_empty()
        && namespace.bytes().all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_.-".contains(&byte)
        });
    let path_is_valid = !path.is_empty()
        && path.bytes().all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"/._-".contains(&byte)
        });
    namespace_is_valid && path_is_valid && !path.contains(':')
}

fn validate_identifier(value: &str) -> Result<(), InvalidIdentifier> {
    if is_valid_identifier(value) {
        Ok(())
    } else {
        Err(InvalidIdentifier)
    }
}

/// An error returned when a string is not a valid Minecraft resource identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidIdentifier;

impl fmt::Display for InvalidIdentifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("invalid Minecraft identifier")
    }
}

impl std::error::Error for InvalidIdentifier {}

/// A variable-length two's-complement signed 32-bit integer.
///
/// VarInts use one to five bytes on the wire. Each byte carries seven payload
/// bits; the most-significant bit is set on every byte except the last.
///
/// # Examples
///
/// ```
/// use mcproto_types::{TypeCodec, basic::VarInt};
///
/// let mut encoded = Vec::new();
/// VarInt(25565).encode(&mut encoded)?;
/// assert_eq!(encoded, [0xdd, 0xc7, 0x01]);
///
/// let mut input = encoded.as_slice();
/// assert_eq!(VarInt::decode(&mut input)?, VarInt(25565));
/// assert!(input.is_empty());
/// # Ok::<(), mcproto_codec::error::CodecError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct VarInt(
    /// The integer value.
    pub i32,
);

impl TypeCodec for VarInt {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        writer.write_varint(self.0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        reader.read_varint().map(Self)
    }
}

/// A variable-length two's-complement signed 64-bit integer.
///
/// VarLongs use one to ten bytes on the wire. Each byte carries seven payload
/// bits; the most-significant bit is set on every byte except the last.
///
/// # Examples
///
/// ```
/// use mcproto_types::{TypeCodec, basic::VarLong};
///
/// let mut encoded = Vec::new();
/// VarLong(9_223_372_036_854_775_000).encode(&mut encoded)?;
///
/// let mut input = encoded.as_slice();
/// assert_eq!(
///     VarLong::decode(&mut input)?,
///     VarLong(9_223_372_036_854_775_000),
/// );
/// assert!(input.is_empty());
/// # Ok::<(), mcproto_codec::error::CodecError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct VarLong(
    /// The integer value.
    pub i64,
);

impl TypeCodec for VarLong {
    fn encode(&self, writer: &mut impl Write) -> Result<(), CodecError> {
        writer.write_varlong(self.0)
    }

    fn decode(reader: &mut impl Read) -> Result<Self, CodecError> {
        reader.read_varlong().map(Self)
    }
}