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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
#![allow(dead_code)]
//! Access Valve's Server Query using this package.
//!
//! # Game Server Info
//!
//! ```ignore
//! use valve_server_query::client::Client;
//!
//! let client = Client::new("ip:port").expects("Connect to dedicated server running Valve game");
//!
//! let info = client.info().expects("Get general server information");
//! let players = client.players().expects("Get server player information");
//! let rules = client.rules().expects("Get server rules");
//! ```

pub use client::Client;
pub use models::info::Server;
pub use models::Player;

pub mod constants {
    const ENCODING: &str = "utf-8";
    const PACKET_SIZE: u16 = 1400;

    /// Packet is not split.
    pub const SIMPLE_RESPONSE_HEADER: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFF];
    /// Packet is split.
    pub const MULTI_PACKET_RESPONSE_HEADER: [u8; 4] = [0xFF, 0xFF, 0xFF, 0xFE];
}

/// All types are little endian
pub mod types {

    // All types are little endian
    pub type Byte = u8;
    pub type Short = i16;
    pub type Long = i32;
    pub type Float = f32;
    pub type LongLong = u64;
    pub type CString = std::ffi::CString;

    /// All types are little endian,
    pub enum DataType {
        // Name   Description
        //
        // byte   8 bit character or unsigned integer
        // short  16 bit signed integer
        // long   32 bit signed integer
        // float  32 bit floating point
        // long   long 64 bit unsigned integer
        // string variable-length byte field, encoded in UTF-8, terminated by null byte (0x00)
        Byte(Byte),
        Short(Short),
        Long(i32),
        Float(f32),
        LongLong(u64),
        // UTF-8 Encoded
        // Null-Terminated
        String(CString),
    }

    type ByteVec = Vec<u8>;

    pub fn get_byte<'a, I>(bytes: &mut I) -> Byte
    where
        I: Iterator<Item = &'a u8>,
    {
        bytes.next().unwrap().to_owned()
    }
    pub fn get_short<'a, I>(bytes: &mut I) -> Short
    where
        I: Iterator<Item = &'a u8>,
    {
        Short::from_le_bytes([*bytes.next().unwrap(), *bytes.next().unwrap()])
    }
    pub fn get_long<'a, I>(bytes: &mut I) -> Long
    where
        I: Iterator<Item = &'a u8>,
    {
        Long::from_le_bytes([
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
        ])
    }
    pub fn get_float<'a, I>(bytes: &mut I) -> Float
    where
        I: Iterator<Item = &'a u8>,
    {
        Float::from_le_bytes([
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
        ])
    }
    pub fn get_longlong<'a, I>(bytes: &mut I) -> LongLong
    where
        I: Iterator<Item = &'a u8>,
    {
        LongLong::from_le_bytes([
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
            *bytes.next().unwrap(),
        ])
    }
    pub fn get_string<'a, I>(bytes: &mut I) -> String
    where
        I: Iterator<Item = &'a u8>,
    {
        let mut string = String::new();
        loop {
            let byte = bytes.next().unwrap();
            if *byte == 0 {
                break;
            } else {
                string.push(*byte as char);
            }
        }
        string
    }
}

pub mod models {

    use crate::types::{get_byte, get_float, get_long, get_string, Byte, Float, Long};

    #[derive(Debug, PartialEq)]
    pub struct Player {
        index: Byte,
        name: String,
        score: Long,
        duration: Float,
    }

    impl Default for Player {
        fn default() -> Self {
            Self {
                index: 0,
                name: "".to_string(),
                score: 0,
                duration: 0.0,
            }
        }
    }

    impl Player {
        pub fn get_players(bytes: &[u8]) -> Vec<Self> {
            let mut it = bytes.iter();
            let mut players: Vec<Self> = Vec::new();

            while it.len()
                > (
                    // There's a String too, but that has a varialble size.
                    std::mem::size_of::<Byte>()
                        + std::mem::size_of::<Long>()
                        + std::mem::size_of::<Float>()
                )
            {
                let player = Self::from_iter_bytes(&mut it);

                players.push(player);
            }

            players
        }

        pub fn from_iter_bytes<'a, I>(iter_bytes: &mut I) -> Self
        where
            I: Iterator<Item = &'a u8>,
        {
            let index = get_byte(iter_bytes);
            let name = get_string(iter_bytes);
            let score = get_long(iter_bytes);
            let duration = get_float(iter_bytes);

            Self {
                index,
                name,
                score,
                duration,
            }
        }

        pub fn from_bytes(bytes: &[u8]) -> Self {
            let mut it = bytes.iter();

            let index = get_byte(&mut it);
            let name = get_string(&mut it);
            let score = get_long(&mut it);
            let duration = get_float(&mut it);

            Self {
                index,
                name,
                score,
                duration,
            }
        }
    }

    pub mod info {

        use crate::types::{Byte, LongLong, Short};

        /// Represents a steam game server.
        ///
        /// Ref: <https://developer.valvesoftware.com/wiki/Server_queries#A2S_INFO>
        #[derive(Debug)]
        pub struct Server {
            /// Response header. Always equal to 'I' (0x49).
            header: Byte,
            /// Protocol version used by the server.
            protocol: Byte,
            /// Name of the server.
            name: String,
            /// Map the server has currently loaded.
            map: String,
            /// Name of the folder containing the game files.
            folder: String,
            /// Full name of the game.
            game: String,
            /// Steam Application ID of game.
            id: Short,
            /// Number of players on the server.
            players: Byte,
            /// Maximum number of players the server reports it can hold.
            max_players: Byte,
            /// Number of bots on the server.
            bots: Byte,
            /// Indicates the type of server:
            /// 'd' for a dedicated server
            /// 'l' for a non-dedicated server
            /// 'p' for a SourceTV relay (proxy)
            server_type: ServerType,
            /// Indicates the operating system of the server:
            /// 'l' for Linux
            /// 'w' for Windows
            /// 'm' or 'o' for Mac (the code changed after L4D1)
            environment: Environment,
            /// Indicates whether the server requires a password:
            /// 0 for public
            /// 1 for private
            visibility: Visibility,
            /// Specifies whether the server uses VAC:
            /// 0 for unsecured
            /// 1 for secured
            vac: Vac,
            /// Version of the game installed on the server.
            game_version: String,
            /// Flag for Extra Features
            extra_data_flag: Option<Byte>,
            /// The server's game port number.
            port: Option<Short>,
            /// Server's SteamID.
            steam_id: Option<LongLong>,
            /// Spectator port number for SourceTV.
            spectator_port: Option<Short>,
            /// Name of the spectator server for SourceTV.
            spectator_name: Option<String>,
            /// Tags that describe the game according to the server (for future use.)
            keywords: Option<String>,
            /// The server's 64-bit GameID. If this is present, a more accurate AppID is present in the
            /// low 24 bits. The earlier AppID could have been truncated as it was forced into 16-bit
            /// storage.
            game_id: Option<LongLong>,
            /// Trailing bytes for Self::from_bytes
            trailing_bytes: Option<Vec<Byte>>,
        }

        impl Server {
            pub fn from_bytes(bytes: &[u8]) -> Self {
                use crate::types::get_byte;
                use crate::types::get_longlong;
                use crate::types::get_short;
                use crate::types::get_string;
                use crate::utils::compress_trailing_null_bytes;

                let mut it = bytes.iter();

                let header = get_byte(&mut it);
                let protocol = get_byte(&mut it);
                let name = get_string(&mut it);
                let map = get_string(&mut it);
                let folder = get_string(&mut it);
                let game = get_string(&mut it);
                let id = get_short(&mut it);
                let players = get_byte(&mut it);
                let max_players = get_byte(&mut it);
                let bots = get_byte(&mut it);
                let server_type = ServerType::from_byte(&get_byte(&mut it));
                let environment = Environment::from_byte(&get_byte(&mut it));
                let visibility = Visibility::from_byte(&get_byte(&mut it));
                let vac = Vac::from_byte(&get_byte(&mut it));
                let game_version = get_string(&mut it);

                let extra_data_flag: Option<u8>;
                if let Some(u) = it.next() {
                    extra_data_flag = Some(*u);
                } else {
                    extra_data_flag = None;
                }

                let port: Option<Short>;
                if extra_data_flag != None && (extra_data_flag.unwrap() & 0x80) != 0 {
                    port = Some(get_short(&mut it));
                } else {
                    port = None;
                }

                let steam_id: Option<LongLong>;
                if extra_data_flag != None && (extra_data_flag.unwrap() & 0x10) != 0 {
                    steam_id = Some(get_longlong(&mut it));
                } else {
                    steam_id = None;
                }

                let spectator_port: Option<Short>;
                let spectator_name: Option<String>;
                if extra_data_flag != None && (extra_data_flag.unwrap() & 0x40) != 0 {
                    spectator_port = Some(get_short(&mut it));
                    spectator_name = Some(get_string(&mut it));
                } else {
                    spectator_port = None;
                    spectator_name = None;
                }

                let keywords: Option<String>;
                if extra_data_flag != None && (extra_data_flag.unwrap() & 0x20) != 0 {
                    keywords = Some(get_string(&mut it));
                } else {
                    keywords = None;
                }

                let game_id: Option<LongLong>;
                if extra_data_flag != None && (extra_data_flag.unwrap() & 0x01) != 0 {
                    game_id = Some(get_longlong(&mut it));
                } else {
                    game_id = None;
                }

                // These are hanging bytes that were not parsed
                let trailing_bytes: Option<Vec<u8>> = if it.len() > 0 {
                    // Remove trailing null bytes (and leave one if there are any)
                    let mut min_bytes: Vec<u8> = it.into_iter().map(|x| *x).collect();
                    compress_trailing_null_bytes(&mut min_bytes);

                    // Just a [0]
                    if min_bytes.len() == 1 && *min_bytes.last().unwrap() == 0 {
                        None
                    } else {
                        Some(min_bytes.into_iter().collect::<Vec<u8>>())
                    }
                } else {
                    None
                };

                Self {
                    header,
                    game_id,
                    trailing_bytes,
                    keywords,
                    spectator_port,
                    spectator_name,
                    extra_data_flag,
                    steam_id,
                    protocol,
                    name,
                    map,
                    folder,
                    game,
                    id,
                    players,
                    max_players,
                    bots,
                    server_type,
                    environment,
                    visibility,
                    vac,
                    game_version,
                    port,
                }
            }
        }

        #[derive(Debug, Eq, PartialEq)]
        enum ServerType {
            Dedicated,
            NonDedicated,
            SourceTvRelay,
        }

        impl ServerType {
            fn from_byte(byte: &u8) -> Self {
                use self::ServerType::{Dedicated, NonDedicated, SourceTvRelay};

                match *byte as char {
                    'd' => Dedicated,
                    'l' => NonDedicated,
                    'p' => SourceTvRelay,
                    _ => panic!("Unrecognized Server Type: <{byte}>."),
                }
            }
        }

        #[derive(Debug, Eq, PartialEq)]
        enum Environment {
            Linux,
            Windows,
            Mac,
        }

        impl Environment {
            fn from_byte(byte: &u8) -> Self {
                use self::Environment::{Linux, Mac, Windows};

                match *byte as char {
                    'l' => Linux,
                    'w' => Windows,
                    'm' => Mac,
                    'o' => Mac,
                    _ => panic!("Unrecognized Environment: <{byte}>."),
                }
            }
        }

        #[derive(Debug, Eq, PartialEq)]
        enum Visibility {
            Public,
            Private,
        }

        impl Visibility {
            fn from_byte(byte: &u8) -> Self {
                use self::Visibility::{Private, Public};

                match *byte {
                    0x00 => Public,
                    0x01 => Private,
                    _ => panic!("Unrecognized Visibility Byte: <{byte}>."),
                }
            }
        }

        #[derive(Debug, Eq, PartialEq)]
        /// Specifies if a server uses VAC.
        enum Vac {
            Unsecured,
            Secured,
        }

        impl Vac {
            fn from_byte(byte: &u8) -> Self {
                use self::Vac::{Secured, Unsecured};

                match *byte {
                    0x00 => Unsecured,
                    0x01 => Secured,
                    _ => panic!("Unrecognized Vac Byte: <{byte}>."),
                }
            }
        }

        #[cfg(test)]
        mod tests {
            use super::*;
            #[test]
            fn test_servertype_from_byte() {
                assert_eq!(ServerType::Dedicated, ServerType::from_byte(&('d' as u8)));
            }
            #[test]
            fn test_environment_from_byte() {
                assert_eq!(Environment::Linux, Environment::from_byte(&('l' as u8)));
            }
            #[test]
            fn test_visibility_from_byte() {
                assert_eq!(Visibility::Public, Visibility::from_byte(&(0x00)));
            }
            #[test]
            fn test_vac_from_byte() {
                assert_eq!(Vac::Secured, Vac::from_byte(&(0x01)));
            }
        }
    }
}

pub mod client {

    use std::collections::HashMap;
    use std::error::Error;
    use std::io;
    use std::net::SocketAddr;
    use std::net::{IpAddr, Ipv4Addr, UdpSocket};

    use crate::models::info::Server;
    use crate::models::Player;
    use crate::types::Byte;
    use crate::utils::get_multipacket_data;

    type Rules = HashMap<String, String>;

    pub struct Client {
        socket: UdpSocket,
        addr: SocketAddr,
    }

    impl Client {
        pub fn new(url: &str) -> Result<Self, Box<dyn Error>> {
            // Init
            let addr: SocketAddr;
            let socket: UdpSocket;

            // Handle Errors
            let result: Result<SocketAddr, _> = url.parse();
            if let Ok(a) = result {
                addr = a;
            } else {
                if let Err(e) = result {
                    return Err(Box::new(e));
                } else {
                    panic!("Unreachable");
                }
            }

            let result: Result<UdpSocket, _> =
                UdpSocket::bind((IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0));
            if let Ok(s) = result {
                socket = s;
            } else {
                if let Err(e) = result {
                    return Err(Box::new(e));
                } else {
                    panic!("Unreachable");
                }
            }

            // Return Successfully
            Ok(Self { addr, socket })
        }
    }

    // A2S_INFO Implementation
    impl Client {
        pub fn info(&self) -> Result<Server, io::Error> {
            let mut request: Vec<u8> = vec![
                255, 255, 255, 255, 84, 83, 111, 117, 114, 99, 101, 32, 69, 110, 103, 105, 110,
                101, 32, 81, 117, 101, 114, 121, 0,
            ];

            self.socket.send_to(&request, &self.addr)?;

            let mut buffer = [0; 1400];
            let mut bytes_returned = self.socket.recv(&mut buffer)?;

            if bytes_returned == 9 {
                // Challenge Received

                // Last 5 bytes of the response
                let challenge = buffer
                    .into_iter()
                    .rev()
                    .skip_while(|&i| i == 0)
                    .collect::<Vec<u8>>()
                    .to_owned()
                    .into_iter()
                    .rev()
                    .collect::<Vec<u8>>()[5..]
                    .to_vec();

                request.extend(challenge);

                self.socket.send_to(&request, &self.addr)?;
                buffer = [0; 1400];
                bytes_returned = self.socket.recv(&mut buffer)?;
            }

            let packet_header = &buffer[..4];
            let payload: Vec<u8>;
            if packet_header == crate::constants::SIMPLE_RESPONSE_HEADER {
                payload = buffer[4..bytes_returned + 1].to_vec();
            } else if packet_header == crate::constants::MULTI_PACKET_RESPONSE_HEADER {
                // id starts at 0
                // tcp means they don't have to be in order
                let (_answer_id, total, packet_id) = get_multipacket_data(&buffer);
                let mut packet_map: HashMap<Byte, Vec<u8>> = HashMap::with_capacity(total as usize);

                let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                packet_map.insert(packet_id, current_payload);

                // Get the remaining packet data.
                while total > packet_map.len() as u8 {
                    buffer = [0; 1400]; // Clear buffer
                    bytes_returned = self.socket.recv(&mut buffer)?;

                    let (_answer_id, _total, packet_id) = get_multipacket_data(&buffer);
                    let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                    packet_map.insert(packet_id, current_payload);
                }

                // Sort and Collect all packet data
                let mut v: Vec<(u8, Vec<u8>)> = packet_map.into_iter().collect();
                v.sort_by_key(|i| i.0);
                payload = v
                    .into_iter()
                    .map(|(_, bytes)| bytes)
                    .flatten()
                    .collect::<Vec<u8>>();
            } else {
                panic!("An unknown packet header was received.");
            }

            let info = Server::from_bytes(&payload);
            Ok(info)
        }
    }

    // A2S_PLAYER Implementation
    impl Client {
        pub fn players(&self) -> Result<Vec<Player>, io::Error> {
            let request = [
                0xFF, 0xFF, 0xFF, 0xFF, // Simple Header
                0x55, // Header
                0xFF, 0xFF, 0xFF, 0xFF, // Request Challenge
            ];

            self.socket.send_to(&request, &self.addr)?;

            let mut buffer = [0; 1400];
            let _bytes_returned = self.socket.recv(&mut buffer)?;

            //  Get Challenge
            let challenge = buffer
                .into_iter()
                .rev()
                .skip_while(|&i| i == 0)
                .collect::<Vec<u8>>()
                .to_owned()
                .into_iter()
                .rev()
                .collect::<Vec<u8>>()[5..]
                .to_vec();

            // Resend Request
            let mut request = vec![
                0xFF, 0xFF, 0xFF, 0xFF, // Simple Header
                0x55, // Header
            ];
            request.extend(challenge);

            // Get Data
            self.socket.send_to(&request, &self.addr)?;
            buffer = [0; 1400];
            let mut bytes_returned = self.socket.recv(&mut buffer)?;

            // Parse Data
            let packet_header = &buffer[..=3];

            let payload: Vec<u8>;
            if packet_header == crate::constants::SIMPLE_RESPONSE_HEADER {
                payload = buffer[4..].to_vec();
            } else if packet_header == crate::constants::MULTI_PACKET_RESPONSE_HEADER {
                // id starts at 0
                // tcp means they don't have to be in order
                let (_answer_id, total, packet_id) = get_multipacket_data(&buffer);
                let mut packet_map: HashMap<Byte, Vec<u8>> = HashMap::with_capacity(total as usize);

                let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                packet_map.insert(packet_id, current_payload);

                // Get the remaining packet data.
                while total > packet_map.len() as u8 {
                    buffer = [0; 1400]; // Clear buffer
                    bytes_returned = self.socket.recv(&mut buffer)?;

                    let (_answer_id, _total, packet_id) = get_multipacket_data(&buffer);
                    let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                    packet_map.insert(packet_id, current_payload);
                }

                // Sort and Collect all packet data
                let mut v: Vec<(u8, Vec<u8>)> = packet_map.into_iter().collect();
                v.sort_by_key(|i| i.0);
                payload = v
                    .into_iter()
                    .map(|(_, bytes)| bytes)
                    .flatten()
                    .collect::<Vec<u8>>();
            } else {
                panic!("An unknown packet header was received.");
            }

            let _header: &Byte = &payload[0];
            let _player_count: Byte = buffer[1].clone();

            let players: Vec<Player> = Player::get_players(&buffer[2..bytes_returned + 1]);

            Ok(players)
        }
    }

    /// A2S_RULES Implementation
    impl Client {
        pub fn rules(&self) -> Result<Rules, io::Error> {
            use crate::utils::compress_trailing_null_bytes;

            let request = [
                0xFF, 0xFF, 0xFF, 0xFF, // Simple Header
                0x56, // Header
                0xFF, 0xFF, 0xFF, 0xFF, // Request Challenge
            ];

            self.socket.send_to(&request, &self.addr)?;

            let mut buffer = [0; 1400];
            let _bytes_returned = self.socket.recv(&mut buffer)?;

            //  Get Challenge
            let challenge = buffer
                .into_iter()
                .rev()
                .skip_while(|&i| i == 0)
                .collect::<Vec<u8>>()
                .to_owned()
                .into_iter()
                .rev()
                .collect::<Vec<u8>>()[5..]
                .to_vec();

            // Resend Request
            let mut request = vec![
                0xFF, 0xFF, 0xFF, 0xFF, // Simple Header
                0x56, // Header
            ];
            request.extend(challenge);

            // Get Data
            self.socket.send_to(&request, &self.addr)?;
            buffer = [0; 1400];
            let mut bytes_returned = self.socket.recv(&mut buffer)?;

            // Parse Data
            let packet_header = &buffer[..=3];
            let _header: &Byte = &buffer[4];

            let mut payload: Vec<u8>;
            if packet_header == crate::constants::SIMPLE_RESPONSE_HEADER {
                let _rule_count: Byte = buffer[5].clone();
                let _ = buffer[6]; // Null Byte
                payload = buffer[7..].to_vec();
                compress_trailing_null_bytes(&mut payload);
            } else if packet_header == crate::constants::MULTI_PACKET_RESPONSE_HEADER {
                // id starts at 0
                // tcp means they don't have to be in order
                let (_answer_id, total, packet_id) = get_multipacket_data(&buffer);
                let mut packet_map: HashMap<Byte, Vec<u8>> = HashMap::with_capacity(total as usize);

                let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                packet_map.insert(packet_id, current_payload);

                // Get the remaining packet data.
                while total > packet_map.len() as u8 {
                    buffer = [0; 1400]; // Clear buffer
                    bytes_returned = self.socket.recv(&mut buffer)?;

                    let (_answer_id, _total, packet_id) = get_multipacket_data(&buffer);
                    let current_payload = buffer[(4 + 4 + 1 + 1)..bytes_returned + 1].to_vec();
                    packet_map.insert(packet_id, current_payload);
                }

                // Sort and Collect all packet data
                let mut v: Vec<(u8, Vec<u8>)> = packet_map.into_iter().collect();
                v.sort_by_key(|i| i.0);
                payload = v
                    .into_iter()
                    .map(|(_, bytes)| bytes)
                    .flatten()
                    .collect::<Vec<u8>>();
            } else {
                panic!("An unknown packet header was received.");
            }

            let rules: Rules = Self::get_rules(&payload);

            Ok(rules)
        }

        pub fn get_rules(bytes: &[u8]) -> Rules {
            use crate::types::get_string;

            let mut it = bytes.iter();
            let mut rules = HashMap::new();

            while it.len() > 0 {
                let name = get_string(&mut it);
                let value = get_string(&mut it);

                rules.insert(name, value);
            }

            rules
        }
    }

    #[cfg(test)]
    mod tests {

        use super::*;

        #[test]
        fn test_client_init() {
            let client: Result<_, _> = Client::new("");
            if let Err(_) = client {
            } else {
                assert!(false, "Client was successfully contructed when it should have failed when parsing URL.")
            }
        }

        #[test]
        #[ignore]
        fn test_client_init_live() {
            // Live server I own
            let client: Result<_, _> = Client::new("54.186.150.6:9879");
            if let Ok(_) = client {
            } else {
                assert!(
                    false,
                    "Client failed to be contructed when it should have succeeded (LIVE TEST)."
                )
            }
        }

        #[test]
        fn test_client_info() {
            // Dummy
            let client = Client::new("127.0.0.1:12345").unwrap();
            let info: Result<Server, _> = client.info();
            if let Err(_) = info {
            } else {
                assert!(
                    false,
                    "Target URL is not real, but we got back an Ok response for A2S_INFO."
                )
            }
        }

        #[test]
        #[ignore]
        fn test_client_info_live() {
            // Live server I own
            let client = Client::new("54.186.150.6:9879").unwrap();
            let info: Result<Server, _> = client.info();
            if let Ok(_) = info {
            } else {
                assert!(
                    false,
                    "Target URL is real and live, but we got back an Err response for A2S_INFO."
                )
            }
        }
        #[test]
        #[ignore]
        fn test_client_players_live() {
            // Live server I own
            let client = Client::new("54.186.150.6:9879").unwrap();
            let players: Result<Vec<Player>, _> = client.players();
            if let Ok(_) = players {
            } else {
                assert!(
                    false,
                    "Target URL is real and live, but we got back an Err response for A2S_PLAYER."
                )
            }
        }
        #[test]
        #[ignore]
        fn test_client_rules_live() {
            // Live server I own
            let client = Client::new("54.186.150.6:9879").unwrap();
            let rules: Result<Rules, _> = client.rules();
            if let Ok(_) = rules {
            } else {
                assert!(
                    false,
                    "Target URL is real and live, but we got back an Err response for A2S_RULES."
                )
            }
        }
    }
}

pub mod utils {
    use crate::types::{get_byte, get_long, Byte, Long};

    pub fn get_multipacket_data(buffer: &[u8]) -> (Long, Byte, Byte) {
        let v = buffer.to_vec();
        let mut buffer_mut = v.iter();

        let _header = get_long(&mut buffer_mut);
        let answer_id = get_long(&mut buffer_mut);
        let total = get_byte(&mut buffer_mut);
        let packet_id = get_byte(&mut buffer_mut);

        (answer_id, total, packet_id)
    }

    pub fn compress_trailing_null_bytes(bytes: &mut Vec<u8>) {
        // No Size
        if bytes.len() == 0 || bytes.len() == 1 {
            return;
        }
        // No trailing null bytes
        if bytes.last().unwrap() != &0 {
            return;
        }

        // Remove trailing null bytes, then add one null byte
        let mut last = bytes.pop().unwrap();
        while last == 0 && bytes.len() > 0 {
            last = bytes.pop().unwrap();
        }
        bytes.push(last);
        bytes.push(0x00);
    }

    #[cfg(test)]
    mod tests {

        use super::*;

        #[test]
        fn test_compress_null_bytes_basic() {
            let mut bytes: Vec<u8> = vec![1, 2, 3, 0, 0, 0, 0];
            compress_trailing_null_bytes(&mut bytes);

            let result = bytes;
            let expected: Vec<u8> = vec![1, 2, 3, 0];

            assert_eq!(result, expected);
        }
        #[test]
        fn test_compress_null_bytes_with_no_trailing_zeroes() {
            let mut bytes: Vec<u8> = vec![1, 2, 3];
            compress_trailing_null_bytes(&mut bytes);

            let result = bytes;
            let expected: Vec<u8> = vec![1, 2, 3];

            assert_eq!(result, expected);
        }
        #[test]
        fn test_compress_null_bytes_with_one_trailing_zeroes() {
            let mut bytes: Vec<u8> = vec![1, 2, 3, 0];
            compress_trailing_null_bytes(&mut bytes);

            let result = bytes;
            let expected: Vec<u8> = vec![1, 2, 3, 0];

            assert_eq!(result, expected);
        }
        #[test]
        fn test_compress_null_bytes_with_empty_vector() {
            let mut bytes: Vec<u8> = vec![];
            compress_trailing_null_bytes(&mut bytes);

            let result = bytes;
            let expected: Vec<u8> = vec![];

            assert_eq!(result, expected);
        }
        #[test]
        fn test_compress_null_bytes_with_one_zero_as_vector() {
            let mut bytes: Vec<u8> = vec![0];
            compress_trailing_null_bytes(&mut bytes);

            let result = bytes;
            let expected: Vec<u8> = vec![0];

            assert_eq!(result, expected);
        }
    }
}