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
use crate::{
    prepare_command,
    resp::{
        cmd, BulkString, CommandArgs, FromSingleValueArray, FromValue, IntoArgs,
        SingleArgOrCollection, Value,
    },
    Error, PreparedCommand, Result,
};

/// A group of generic Redis commands
///
/// # See Also
/// [Redis Generic Commands](https://redis.io/commands/?group=generic)
pub trait GenericCommands {
    /// This command copies the value stored at the source key to the destination key.
    ///
    /// # Return
    /// Success of the operation
    ///
    /// # See Also
    /// [<https://redis.io/commands/copy/>](https://redis.io/commands/copy/)
    #[must_use]
    fn copy<S, D>(
        &mut self,
        source: S,
        destination: D,
        destination_db: Option<usize>,
        replace: bool,
    ) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        S: Into<BulkString>,
        D: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("COPY")
                .arg(source)
                .arg(destination)
                .arg(destination_db.map(|db| ("DB", db)))
                .arg_if(replace, "REPLACE"),
        )
    }

    /// Removes the specified keys. A key is ignored if it does not exist.
    ///
    /// # Return
    /// The number of keys that were removed.
    ///
    /// # See Also
    /// [<https://redis.io/commands/del/>](https://redis.io/commands/del/)
    #[must_use]
    fn del<K, C>(&mut self, keys: C) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
        K: Into<BulkString>,
        C: SingleArgOrCollection<K>,
    {
        prepare_command(self, cmd("DEL").arg(keys))
    }

    /// Serialize the value stored at key in a Redis-specific format and return it to the user.
    ///
    /// # Return
    /// The serialized value.
    ///
    /// # See Also
    /// [<https://redis.io/commands/dump/>](https://redis.io/commands/dump/)
    #[must_use]
    fn dump<K>(&mut self, key: K) -> PreparedCommand<Self, DumpResult>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("DUMP").arg(key))
    }

    /// Returns if keys exist.
    ///
    /// # Return
    /// The number of keys that exist from those specified as arguments.
    ///
    /// # See Also
    /// [<https://redis.io/commands/exists/>](https://redis.io/commands/exists/)
    #[must_use]
    fn exists<K, C>(&mut self, keys: C) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
        K: Into<BulkString>,
        C: SingleArgOrCollection<K>,
    {
        prepare_command(self, cmd("EXISTS").arg(keys))
    }

    /// Set a timeout on key in seconds
    ///
    /// # Return
    /// * `true` - if the timeout was set.
    /// * `false` - if the timeout was not set. e.g. key doesn't exist, or operation skipped due to the provided arguments.
    ///
    /// # See Also
    /// [<https://redis.io/commands/expire/>](https://redis.io/commands/expire/)
    #[must_use]
    fn expire<K>(
        &mut self,
        key: K,
        seconds: u64,
        option: ExpireOption,
    ) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("EXPIRE").arg(key).arg(seconds).arg(option))
    }

    /// EXPIREAT has the same effect and semantic as EXPIRE,
    /// but instead of specifying the number of seconds representing the TTL (time to live),
    /// it takes an absolute Unix timestamp (seconds since January 1, 1970)
    ///
    /// A timestamp in the past will delete the key
    ///
    /// # Return
    /// * `true` - if the timeout was set.
    /// * `false` - if the timeout was not set. e.g. key doesn't exist, or operation skipped due to the provided arguments.
    ///
    /// # See Also
    /// [<https://redis.io/commands/expireat/>](https://redis.io/commands/expireat/)
    #[must_use]
    fn expireat<K>(
        &mut self,
        key: K,
        unix_time_seconds: u64,
        option: ExpireOption,
    ) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("EXPIREAT").arg(key).arg(unix_time_seconds).arg(option),
        )
    }

    /// Returns the absolute Unix timestamp (since January 1, 1970) in seconds at which the given key will expire.
    ///
    /// # Return
    /// Expiration Unix timestamp in seconds, or a negative value in order to signal an error (see the description below).
    /// - The command returns -1 if the key exists but has no associated expiration time.
    /// - The command returns -2 if the key does not exist.
    ///
    /// # See Also
    /// [<https://redis.io/commands/expiretime/>](https://redis.io/commands/expiretime/)
    #[must_use]
    fn expiretime<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("EXPIRETIME").arg(key))
    }

    /// Returns all keys matching pattern.
    ///
    /// # Return
    /// list of keys matching pattern.
    ///
    /// # See Also
    /// [<https://redis.io/commands/keys/>](https://redis.io/commands/keys/)
    #[must_use]
    fn keys<P, K, A>(&mut self, pattern: P) -> PreparedCommand<Self, A>
    where
        Self: Sized,
        P: Into<BulkString>,
        K: FromValue,
        A: FromSingleValueArray<K>,
    {
        prepare_command(self, cmd("KEYS").arg(pattern))
    }

    /// Atomically transfer a key or a collection of keys from a source Redis instance to a destination Redis instance.
    ///
    /// # Return
    /// * `true` - on success
    /// * `false` - if no keys were found in the source instance.
    ///
    /// # See Also
    /// [<https://redis.io/commands/migrate/>](https://redis.io/commands/migrate/)
    #[must_use]
    fn migrate<H, K>(
        &mut self,
        host: H,
        port: u16,
        key: K,
        destination_db: usize,
        timeout: u64,
        options: MigrateOptions,
    ) -> PreparedCommand<Self, MigrateResult>
    where
        Self: Sized,
        H: Into<BulkString>,
        K: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("MIGRATE")
                .arg(host)
                .arg(port)
                .arg(key)
                .arg(destination_db)
                .arg(timeout)
                .arg(options),
        )
    }

    /// Move key from the currently selected database to the specified destination database.
    ///
    /// # Return
    /// * `true` - if key was moved.
    /// * `false` - f key was not moved.
    ///
    /// # See Also
    /// [<https://redis.io/commands/move/>](https://redis.io/commands/move/)
    #[must_use]
    fn move_<K>(&mut self, key: K, db: usize) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("MOVE").arg(key).arg(db))
    }

    /// Returns the internal encoding for the Redis object stored at `key`
    ///
    /// # Return
    /// The encoding of the object, or nil if the key doesn't exist
    ///
    /// # See Also
    /// [<https://redis.io/commands/object-encoding/>](https://redis.io/commands/object-encoding/)
    #[must_use]
    fn object_encoding<K, E>(&mut self, key: K) -> PreparedCommand<Self, E>
    where
        Self: Sized,
        K: Into<BulkString>,
        E: FromValue,
    {
        prepare_command(self, cmd("OBJECT").arg("ENCODING").arg(key))
    }

    /// This command returns the logarithmic access frequency counter of a Redis object stored at `key`.
    ///
    /// # Return
    /// The counter's value.
    ///
    /// # See Also
    /// [<https://redis.io/commands/object-freq/>](https://redis.io/commands/object-freq/)
    #[must_use]
    fn object_freq<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("OBJECT").arg("FREQ").arg(key))
    }

    /// This command returns the time in seconds since the last access to the value stored at `key`.
    ///
    /// # Return
    /// The idle time in seconds.
    ///
    /// # See Also
    /// [<https://redis.io/commands/object-idletime/>](https://redis.io/commands/object-idletime/)
    #[must_use]
    fn object_idle_time<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("OBJECT").arg("IDLETIME").arg(key))
    }

    /// This command returns the reference count of the stored at `key`.
    ///
    /// # Return
    /// The number of references.
    ///
    /// # See Also
    /// [<https://redis.io/commands/object-refcount/>](https://redis.io/commands/object-refcount/)
    #[must_use]
    fn object_refcount<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("OBJECT").arg("REFCOUNT").arg(key))
    }

    /// Remove the existing timeout on key,
    /// turning the key from volatile (a key with an expire set)
    /// to persistent (a key that will never expire as no timeout is associated).
    ///
    /// # Return
    /// * `true` - if the timeout was removed.
    /// * `false` - if key does not exist or does not have an associated timeout.
    ///
    /// # See Also
    /// [<https://redis.io/commands/persist/>](https://redis.io/commands/persist/)
    #[must_use]
    fn persist<K>(&mut self, key: K) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("PERSIST").arg(key))
    }

    /// This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.
    ///
    /// # Return
    /// * `true` - if the timeout was set.
    /// * `false` - if the timeout was not set. e.g. key doesn't exist, or operation skipped due to the provided arguments.
    ///
    /// # See Also
    /// [<https://redis.io/commands/pexpire/>](https://redis.io/commands/pexpire/)
    #[must_use]
    fn pexpire<K>(
        &mut self,
        key: K,
        milliseconds: u64,
        option: ExpireOption,
    ) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("PEXPIRE").arg(key).arg(milliseconds).arg(option))
    }

    /// PEXPIREAT has the same effect and semantic as EXPIREAT,
    /// but the Unix time at which the key will expire is specified in milliseconds instead of seconds.
    ///
    /// # Return
    /// * `true` - if the timeout was set.
    /// * `false` - if the timeout was not set. e.g. key doesn't exist, or operation skipped due to the provided arguments.
    ///
    /// # See Also
    /// [<https://redis.io/commands/pexpireat/>](https://redis.io/commands/pexpireat/)
    #[must_use]
    fn pexpireat<K>(
        &mut self,
        key: K,
        unix_time_milliseconds: u64,
        option: ExpireOption,
    ) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("PEXPIREAT")
                .arg(key)
                .arg(unix_time_milliseconds)
                .arg(option),
        )
    }

    /// PEXPIRETIME has the same semantic as EXPIRETIME,
    /// but returns the absolute Unix expiration timestamp in milliseconds instead of seconds.
    ///
    /// # Return
    ///  Expiration Unix timestamp in milliseconds, or a negative value in order to signal an error (see the description below).
    /// - The command returns -1 if the key exists but has no associated expiration time.
    /// - The command returns -2 if the key does not exist.
    ///
    /// # See Also
    /// [<https://redis.io/commands/pexpiretime/>](https://redis.io/commands/pexpiretime/)
    #[must_use]
    fn pexpiretime<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("PEXPIRETIME").arg(key))
    }

    /// Returns the remaining time to live of a key that has a timeout.
    ///
    /// # Return
    /// TTL in milliseconds, or a negative value in order to signal an error:
    /// -2 if the key does not exist.
    /// -1 if the key exists but has no associated expire.
    ///
    /// # See Also
    /// [<https://redis.io/commands/pttl/>](https://redis.io/commands/pttl/)
    #[must_use]
    fn pttl<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("PTTL").arg(key))
    }

    /// Return a random key from the currently selected database.
    ///
    /// # Return
    /// The number of references.
    ///
    /// # See Also
    /// [<https://redis.io/commands/randomkey/>](https://redis.io/commands/randomkey/)
    #[must_use]
    fn randomkey<R>(&mut self) -> PreparedCommand<Self, R>
    where
        Self: Sized,
        R: FromValue,
    {
        prepare_command(self, cmd("RANDOMKEY"))
    }

    /// Renames key to newkey.
    ///
    /// # See Also
    /// [<https://redis.io/commands/rename/>](https://redis.io/commands/rename/)
    #[must_use]
    fn rename<K1, K2>(&mut self, key: K1, new_key: K2) -> PreparedCommand<Self, ()>
    where
        Self: Sized,
        K1: Into<BulkString>,
        K2: Into<BulkString>,
    {
        prepare_command(self, cmd("RENAME").arg(key).arg(new_key))
    }

    /// Renames key to newkey if newkey does not yet exist.
    /// It returns an error when key does not exist.
    ///
    /// # Return
    /// * `true` if key was renamed to newkey.
    /// * `false` if newkey already exists.
    /// # See Also
    /// [<https://redis.io/commands/renamenx/>](https://redis.io/commands/renamenx/)
    #[must_use]
    fn renamenx<K1, K2>(&mut self, key: K1, new_key: K2) -> PreparedCommand<Self, bool>
    where
        Self: Sized,
        K1: Into<BulkString>,
        K2: Into<BulkString>,
    {
        prepare_command(self, cmd("RENAMENX").arg(key).arg(new_key))
    }

    /// Create a key associated with a value that is obtained by deserializing
    /// the provided serialized value (obtained via DUMP).
    ///
    /// # Return
    /// Restore command builder
    ///
    /// # See Also
    /// [<https://redis.io/commands/restore/>](https://redis.io/commands/restore/)
    #[must_use]
    fn restore<K>(
        &mut self,
        key: K,
        ttl: u64,
        serialized_value: Vec<u8>,
        options: RestoreOptions,
    ) -> PreparedCommand<Self, ()>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("RESTORE")
                .arg(key)
                .arg(ttl)
                .arg(BulkString::Binary(serialized_value))
                .arg(options),
        )
    }

    /// Iterates the set of keys in the currently selected Redis database.
    ///
    /// # Return
    /// A list of keys
    ///
    /// # See Also
    /// [<https://redis.io/commands/scan/>](https://redis.io/commands/scan/)
    #[must_use]
    fn scan<K, A>(&mut self, cursor: u64, options: ScanOptions) -> PreparedCommand<Self, (u64, A)>
    where
        Self: Sized,
        K: FromValue,
        A: FromSingleValueArray<K>,
    {
        prepare_command(self, cmd("SCAN").arg(cursor).arg(options))
    }

    /// Returns the elements contained in the list, set or sorted set at key.
    ///
    /// # Return
    /// A collection of sorted elements.
    ///
    /// # See Also
    /// [<https://redis.io/commands/sort/>](https://redis.io/commands/sort/)
    #[must_use]
    fn sort<K, M, A>(&mut self, key: K, options: SortOptions) -> PreparedCommand<Self, A>
    where
        Self: Sized,
        K: Into<BulkString>,
        M: FromValue,
        A: FromSingleValueArray<M>,
    {
        prepare_command(self, cmd("SORT").arg(key).arg(options))
    }

    /// Stores the elements contained in the list, set or sorted set at key.
    ///
    /// # Return
    /// The number of sorted elements in the destination list.
    ///
    /// # See Also
    /// [<https://redis.io/commands/sort/>](https://redis.io/commands/sort/)
    #[must_use]
    fn sort_and_store<K, D>(
        &mut self,
        key: K,
        destination: D,
        options: SortOptions,
    ) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
        K: Into<BulkString>,
        D: Into<BulkString>,
    {
        prepare_command(
            self,
            cmd("SORT")
                .arg(key)
                .arg(options)
                .arg("STORE")
                .arg(destination),
        )
    }

    /// Read-only variant of the SORT command.
    ///
    /// It is exactly like the original SORT but refuses the STORE option
    /// and can safely be used in read-only replicas.
    ///
    /// # Return
    /// A collection of sorted elements.
    ///
    /// # See Also
    /// [<https://redis.io/commands/sort_ro/>](https://redis.io/commands/sort_ro/)
    #[must_use]
    fn sort_readonly<K, M, A>(&mut self, key: K, options: SortOptions) -> PreparedCommand<Self, A>
    where
        Self: Sized,
        K: Into<BulkString>,
        M: FromValue,
        A: FromSingleValueArray<M>,
    {
        prepare_command(self, cmd("SORT_RO").arg(key).arg(options))
    }

    /// Alters the last access time of a key(s). A key is ignored if it does not exist.
    ///
    /// # Return
    /// The number of keys that were touched.
    ///
    /// # See Also
    /// [<https://redis.io/commands/touch/>](https://redis.io/commands/touch/)
    #[must_use]
    fn touch<K, KK>(&mut self, keys: KK) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
        K: Into<BulkString>,
        KK: SingleArgOrCollection<K>,
    {
        prepare_command(self, cmd("TOUCH").arg(keys))
    }

    /// Returns the remaining time to live of a key that has a timeout.
    ///
    /// # Return
    /// TTL in seconds, or a negative value in order to signal an error:
    /// -2 if the key does not exist.
    /// -1 if the key exists but has no associated expire.
    ///
    /// # See Also
    /// [<https://redis.io/commands/ttl/>](https://redis.io/commands/ttl/)
    #[must_use]
    fn ttl<K>(&mut self, key: K) -> PreparedCommand<Self, i64>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("TTL").arg(key))
    }

    /// Returns the string representation of the type of the value stored at key.
    ///
    /// The different types that can be returned are: string, list, set, zset, hash and stream.
    ///
    /// # Return
    /// type of key, or empty string when key does not exist.
    ///
    /// # See Also
    /// [<https://redis.io/commands/type/>](https://redis.io/commands/type/)
    #[must_use]
    fn type_<K>(&mut self, key: K) -> PreparedCommand<Self, String>
    where
        Self: Sized,
        K: Into<BulkString>,
    {
        prepare_command(self, cmd("TYPE").arg(key))
    }

    /// This command is very similar to DEL: it removes the specified keys.
    ///
    /// # Return
    /// The number of keys that were unlinked.
    ///
    /// # See Also
    /// [<https://redis.io/commands/unlink/>](https://redis.io/commands/unlink/)
    #[must_use]
    fn unlink<K, C>(&mut self, keys: C) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
        K: Into<BulkString>,
        C: SingleArgOrCollection<K>,
    {
        prepare_command(self, cmd("UNLINK").arg(keys))
    }

    /// This command blocks the current client until all the previous write commands are
    /// successfully transferred and acknowledged by at least the specified number of replicas.
    ///
    /// # Return
    /// The number of replicas reached by all the writes performed in the context of the current connection.
    ///
    /// # See Also
    /// [<https://redis.io/commands/wait/>](https://redis.io/commands/wait/)
    #[must_use]
    fn wait(&mut self, num_replicas: usize, timeout: u64) -> PreparedCommand<Self, usize>
    where
        Self: Sized,
    {
        prepare_command(self, cmd("WAIT").arg(num_replicas).arg(timeout))
    }
}

/// Options for the [expire](crate::GenericCommands::expire) command
pub enum ExpireOption {
    /// No option
    None,
    /// Set expiry only when the key has no expiry
    Nx,
    /// Set expiry only when the key has no expiry    
    Xx,
    /// Set expiry only when the new expiry is greater than current one
    Gt,
    /// Set expiry only when the new expiry is less than current one
    Lt,
}

impl Default for ExpireOption {
    fn default() -> Self {
        ExpireOption::None
    }
}

impl IntoArgs for ExpireOption {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        match self {
            ExpireOption::None => args,
            ExpireOption::Nx => args.arg("NX"),
            ExpireOption::Xx => args.arg("XX"),
            ExpireOption::Gt => args.arg("GT"),
            ExpireOption::Lt => args.arg("LT"),
        }
    }
}

#[derive(Default)]
pub struct MigrateOptions {
    command_args: CommandArgs,
}

impl MigrateOptions {
    #[must_use]
    pub fn copy(self) -> Self {
        Self {
            command_args: self.command_args.arg("COPY"),
        }
    }

    #[must_use]
    pub fn replace(self) -> Self {
        Self {
            command_args: self.command_args.arg("REPLACE"),
        }
    }

    #[must_use]
    pub fn auth<P: Into<BulkString>>(self, password: P) -> Self {
        Self {
            command_args: self.command_args.arg("AUTH").arg(password),
        }
    }

    #[must_use]
    pub fn auth2<U: Into<BulkString>, P: Into<BulkString>>(self, username: U, password: P) -> Self {
        Self {
            command_args: self.command_args.arg("AUTH2").arg(username).arg(password),
        }
    }

    #[must_use]
    pub fn keys<K: Into<BulkString>, KK: SingleArgOrCollection<K>>(self, keys: KK) -> Self {
        Self {
            command_args: self.command_args.arg("KEYS").arg(keys),
        }
    }
}

impl IntoArgs for MigrateOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Options for the [`restore`](crate::GenericCommands::restore) command
#[derive(Default)]
pub struct RestoreOptions {
    command_args: CommandArgs,
}

impl RestoreOptions {
    #[must_use]
    pub fn replace(self) -> Self {
        Self {
            command_args: self.command_args.arg("REPLACE"),
        }
    }

    #[must_use]
    pub fn abs_ttl(self) -> Self {
        Self {
            command_args: self.command_args.arg("ABSTTL"),
        }
    }

    #[must_use]
    pub fn idle_time(self, idle_time: i64) -> Self {
        Self {
            command_args: self.command_args.arg("IDLETIME").arg(idle_time),
        }
    }

    #[must_use]
    pub fn frequency(self, frequency: f64) -> Self {
        Self {
            command_args: self.command_args.arg("FREQ").arg(frequency),
        }
    }
}

impl IntoArgs for RestoreOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Order option of the [sort](crate::GenericCommands::sort) command
pub enum SortOrder {
    Asc,
    Desc,
}

impl IntoArgs for SortOrder {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        match self {
            SortOrder::Asc => args.arg("ASC"),
            SortOrder::Desc => args.arg("DESC"),
        }
    }
}

/// Options for the [`sort`](crate::GenericCommands::sort) command
#[derive(Default)]
pub struct SortOptions {
    command_args: CommandArgs,
}

impl SortOptions {
    #[must_use]
    pub fn by<P: Into<BulkString>>(self, pattern: P) -> Self {
        Self {
            command_args: self.command_args.arg("BY").arg(pattern),
        }
    }

    #[must_use]
    pub fn limit(self, offset: usize, count: isize) -> Self {
        Self {
            command_args: self.command_args.arg("LIMIT").arg(offset).arg(count),
        }
    }

    #[must_use]
    pub fn get<P: Into<BulkString>>(self, pattern: P) -> Self {
        Self {
            command_args: self.command_args.arg("GET").arg(pattern),
        }
    }

    #[must_use]
    pub fn order(self, order: SortOrder) -> Self {
        Self {
            command_args: self.command_args.arg(order),
        }
    }

    #[must_use]
    pub fn alpha(self) -> Self {
        Self {
            command_args: self.command_args.arg("ALPHA"),
        }
    }
}

impl IntoArgs for SortOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Result for the [dump](crate::GenericCommands::dump) command.
pub struct DumpResult {
    pub serialized_value: Vec<u8>,
}

impl FromValue for DumpResult {
    fn from_value(value: Value) -> crate::Result<Self> {
        match value {
            Value::BulkString(BulkString::Binary(b)) => Ok(DumpResult {
                serialized_value: b,
            }),
            _ => Err(Error::Client("Unexpected dump format".to_owned())),
        }
    }
}

/// Options for the [`scan`](crate::GenericCommands::scan) command
#[derive(Default)]
pub struct ScanOptions {
    command_args: CommandArgs,
}

impl ScanOptions {
    #[must_use]
    pub fn match_pattern<P: Into<BulkString>>(self, match_pattern: P) -> Self {
        Self {
            command_args: self.command_args.arg("MATCH").arg(match_pattern),
        }
    }

    #[must_use]
    pub fn count(self, count: usize) -> Self {
        Self {
            command_args: self.command_args.arg("COUNT").arg(count),
        }
    }

    #[must_use]
    pub fn type_<TY: Into<BulkString>>(self, type_: TY) -> Self {
        Self {
            command_args: self.command_args.arg("TYPE").arg(type_),
        }
    }
}

impl IntoArgs for ScanOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Result for the [`migrate`](crate::GenericCommands::migrate) command
pub enum MigrateResult {
    /// key(s) successfully migrated
    Ok,
    /// no keys were found in the source instance.
    NoKey,
}

impl FromValue for MigrateResult {
    fn from_value(value: Value) -> Result<Self> {
        let result: String = value.into()?;
        match result.as_str() {
            "OK" => Ok(Self::Ok),
            "NOKEY" => Ok(Self::NoKey),
            _ => Err(Error::Client(
                "Unexpected result for command 'MIGRATE'".to_owned(),
            )),
        }
    }
}