swarm_bot_packets/
write.rs1use std::io::Write;
2
3use bytes::{BufMut, BytesMut};
4
5use crate::types::VarInt;
6
7#[derive(Default)]
8pub struct ByteWriter {
9 bytes: BytesMut,
10}
11
12impl Write for ByteWriter {
13 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
14 for elem in buf {
15 self.write(*elem);
16 }
17
18 Ok(buf.len())
19 }
20
21 fn flush(&mut self) -> std::io::Result<()> {
22 Ok(())
23 }
24}
25
26impl ByteWritable for u8 {
27 fn write_to_bytes(self, writer: &mut ByteWriter) {
28 writer.bytes.put_u8(self);
29 }
30}
31
32impl ByteWritable for bool {
33 fn write_to_bytes(self, writer: &mut ByteWriter) {
34 let val: u8 = if self { 1 } else { 0 };
35 writer.write(val);
36 }
37}
38
39impl ByteWritable for u128 {
40 fn write_to_bytes(self, writer: &mut ByteWriter) {
41 writer.bytes.put_u128(self);
42 }
43}
44
45impl ByteWritable for i16 {
46 fn write_to_bytes(self, writer: &mut ByteWriter) {
47 writer.bytes.put_i16(self);
48 }
49}
50
51impl ByteWritable for f64 {
52 fn write_to_bytes(self, writer: &mut ByteWriter) {
53 writer.bytes.put_f64(self);
54 }
55}
56
57impl ByteWritable for u64 {
58 fn write_to_bytes(self, writer: &mut ByteWriter) {
59 writer.bytes.put_u64(self);
60 }
61}
62
63impl ByteWritable for f32 {
64 fn write_to_bytes(self, writer: &mut ByteWriter) {
65 writer.bytes.put_f32(self);
66 }
67}
68
69impl ByteWritable for u16 {
70 fn write_to_bytes(self, writer: &mut ByteWriter) {
71 writer.bytes.put_u16(self);
72 }
73}
74
75pub trait ByteWritable {
76 fn write_to_bytes(self, writer: &mut ByteWriter);
77}
78
79pub trait ByteWritableLike {
80 type Param;
81 fn write_to_bytes_like(self, writer: &mut ByteWriter, param: &Self::Param);
82}
83
84impl ByteWriter {
85 pub fn write<T: ByteWritable>(&mut self, value: T) -> &mut Self {
86 value.write_to_bytes(self);
87 self
88 }
89
90 pub fn write_like<T: ByteWritableLike<Param = P>, P>(
91 &mut self,
92 value: T,
93 param: &P,
94 ) -> &mut Self {
95 value.write_to_bytes_like(self, param);
96 self
97 }
98
99 pub fn new() -> Self {
100 ByteWriter {
101 bytes: BytesMut::new(),
102 }
103 }
104
105 pub fn freeze(self) -> Vec<u8> {
106 self.bytes.freeze().to_vec()
107 }
108}
109
110impl ByteWritable for &[u8] {
111 fn write_to_bytes(self, writer: &mut ByteWriter) {
112 for &x in self {
113 writer.write(x);
114 }
115 }
116}
117
118impl ByteWritable for String {
119 fn write_to_bytes(self, writer: &mut ByteWriter) {
120 let bytes = self.as_bytes();
121 let byte_len = self.bytes().len();
122
123 writer.write(VarInt::from(byte_len)).write(bytes);
124 }
125}
126
127impl ByteWritable for Vec<u8> {
128 fn write_to_bytes(self, writer: &mut ByteWriter) {
129 let len: VarInt = self.len().into();
130 writer.write(len);
131 for x in self {
132 writer.write(x);
133 }
134 }
135}