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
use crate::codec::{decode_u16, encode_u16, Codec, CodecError, CodecResult, Reader};
use std::fmt::Debug;
use std::io;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicU16, Ordering};

/// Enum for errors that could occur when dealing with packets
/// (encoding and decoding)
#[derive(Debug)]
pub enum PacketError {
    CodecError(CodecError),
    IO(io::Error),
}

impl From<CodecError> for PacketError {
    fn from(err: CodecError) -> Self {
        PacketError::CodecError(err)
    }
}

impl From<io::Error> for PacketError {
    fn from(err: io::Error) -> Self {
        PacketError::IO(err)
    }
}

/// Result type for returning a value or Packet Error
pub type PacketResult<T> = Result<T, PacketError>;

/// Empty content type for packets
#[derive(Debug)]
pub struct EmptyContent {}

impl Codec for EmptyContent {
    fn encode(&self, _: &mut Vec<u8>) {}

    fn decode(_: &mut Reader) -> CodecResult<Self> {
        Ok(EmptyContent {})
    }
}

impl PacketContent for EmptyContent {}

/// Trait implemented by Codec values that can be used
/// as packet contents
pub trait PacketContent: Codec + Debug {}

/// Trait for implementing packet target details
pub trait PacketComponent: Debug + Eq + PartialEq {
    fn component(&self) -> u16;

    fn command(&self) -> u16;

    fn from_value(value: u16) -> Self;
}

/// The different types of packets
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PacketType {
    /// ID counted request packets
    Request,
    /// Packets responding to requests
    Response,
    /// Unique packets coming from the server
    Notify,
    /// Error packets
    Error,
    /// Packet type that is unknown
    Unknown(u16),
}

impl PacketType {
    /// Returns the u16 representation of the packet type
    pub fn value(&self) -> u16 {
        match self {
            PacketType::Request => 0x0000,
            PacketType::Response => 0x1000,
            PacketType::Notify => 0x2000,
            PacketType::Error => 0x3000,
            PacketType::Unknown(value) => *value,
        }
    }

    /// Gets the packet type this value is represented by
    pub fn from_value(value: u16) -> PacketType {
        match value {
            0x0000 => PacketType::Request,
            0x1000 => PacketType::Response,
            0x2000 => PacketType::Notify,
            0x3000 => PacketType::Error,
            value => PacketType::Unknown(value),
        }
    }
}

/// Structure of packet header which comes before the
/// packet content and describes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PacketHeader {
    /// The component of this packet
    pub component: u16,
    /// The command of this packet
    pub command: u16,
    /// A possible error this packet contains (zero is none)
    pub error: u16,
    /// The type of this packet
    pub ty: PacketType,
    /// The unique ID of this packet (Notify packets this is just zero)
    pub id: u16,
}

impl PacketHeader {
    /// Encodes a packet header with the provided length value
    pub fn encode_bytes(&self, length: usize) -> Vec<u8> {
        let mut header = Vec::with_capacity(12);
        let is_extended = length > 0xFFFF;
        encode_u16(&(length as u16), &mut header);
        encode_u16(&self.component, &mut header);
        encode_u16(&self.command, &mut header);
        encode_u16(&self.error, &mut header);
        header.push((self.ty.value() >> 8) as u8);
        header.push(if is_extended { 0x10 } else { 0x00 });
        encode_u16(&self.id, &mut header);
        if is_extended {
            header.push(((length & 0xFF000000) >> 24) as u8);
            header.push(((length & 0x00FF0000) >> 16) as u8);
        }
        header
    }

    /// Reads a packet header from the provided input as well as
    /// the length of the content
    pub fn read<R: Read>(input: &mut R) -> PacketResult<(PacketHeader, usize)>
    where
        Self: Sized,
    {
        let mut header = [0u8; 12];
        input.read_exact(&mut header)?;
        let mut length = decode_u16(&header[0..2])? as usize;
        let component = decode_u16(&header[2..4])?;
        let command = decode_u16(&header[4..6])?;
        let error = decode_u16(&header[6..8])?;
        let q_type = decode_u16(&header[8..10])?;
        let id = decode_u16(&header[10..12])?;
        if q_type & 0x10 != 0 {
            let mut buffer = [0; 2];
            input.read_exact(&mut buffer)?;
            let ext_length = u16::from_be_bytes(buffer);
            length += (ext_length as usize) << 16;
        }
        let ty = PacketType::from_value(q_type);
        let header = PacketHeader {
            component,
            command,
            error,
            ty,
            id,
        };
        Ok((header, length))
    }
}

/// Structure for a packet created by ourselves where
/// the data contents are already known and not encoded
#[derive(Debug)]
pub struct Packet<C: PacketContent>(PacketHeader, C);

/// Structure for storing functions related to creation of packets
pub struct Packets {}

impl Packets {
    /// Creates a new response packet for responding to the provided
    /// decodable packet. With the `contents`
    pub fn response<C: PacketContent>(packet: &OpaquePacket, contents: C) -> Packet<C> {
        let mut header = packet.0.clone();
        header.ty = PacketType::Response;
        Packet(header, contents)
    }

    /// Shortcut function for creating a response packet with no content
    #[inline]
    pub fn response_empty(packet: &OpaquePacket) -> Packet<EmptyContent> {
        Self::response(packet, EmptyContent {})
    }

    /// Creates a new error response packet for responding to the
    /// provided packet with an error number with `contents`
    pub fn error<C: PacketContent>(
        packet: &OpaquePacket,
        error: impl Into<u16>,
        contents: C,
    ) -> Packet<C> {
        let mut header = packet.0.clone();
        header.error = error.into();
        header.ty = PacketType::Error;
        Packet(header, contents)
    }

    /// Shortcut function for creating an error packet with no content
    #[inline]
    pub fn error_empty(packet: &OpaquePacket, error: impl Into<u16>) -> Packet<EmptyContent> {
        Self::error(packet, error, EmptyContent {})
    }

    /// Creates a new notify packet with the provided component and command
    /// and `contents`
    pub fn notify<C: PacketContent>(component: impl PacketComponent, contents: C) -> Packet<C> {
        Packet(
            PacketHeader {
                component: component.component(),
                command: component.command(),
                error: 0,
                ty: PacketType::Notify,
                id: 0,
            },
            contents,
        )
    }
    /// Shortcut function for creating a notify packet with no content
    #[inline]
    pub fn notify_empty(component: impl PacketComponent) -> Packet<EmptyContent> {
        Self::notify(component, EmptyContent {})
    }

    /// Creates a new request packet retrieving its ID from the provided
    /// request counter.
    pub fn request<R: RequestCounter, C: PacketContent>(
        counter: &mut R,
        component: impl PacketComponent,
        contents: C,
    ) -> Packet<C> {
        Packet(
            PacketHeader {
                component: component.component(),
                command: component.command(),
                error: 0,
                ty: PacketType::Request,
                id: counter.next(),
            },
            contents,
        )
    }
}

impl<C: PacketContent> Packet<C> {
    /// Reads a packet from the provided input and parses the
    /// contents
    pub fn read<R: Read>(input: &mut R) -> PacketResult<Packet<C>>
    where
        Self: Sized,
    {
        let (header, length) = PacketHeader::read(input)?;
        let mut contents = vec![0u8; length];
        input.read_exact(&mut contents)?;
        let mut reader = Reader::new(&contents);
        let contents = C::decode(&mut reader)?;
        Ok(Packet(header, contents))
    }

    /// Handles writing the header and contents of this packet to
    /// the Writable object
    pub fn write<W: Write>(&self, output: &mut W) -> io::Result<()>
    where
        Self: Sized,
    {
        let content = self.1.encode_bytes();
        let header = self.0.encode_bytes(content.len());
        output.write_all(&header)?;
        output.write_all(&content)?;
        Ok(())
    }
}

impl<C: PacketContent> TryInto<Packet<C>> for OpaquePacket {
    type Error = CodecError;

    fn try_into(self) -> Result<Packet<C>, Self::Error> {
        let contents = self.contents::<C>()?;
        Ok(Packet(self.0, contents))
    }
}

/// Structure for packets that have been read where the contents
/// are not know and are encoded as a vector of bytes.
#[derive(Debug)]
pub struct OpaquePacket(pub PacketHeader, pub Vec<u8>);

impl OpaquePacket {
    /// Reads the contents of this encoded packet and tries to decode
    /// the `R` from it.
    pub fn contents<R: PacketContent>(&self) -> CodecResult<R> {
        let mut reader = Reader::new(&self.1);
        R::decode(&mut reader)
    }

    /// Reads a packet from the provided input without parsing
    /// the contents of the packet
    pub fn read<R: Read>(input: &mut R) -> PacketResult<Self>
    where
        Self: Sized,
    {
        let (header, length) = PacketHeader::read(input)?;
        let mut contents = vec![0u8; length];
        input.read_exact(&mut contents)?;
        Ok(Self(header, contents))
    }
}

/// Structure for counting requests to generate the packet
/// ID's for requests
pub trait RequestCounter {
    /// Called to obtain the next packet ID
    fn next(&mut self) -> u16;
}

/// Simple counter which is just backed by a u16
/// value that is incremented on each request
pub struct SimpleCounter {
    value: u16,
}

impl SimpleCounter {
    /// Creates a new simple counter
    pub fn new() -> SimpleCounter {
        SimpleCounter { value: 0 }
    }
}

impl RequestCounter for SimpleCounter {
    fn next(&mut self) -> u16 {
        self.value += 1;
        self.value
    }
}

/// Atomic backed counter implementation
pub struct AtomicCounter {
    value: AtomicU16,
}

impl AtomicCounter {
    /// Creates a new atomic counter
    pub fn new() -> AtomicCounter {
        AtomicCounter {
            value: AtomicU16::new(0),
        }
    }
}

impl RequestCounter for AtomicCounter {
    fn next(&mut self) -> u16 {
        self.value.fetch_add(1, Ordering::AcqRel)
    }
}

#[cfg(test)]
mod test {
    use crate::packet::{OpaquePacket, Packet, Packets};
    use crate::types::VarInt;
    use crate::{define_components, packet};
    use std::io::Cursor;

    packet! {
        struct Test {
            TEST: String,
            ALT: VarInt,
            AA: u32,
        }
    }

    define_components! {
        Authentication (0x0) {
            First (0x1)
            Second (0x2)
            Third (0x3)
        }

        Other (0x1) {
            First (0x1)
            Second (0x2)
            Third (0x3)
        }
    }

    #[test]
    fn test() {
        let contents = Test {
            TEST: String::from("Test"),
            ALT: VarInt(0),
            AA: 32,
        };
        println!("{:?}", contents);
        let packet = Packets::notify(components::Authentication::Second, contents);
        println!("{packet:?}");

        let mut out = Cursor::new(Vec::new());
        packet.write(&mut out).unwrap();

        let bytes = out.get_ref();
        println!("{bytes:?}");
        let mut bytes_in = Cursor::new(bytes);

        let packet_in = OpaquePacket::read(&mut bytes_in).unwrap();
        println!("{packet_in:?}");
        let packet_in_dec: Packet<Test> = packet_in.try_into().unwrap();
        println!("{packet_in_dec:?}");

        assert_eq!(packet.0, packet_in_dec.0)
    }
}