redis-asyncx 0.1.0

An asynchronous Redis client library and a Redis CLI built in Rust.
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
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Implements the [RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec)
//! serialization protocol for Redis client-server communication.

use crate::{RedisError, Result};
// use anyhow::Ok; // Removed as it conflicts with the Result type in your crate
use bytes::{Buf, Bytes, BytesMut};
use std::io::{BufRead, Cursor};

#[derive(Debug, PartialEq)]
pub struct BigInt {
    sign: bool,
    data: Vec<u8>,
}

/// Frame represents a single RESP data transmit unit over the socket.
///
/// more on the RESP protocol can be found [here](https://redis.io/topics/protocol)
#[derive(Debug, PartialEq)]
pub enum Frame {
    SimpleString(String),
    SimpleError(String),
    Integer(i64),
    BulkString(Bytes),
    Array(Vec<Frame>),
    Null,
    Boolean(bool),
    Double(f64),
    BigNumber(BigInt),
    BulkError(Bytes),
    // first: encoding, second: data payload
    VerbatimString(Bytes, Bytes),
    Map(Vec<(Frame, Frame)>),
    Attribute,
    Set(Vec<Frame>),
    Push,
}

impl Frame {
    /// Returns an empty Array Frame.
    pub const fn array() -> Self {
        Frame::Array(Vec::new())
    }

    /// A utility method to push a Frame into an Array/Set Frame.
    ///
    /// # Arguments
    ///
    /// * `frame` - A Frame to be pushed into the Array
    ///
    /// # Panics
    ///
    /// This method will panic if the Frame is not an Array or Set.
    pub fn push_frame_to_array(&mut self, frame: Frame) -> Result<()> {
        match self {
            Frame::Array(vec) => {
                vec.push(frame);
                Ok(())
            }
            Frame::Set(vec) => {
                vec.push(frame);
                Ok(())
            }
            _ => Err(RedisError::Unknown),
        }
    }

    /// A utility method to push a Frame into a Map Frame.
    ///
    /// # Arguments
    ///
    /// * `key` - A Frame to be used as a key in the Map
    /// * `value` - A Frame to be used as a value in the Map
    ///
    /// # Panics
    ///
    /// This method will panic if the Frame is not a Map.
    pub fn push_frame_to_map(&mut self, key: Frame, value: Frame) -> Result<()> {
        match self {
            Frame::Map(vec) => {
                vec.push((key, value));
                Ok(())
            }
            _ => Err(RedisError::Unknown),
        }
    }

    /// Serializes a Frame into a bytes buffer.
    ///
    /// The returned value is a smart pointer only counting reference. It is cheap to clone.
    /// Caller can get the underlying slice by calling `as_slice` or `as_ref` on the returned value.
    /// It is almost 0 cost to get the slice.
    ///
    /// # Returns
    ///
    /// A Result containing the serialized bytes buffer
    pub async fn serialize(&self) -> Result<Bytes> {
        match self {
            Frame::SimpleString(val) => {
                let mut buf = BytesMut::with_capacity(val.len() + 3);

                // + indicates it is a simple string
                buf.extend_from_slice(b"+");
                // encode the string value
                buf.extend_from_slice(val.as_bytes());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze()) // Ensure this uses the crate's Result type
            }
            Frame::SimpleError(val) => {
                let mut buf = BytesMut::with_capacity(val.len() + 3);

                // - indicates it is an error
                buf.extend_from_slice(b"-");
                // encode the error message
                buf.extend_from_slice(val.as_bytes());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::Integer(val) => {
                let mut buf = BytesMut::with_capacity(20);

                // : indicates it is an integer
                buf.extend_from_slice(b":");
                // encode the integer value
                buf.extend_from_slice(val.to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::BulkString(val) => {
                let mut buf = BytesMut::with_capacity(val.len() + 5);

                // $ indicates it is a bulk string
                buf.extend_from_slice(b"$");
                // encode the length of the binary string
                buf.extend_from_slice(val.len().to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");
                // encode the binary string
                buf.extend_from_slice(val.as_ref());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::Array(frame_vec) => {
                let mut buf = BytesMut::new();

                // * indicates it is an array
                buf.extend_from_slice(b"*");
                // encode the number of elements in the array
                buf.extend_from_slice(frame_vec.len().to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");

                // encode each element in the array
                for frame in frame_vec {
                    buf.extend_from_slice(&Box::pin(frame.serialize()).await?);
                }

                Ok(buf.freeze())
            }
            Frame::Null => {
                let mut buf = BytesMut::with_capacity(3);

                // _ indicates it is a null
                buf.extend_from_slice(b"_\r\n");

                Ok(buf.freeze())
            }
            Frame::Boolean(val) => {
                let mut buf: BytesMut = BytesMut::with_capacity(3);

                // # indicates it is a boolean
                buf.extend_from_slice(b"#");
                // encode the boolean value
                buf.extend_from_slice(if *val { b"t" } else { b"f" });
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::Double(val) => {
                let mut buf: BytesMut = BytesMut::with_capacity(20);

                // , indicates it is a double
                buf.extend_from_slice(b",");

                // encode the double value
                if val.is_nan() {
                    buf.extend_from_slice(b"nan");
                } else {
                    match *val {
                        f64::INFINITY => buf.extend_from_slice(b"inf"),
                        f64::NEG_INFINITY => buf.extend_from_slice(b"-inf"),
                        _ => {
                            buf.extend_from_slice(val.to_string().as_bytes());
                        }
                    }
                }

                // append \r\n to the end of the buffer
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::BigNumber(val) => {
                todo!("BigNumber serialization is not implemented yet {:?}", val)
            }
            Frame::BulkError(val) => {
                let mut buf = BytesMut::with_capacity(val.len() + 5);

                // ! indicates it is a bulk error
                buf.extend_from_slice(b"!");
                // encode the length of the binary string
                buf.extend_from_slice(val.len().to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");
                // encode the binary string
                buf.extend_from_slice(val.as_ref());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::VerbatimString(encoding, val) => {
                let mut buf: BytesMut = BytesMut::with_capacity(val.len() + 10);

                // = indicates it is a verbatim string
                buf.extend_from_slice(b"=");
                // encode the length of the binary string
                // +4 because encoding takes 3 bytes and : takes 1 byte
                buf.extend_from_slice((val.len() + 4).to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");
                // encode the encoding
                buf.extend_from_slice(encoding.as_ref());
                buf.extend_from_slice(b":");
                // encode the binary string
                buf.extend_from_slice(val.as_ref());
                buf.extend_from_slice(b"\r\n");

                Ok(buf.freeze())
            }
            Frame::Map(val) => {
                let mut buf: BytesMut = BytesMut::new();

                // % indicates it is a map
                buf.extend_from_slice(b"%");
                // encode the number of elements in the map
                buf.extend_from_slice(val.len().to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");

                // encode each element in the map
                for (key, value) in val {
                    buf.extend_from_slice(&Box::pin(key.serialize()).await?);
                    buf.extend_from_slice(&Box::pin(value.serialize()).await?);
                }

                Ok(buf.freeze())
            }
            Frame::Attribute => {
                todo!("Attribute serialization is not implemented yet")
            }
            Frame::Set(val) => {
                let mut buf: BytesMut = BytesMut::new();

                // ~ indicates it is a set
                buf.extend_from_slice(b"~");
                // encode the number of elements in the set
                buf.extend_from_slice(val.len().to_string().as_bytes());
                buf.extend_from_slice(b"\r\n");

                // encode each element in the set
                for frame in val {
                    buf.extend_from_slice(&Box::pin(frame.serialize()).await?);
                }

                Ok(buf.freeze())
            }
            Frame::Push => {
                todo!("Push serialization is not implemented yet")
            }
        }
    }

    /// Deserializes from the buffer into a Frame.
    ///
    /// The method reads from the buffer and parses it into a Frame.
    ///
    /// # Arguments
    ///
    /// * `buf` - An immutable read buffer containing the serialized Frame
    ///
    /// # Returns
    ///
    /// A Result containing the deserialized Frame
    pub async fn deserialize(buf: Bytes) -> Result<Frame> {
        // the cursor is almost zero cost as it is just a smart ptr to the buffer
        Frame::try_parse(&mut Cursor::new(&buf[..]))
    }

    /// Tries parsing a Frame from the buffer.
    ///
    /// This method wraps the input with a cursor to track the current version as we need to make resursive calls.
    /// Using a cursor avoids the need to split the buffer or passing an additional parameter.
    ///
    /// # Returns
    ///
    /// * `Ok(usize)` if the buffer contains a complete frame, the number of bytes needed to parse the frame
    /// * `Err(RedisError::IncompleteFrame)` if the buffer contains an incomplete frame
    /// * `Err(RedisError::InvalidFrame)` if the buffer contains an invalid frame
    pub fn try_parse(cursor: &mut Cursor<&[u8]>) -> Result<Frame> {
        if !cursor.has_remaining() {
            return Err(RedisError::IncompleteFrame);
        }

        match cursor.get_u8() {
            b'+' => {
                // Simple string
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                if buf.ends_with("\r\n") {
                    Ok(Frame::SimpleString(
                        buf.trim_end_matches("\r\n").to_string(),
                    ))
                } else {
                    // fixme: there maybe edge cases here
                    // we need to guarantee there's no more \r\n in the buffer
                    Err(RedisError::IncompleteFrame)
                }
            }
            b'-' => {
                // Simple error
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                if buf.ends_with("\r\n") {
                    Ok(Frame::SimpleError(buf.trim_end_matches("\r\n").to_string()))
                } else {
                    // fixme: there maybe edge cases here
                    // we need to guarantee there's no more \r\n in the buffer
                    Err(RedisError::IncompleteFrame)
                }
            }
            b':' => {
                // Integer
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                // todo: check whether it is a valid integer
                if buf.ends_with("\r\n") {
                    Ok(Frame::Integer(
                        buf.trim_end_matches("\r\n").parse::<i64>().unwrap(),
                    ))
                } else {
                    Err(RedisError::IncompleteFrame)
                }
            }
            b'$' => {
                // Bulk string
                let mut buf = String::new();
                // read the length of the bulk string
                let _ = cursor.read_line(&mut buf).unwrap();

                if !buf.ends_with("\r\n") {
                    return Err(RedisError::IncompleteFrame);
                }

                let len: isize = buf.trim_end_matches("\r\n").parse::<isize>().unwrap();

                // for RESP2, -1 indicates a null bulk string
                if len == -1 {
                    return Ok(Frame::Null);
                }

                // +2 because \r\n
                if cursor.remaining() < len as usize + 2 {
                    return Err(RedisError::IncompleteFrame);
                }

                let data = Bytes::copy_from_slice(&cursor.chunk()[..len as usize]);

                // advance cursor
                cursor.advance(len as usize + 2);

                Ok(Frame::BulkString(data))
            }
            b'*' => {
                // Array
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                let len = buf.trim_end_matches("\r\n").parse::<usize>().unwrap();
                let mut frame_vec: Vec<_> = Vec::with_capacity(len);

                for _ in 0..len {
                    frame_vec.push(Frame::try_parse(cursor)?);
                }

                Ok(Frame::Array(frame_vec))
            }
            b'_' => Ok(Frame::Null),
            b'#' => {
                // Boolean
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                if buf.ends_with("\r\n") {
                    let val = buf.trim_end_matches("\r\n");
                    if val == "t" {
                        Ok(Frame::Boolean(true))
                    } else if val == "f" {
                        Ok(Frame::Boolean(false))
                    } else {
                        Err(RedisError::InvalidFrame)
                    }
                } else {
                    Err(RedisError::IncompleteFrame)
                }
            }
            b',' => {
                // Double
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                if buf.ends_with("\r\n") {
                    let val = buf.trim_end_matches("\r\n");
                    if val == "nan" {
                        Ok(Frame::Double(f64::NAN))
                    } else if val == "inf" {
                        Ok(Frame::Double(f64::INFINITY))
                    } else if val == "-inf" {
                        Ok(Frame::Double(f64::NEG_INFINITY))
                    } else {
                        Ok(Frame::Double(val.parse::<f64>().unwrap()))
                    }
                } else {
                    Err(RedisError::IncompleteFrame)
                }
            }
            b'(' => {
                // Big number
                todo!("Big number deserialization is not implemented yet")
            }
            b'!' => {
                // Bulk error
                let mut buf = String::new();
                // read the length of the bulk string
                let _ = cursor.read_line(&mut buf).unwrap();

                if !buf.ends_with("\r\n") {
                    return Err(RedisError::IncompleteFrame);
                }

                let len: isize = buf.trim_end_matches("\r\n").parse::<isize>().unwrap();

                // for RESP2, -1 indicates a null bulk error
                if len == -1 {
                    return Ok(Frame::Null);
                }

                let len: usize = len.try_into().unwrap();

                // +2 because \r\n
                if cursor.remaining() < len + 2 {
                    return Err(RedisError::IncompleteFrame);
                }

                // check if cursor ends with \r\n
                if cursor.chunk()[len] != b'\r' || cursor.chunk()[len + 1] != b'\n' {
                    return Err(RedisError::InvalidFrame);
                }

                let data = Bytes::copy_from_slice(&cursor.chunk()[..len]);

                // advance cursor
                cursor.advance(len + 2);

                Ok(Frame::BulkError(data))
            }
            b'=' => {
                // Verbatim string
                let mut buf = String::new();
                // read the length of the bulk string
                let _ = cursor.read_line(&mut buf).unwrap();

                if !buf.ends_with("\r\n") {
                    return Err(RedisError::IncompleteFrame);
                }

                let len: usize = buf.trim_end_matches("\r\n").parse::<usize>().unwrap();

                // +2 for \r\n
                if cursor.remaining() < len + 2 {
                    return Err(RedisError::IncompleteFrame);
                }

                // check if cursor ends with \r\n
                if !cursor.chunk()[len..].starts_with(b"\r\n") {
                    return Err(RedisError::InvalidFrame);
                }

                // read the encoding
                let mut data = Bytes::copy_from_slice(&cursor.chunk()[..len]);

                // split data into encoding and value, : as the delimiter
                let encoding: Bytes = data.split_to(3);

                // data[0] is b':', ignore it
                data.advance(1);

                // advance cursor
                cursor.advance(len + 2);

                Ok(Frame::VerbatimString(encoding, data))
            }
            b'%' => {
                // Map
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                let len = buf.trim_end_matches("\r\n").parse::<usize>().unwrap();
                let mut frame_vec: Vec<_> = Vec::with_capacity(len);

                for _ in 0..len {
                    let key = Frame::try_parse(cursor)?;
                    let value = Frame::try_parse(cursor)?;
                    frame_vec.push((key, value));
                }

                Ok(Frame::Map(frame_vec))
            }
            b'&' => {
                // Attribute
                todo!("Attribute deserialization is not implemented yet")
            }
            b'~' => {
                // Set
                let mut buf = String::new();
                let _ = cursor.read_line(&mut buf).unwrap();

                let len = buf.trim_end_matches("\r\n").parse::<usize>().unwrap();
                let mut frame_vec: Vec<_> = Vec::with_capacity(len);

                for _ in 0..len {
                    frame_vec.push(Frame::try_parse(cursor)?);
                }

                Ok(Frame::Set(frame_vec))
            }
            b'>' => {
                // Push
                todo!("Push deserialization is not implemented yet")
            }
            _ => Err(RedisError::InvalidFrame),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests the serialization of a simple string frame.
    #[tokio::test]
    async fn test_serialize_simple_string() {
        let frame = Frame::SimpleString("OK".to_string());
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"+OK\r\n"));
    }

    /// Tests the serialization of a simple error frame.
    #[tokio::test]
    async fn test_serialize_simple_error() {
        let frame = Frame::SimpleError("ERR".to_string());
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"-ERR\r\n"));
    }

    /// Tests the serialization of an integer frame.
    #[tokio::test]
    async fn test_serialize_integer() {
        // positive integer
        let frame = Frame::Integer(123_i64);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b":123\r\n"));

        // negative integer
        let frame = Frame::Integer(-123_i64);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b":-123\r\n"));
    }

    /// Tests the serialization of a bulk string frame.
    #[tokio::test]
    async fn test_serialize_bulk_string() {
        let frame = Frame::BulkString(Bytes::from_static(b"Hello Redis"));
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"$11\r\nHello Redis\r\n"));

        // empty bulk string
        let frame = Frame::BulkString(Bytes::from_static(b""));
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"$0\r\n\r\n"));
    }

    /// Tests the serailization of an array frame.
    #[tokio::test]
    async fn test_serialize_array() {
        let mut frame = Frame::array();
        frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        let bytes = frame.serialize().await.unwrap();

        assert_eq!(
            bytes,
            Bytes::from_static(b"*2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n")
        );

        // empty array
        let frame = Frame::array();
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"*0\r\n"));

        // nested array
        let mut frame: Frame = Frame::array();
        let mut nested_frame = Frame::array();
        nested_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        nested_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        if let Frame::Array(vec) = &mut frame {
            vec.push(nested_frame);
        }

        let bytes = frame.serialize().await.unwrap();

        assert_eq!(
            bytes,
            Bytes::from_static(b"*1\r\n*2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n")
        );
    }

    /// Tests the serialization of a null frame.
    #[tokio::test]
    async fn test_serialize_null() {
        let frame = Frame::Null;
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"_\r\n"));
    }

    /// Tests the serialization of a boolean frame.
    #[tokio::test]
    async fn test_serialize_boolean() {
        let frame = Frame::Boolean(true);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"#t\r\n"));

        let frame = Frame::Boolean(false);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"#f\r\n"));
    }

    // Tests the serialization of a double frame.
    #[tokio::test]
    async fn test_serialize_double() {
        let frame = Frame::Double(123.456);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b",123.456\r\n"));

        let frame = Frame::Double(f64::NAN);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b",nan\r\n"));

        let frame = Frame::Double(f64::INFINITY);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b",inf\r\n"));

        let frame = Frame::Double(f64::NEG_INFINITY);
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b",-inf\r\n"));
    }

    /// Tests the serialization of a bulk error frame.
    #[tokio::test]
    async fn test_serialize_bulk_error() {
        let frame = Frame::BulkError(Bytes::from_static(b"Hello Redis"));
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"!11\r\nHello Redis\r\n"));

        // empty bulk error
        let frame = Frame::BulkError(Bytes::from_static(b""));
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"!0\r\n\r\n"));
    }

    /// Tests the serialization of a verbatim string frame.
    #[tokio::test]
    async fn test_serialize_verbatim_string() {
        let frame = Frame::VerbatimString(
            Bytes::from_static(b"txt"),
            Bytes::from_static(b"Some string"),
        );
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"=15\r\ntxt:Some string\r\n"));

        // empty verbatim string
        let frame = Frame::VerbatimString(Bytes::from_static(b"txt"), Bytes::from_static(b""));
        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"=4\r\ntxt:\r\n"));
    }

    /// Tests the serialization of a map frame.
    #[tokio::test]
    async fn test_serialize_map() {
        let mut frame: Frame = Frame::Map(Vec::new());
        frame
            .push_frame_to_map(
                Frame::SimpleString("key".to_string()),
                Frame::SimpleString("value".to_string()),
            )
            .unwrap();

        let bytes = frame.serialize().await.unwrap();

        assert_eq!(bytes, Bytes::from_static(b"%1\r\n+key\r\n+value\r\n"));
    }

    /// Tests the serialization of a set frame.
    #[tokio::test]
    async fn test_serialize_set() {
        let mut frame: Frame = Frame::Set(Vec::new());
        frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        let bytes = frame.serialize().await.unwrap();

        assert_eq!(
            bytes,
            Bytes::from_static(b"~2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n")
        );
    }

    /// Tests the deserialization of a simple string frame.
    #[tokio::test]
    async fn test_deserialize_simple_string() {
        let bytes = Bytes::from_static(b"+OK\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::SimpleString("OK".to_string()));
    }

    /// Tests the deserialization of a simple error frame.
    #[tokio::test]
    async fn test_deserialize_simple_error() {
        let bytes = Bytes::from_static(b"-ERR\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::SimpleError("ERR".to_string()));
    }

    /// Tests the deserialization of an integer frame.
    #[tokio::test]
    async fn test_deserialize_integer() {
        // positive integer
        let bytes = Bytes::from_static(b":123\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Integer(123_i64));

        // negative integer
        let bytes = Bytes::from_static(b":-123\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Integer(-123_i64));
    }

    /// Tests the deserialization of a bulk string frame.
    #[tokio::test]
    async fn test_deserialize_bulk_string() {
        let bytes = Bytes::from_static(b"$11\r\nHello Redis\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::BulkString(Bytes::from_static(b"Hello Redis")));

        let bytes = Bytes::from_static(b"$0\r\n\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::BulkString(Bytes::from_static(b"")));
    }

    /// Tests deseaialization of an array frame.
    #[tokio::test]
    async fn test_deserialize_array() {
        let bytes = Bytes::from_static(b"*2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        let mut expected_frame = Frame::array();
        expected_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        expected_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        assert_eq!(frame, expected_frame);

        // empty array
        let bytes = Bytes::from_static(b"*0\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::array());

        // nested array
        let bytes = Bytes::from_static(b"*1\r\n*2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        let mut expected_frame = Frame::array();
        let mut nested_frame = Frame::array();
        nested_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        nested_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        expected_frame.push_frame_to_array(nested_frame).unwrap();

        assert_eq!(frame, expected_frame);
    }

    /// Tests the deserialization of a null frame.
    #[tokio::test]
    async fn test_deserialize_null() {
        let bytes = Bytes::from_static(b"_\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Null);
    }

    /// Tests the deserialization of a boolean frame.
    #[tokio::test]
    async fn test_deserialize_boolean() {
        let bytes = Bytes::from_static(b"#t\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Boolean(true));

        let bytes = Bytes::from_static(b"#f\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Boolean(false));
    }

    /// Tests the deserialization of a double frame.
    #[tokio::test]
    async fn test_deserialize_double() {
        let bytes = Bytes::from_static(b",123.456\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Double(123.456));

        let bytes = Bytes::from_static(b",nan\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        if let Frame::Double(val) = frame {
            assert!(val.is_nan());
        } else {
            panic!("Expected a Double frame");
        }

        let bytes = Bytes::from_static(b",inf\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Double(f64::INFINITY));

        let bytes = Bytes::from_static(b",-inf\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::Double(f64::NEG_INFINITY));
    }

    /// Tests the deserialization of a bulk error frame.
    #[tokio::test]
    async fn test_deserialize_bulk_error() {
        let bytes = Bytes::from_static(b"!11\r\nHello Redis\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::BulkError(Bytes::from_static(b"Hello Redis")));

        let bytes = Bytes::from_static(b"!0\r\n\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(frame, Frame::BulkError(Bytes::from_static(b"")));
    }

    /// Tests the deserialization of a verbatim string frame.
    #[tokio::test]
    async fn test_deserialize_verbatim_string() {
        let bytes = Bytes::from_static(b"=15\r\ntxt:Some string\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(
            frame,
            Frame::VerbatimString(
                Bytes::from_static(b"txt"),
                Bytes::from_static(b"Some string")
            )
        );

        let bytes = Bytes::from_static(b"=4\r\ntxt:\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        assert_eq!(
            frame,
            Frame::VerbatimString(Bytes::from_static(b"txt"), Bytes::from_static(b""))
        );
    }

    /// Tests the deserialization of a map frame.
    #[tokio::test]
    async fn test_deserialize_map() {
        let bytes = Bytes::from_static(b"%1\r\n+key\r\n+value\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        let mut expected_frame = Frame::Map(Vec::new());
        expected_frame
            .push_frame_to_map(
                Frame::SimpleString("key".to_string()),
                Frame::SimpleString("value".to_string()),
            )
            .unwrap();

        assert_eq!(frame, expected_frame);
    }

    /// Tests the deserialization of a set frame.
    #[tokio::test]
    async fn test_deserialize_set() {
        let bytes = Bytes::from_static(b"~2\r\n$5\r\nHello\r\n$5\r\nRedis\r\n");

        let frame = Frame::deserialize(bytes).await.unwrap();

        let mut expected_frame = Frame::Set(Vec::new());
        expected_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Hello")))
            .unwrap();
        expected_frame
            .push_frame_to_array(Frame::BulkString(Bytes::from_static(b"Redis")))
            .unwrap();

        assert_eq!(frame, expected_frame);
    }
}