aboutsummaryrefslogtreecommitdiff
path: root/minecraft-protocol/src/friendly_byte_buf.rs
blob: 2babe3980b94338d70bd1bac4c88a0142b90a925 (plain)
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
//! Minecraft calls it a "friendly byte buffer".

use byteorder::{BigEndian, WriteBytesExt};
// use std::io::Write;

const MAX_VARINT_SIZE: u32 = 5;
const MAX_VARLONG_SIZE: u32 = 10;
const DEFAULT_NBT_QUOTA: u32 = 2097152;
const MAX_STRING_LENGTH: u16 = 32767;
const MAX_COMPONENT_STRING_LENGTH: u32 = 262144;

pub struct FriendlyByteBuf<'a> {
    source: &'a mut Vec<u8>,
}

impl FriendlyByteBuf<'_> {
    pub fn write_byte(&mut self, n: u8) {
        self.source.write_u8(n).unwrap();
        println!("write_byte: {}", n);
    }

    pub fn write_bytes(&mut self, bytes: &[u8]) {
        self.source.extend_from_slice(bytes);
    }

    pub fn write_varint(&mut self, mut n: u32) {
        loop {
            if (n & 0xFFFFFF80) == 0 {
                self.write_byte(n as u8);
                return ();
            }
            self.write_byte((n & 0x7F | 0x80) as u8);
            n >>= 7;
        }
    }

    pub fn write_utf_with_len(&mut self, string: &String, len: usize) {
        if string.len() > len {
            panic!(
                "String too big (was {} bytes encoded, max {})",
                string.len(),
                len
            );
        }
        self.write_varint(string.len() as u32);
        self.write_bytes(string.as_bytes());
    }

    pub fn write_utf(&mut self, string: &String) {
        self.write_utf_with_len(string, MAX_STRING_LENGTH as usize);
    }

    pub fn write_short(&mut self, n: u16) {
        self.source.write_u16::<BigEndian>(n).unwrap();
    }
}