1use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25use crate::CommandArg;
26
27#[derive(Clone)]
32pub struct LPush {
33 key: CommandArg,
34 elements: Vec<CommandArg>,
35}
36
37impl LPush {
38 pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
40 Self {
41 key: key.into(),
42 elements: vec![element.into()],
43 }
44 }
45
46 pub fn elements(
48 key: impl Into<CommandArg>,
49 elements: impl IntoIterator<Item = impl Into<CommandArg>>,
50 ) -> Self {
51 Self {
52 key: key.into(),
53 elements: elements.into_iter().map(Into::into).collect(),
54 }
55 }
56
57 pub fn element(mut self, element: impl Into<CommandArg>) -> Self {
59 self.elements.push(element.into());
60 self
61 }
62}
63
64impl Command for LPush {
65 type Response = i64;
66
67 fn to_frame(&self) -> Frame {
68 let mut args = vec![bulk("LPUSH"), bulk(self.key.as_bytes())];
69 for element in &self.elements {
70 args.push(bulk(element.as_bytes()));
71 }
72 array(args)
73 }
74
75 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
76 match frame {
77 Frame::Integer(n) => Ok(n),
78 other => Err(RedisError::UnexpectedResponse {
79 expected: "integer",
80 actual: format!("{other:?}"),
81 }),
82 }
83 }
84
85 fn name(&self) -> &str {
86 "LPUSH"
87 }
88}
89
90#[derive(Clone)]
95pub struct RPush {
96 key: CommandArg,
97 elements: Vec<CommandArg>,
98}
99
100impl RPush {
101 pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
103 Self {
104 key: key.into(),
105 elements: vec![element.into()],
106 }
107 }
108
109 pub fn elements(
111 key: impl Into<CommandArg>,
112 elements: impl IntoIterator<Item = impl Into<CommandArg>>,
113 ) -> Self {
114 Self {
115 key: key.into(),
116 elements: elements.into_iter().map(Into::into).collect(),
117 }
118 }
119
120 pub fn element(mut self, element: impl Into<CommandArg>) -> Self {
122 self.elements.push(element.into());
123 self
124 }
125}
126
127impl Command for RPush {
128 type Response = i64;
129
130 fn to_frame(&self) -> Frame {
131 let mut args = vec![bulk("RPUSH"), bulk(self.key.as_bytes())];
132 for element in &self.elements {
133 args.push(bulk(element.as_bytes()));
134 }
135 array(args)
136 }
137
138 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
139 match frame {
140 Frame::Integer(n) => Ok(n),
141 other => Err(RedisError::UnexpectedResponse {
142 expected: "integer",
143 actual: format!("{other:?}"),
144 }),
145 }
146 }
147
148 fn name(&self) -> &str {
149 "RPUSH"
150 }
151}
152
153#[derive(Clone)]
158pub struct LPop {
159 key: CommandArg,
160}
161
162impl LPop {
163 pub fn new(key: impl Into<CommandArg>) -> Self {
165 Self { key: key.into() }
166 }
167}
168
169impl Command for LPop {
170 type Response = Option<Bytes>;
171
172 fn to_frame(&self) -> Frame {
173 array(vec![bulk("LPOP"), bulk(self.key.as_bytes())])
174 }
175
176 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
177 match frame {
178 Frame::BulkString(data) => Ok(data),
179 Frame::Null => Ok(None),
180 other => Err(RedisError::UnexpectedResponse {
181 expected: "bulk string or null",
182 actual: format!("{other:?}"),
183 }),
184 }
185 }
186
187 fn name(&self) -> &str {
188 "LPOP"
189 }
190}
191
192#[derive(Clone)]
197pub struct RPop {
198 key: CommandArg,
199}
200
201impl RPop {
202 pub fn new(key: impl Into<CommandArg>) -> Self {
204 Self { key: key.into() }
205 }
206}
207
208impl Command for RPop {
209 type Response = Option<Bytes>;
210
211 fn to_frame(&self) -> Frame {
212 array(vec![bulk("RPOP"), bulk(self.key.as_bytes())])
213 }
214
215 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
216 match frame {
217 Frame::BulkString(data) => Ok(data),
218 Frame::Null => Ok(None),
219 other => Err(RedisError::UnexpectedResponse {
220 expected: "bulk string or null",
221 actual: format!("{other:?}"),
222 }),
223 }
224 }
225
226 fn name(&self) -> &str {
227 "RPOP"
228 }
229}
230
231#[derive(Clone)]
237pub struct LRange {
238 key: CommandArg,
239 start: i64,
240 stop: i64,
241}
242
243impl LRange {
244 pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
246 Self {
247 key: key.into(),
248 start,
249 stop,
250 }
251 }
252}
253
254impl Command for LRange {
255 type Response = Vec<Bytes>;
256
257 fn to_frame(&self) -> Frame {
258 array(vec![
259 bulk("LRANGE"),
260 bulk(self.key.as_bytes()),
261 bulk(self.start.to_string()),
262 bulk(self.stop.to_string()),
263 ])
264 }
265
266 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
267 match frame {
268 Frame::Array(Some(frames)) => frames
269 .into_iter()
270 .map(|f| match f {
271 Frame::BulkString(Some(data)) => Ok(data),
272 other => Err(RedisError::UnexpectedResponse {
273 expected: "bulk string",
274 actual: format!("{other:?}"),
275 }),
276 })
277 .collect(),
278 Frame::Array(None) => Ok(Vec::new()),
279 other => Err(RedisError::UnexpectedResponse {
280 expected: "array",
281 actual: format!("{other:?}"),
282 }),
283 }
284 }
285
286 fn name(&self) -> &str {
287 "LRANGE"
288 }
289
290 fn idempotent(&self) -> bool {
291 true
292 }
293}
294
295#[derive(Clone)]
300pub struct LLen {
301 key: CommandArg,
302}
303
304impl LLen {
305 pub fn new(key: impl Into<CommandArg>) -> Self {
307 Self { key: key.into() }
308 }
309}
310
311impl Command for LLen {
312 type Response = i64;
313
314 fn to_frame(&self) -> Frame {
315 array(vec![bulk("LLEN"), bulk(self.key.as_bytes())])
316 }
317
318 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
319 match frame {
320 Frame::Integer(n) => Ok(n),
321 other => Err(RedisError::UnexpectedResponse {
322 expected: "integer",
323 actual: format!("{other:?}"),
324 }),
325 }
326 }
327
328 fn name(&self) -> &str {
329 "LLEN"
330 }
331
332 fn idempotent(&self) -> bool {
333 true
334 }
335}
336
337#[derive(Clone)]
343pub struct LIndex {
344 key: CommandArg,
345 index: i64,
346}
347
348impl LIndex {
349 pub fn new(key: impl Into<CommandArg>, index: i64) -> Self {
351 Self {
352 key: key.into(),
353 index,
354 }
355 }
356}
357
358impl Command for LIndex {
359 type Response = Option<Bytes>;
360
361 fn to_frame(&self) -> Frame {
362 array(vec![
363 bulk("LINDEX"),
364 bulk(self.key.as_bytes()),
365 bulk(self.index.to_string()),
366 ])
367 }
368
369 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
370 match frame {
371 Frame::BulkString(data) => Ok(data),
372 Frame::Null => Ok(None),
373 other => Err(RedisError::UnexpectedResponse {
374 expected: "bulk string or null",
375 actual: format!("{other:?}"),
376 }),
377 }
378 }
379
380 fn name(&self) -> &str {
381 "LINDEX"
382 }
383
384 fn idempotent(&self) -> bool {
385 true
386 }
387}
388
389#[derive(Clone)]
394pub struct LSet {
395 key: CommandArg,
396 index: i64,
397 element: CommandArg,
398}
399
400impl LSet {
401 pub fn new(key: impl Into<CommandArg>, index: i64, element: impl Into<CommandArg>) -> Self {
403 Self {
404 key: key.into(),
405 index,
406 element: element.into(),
407 }
408 }
409}
410
411impl Command for LSet {
412 type Response = ();
413
414 fn to_frame(&self) -> Frame {
415 array(vec![
416 bulk("LSET"),
417 bulk(self.key.as_bytes()),
418 bulk(self.index.to_string()),
419 bulk(self.element.as_bytes()),
420 ])
421 }
422
423 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
424 match frame {
425 Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
426 other => Err(RedisError::UnexpectedResponse {
427 expected: "OK",
428 actual: format!("{other:?}"),
429 }),
430 }
431 }
432
433 fn name(&self) -> &str {
434 "LSET"
435 }
436}
437
438#[derive(Clone)]
440pub enum ListDirection {
441 Left,
443 Right,
445}
446
447impl ListDirection {
448 fn as_str(&self) -> &str {
449 match self {
450 ListDirection::Left => "LEFT",
451 ListDirection::Right => "RIGHT",
452 }
453 }
454}
455
456#[derive(Clone)]
461pub struct LMove {
462 source: CommandArg,
463 destination: CommandArg,
464 wherefrom: ListDirection,
465 whereto: ListDirection,
466}
467
468impl LMove {
469 pub fn new(
471 source: impl Into<CommandArg>,
472 destination: impl Into<CommandArg>,
473 wherefrom: ListDirection,
474 whereto: ListDirection,
475 ) -> Self {
476 Self {
477 source: source.into(),
478 destination: destination.into(),
479 wherefrom,
480 whereto,
481 }
482 }
483}
484
485impl Command for LMove {
486 type Response = Option<Bytes>;
487
488 fn to_frame(&self) -> Frame {
489 array(vec![
490 bulk("LMOVE"),
491 bulk(self.source.as_bytes()),
492 bulk(self.destination.as_bytes()),
493 bulk(self.wherefrom.as_str()),
494 bulk(self.whereto.as_str()),
495 ])
496 }
497
498 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
499 match frame {
500 Frame::BulkString(data) => Ok(data),
501 Frame::Null => Ok(None),
502 other => Err(RedisError::UnexpectedResponse {
503 expected: "bulk string or null",
504 actual: format!("{other:?}"),
505 }),
506 }
507 }
508
509 fn name(&self) -> &str {
510 "LMOVE"
511 }
512}
513
514#[derive(Clone)]
520pub struct LPushX {
521 key: CommandArg,
522 element: CommandArg,
523}
524
525impl LPushX {
526 pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
528 Self {
529 key: key.into(),
530 element: element.into(),
531 }
532 }
533}
534
535impl Command for LPushX {
536 type Response = i64;
537
538 fn to_frame(&self) -> Frame {
539 array(vec![
540 bulk("LPUSHX"),
541 bulk(self.key.as_bytes()),
542 bulk(self.element.as_bytes()),
543 ])
544 }
545
546 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
547 match frame {
548 Frame::Integer(n) => Ok(n),
549 other => Err(RedisError::UnexpectedResponse {
550 expected: "integer",
551 actual: format!("{other:?}"),
552 }),
553 }
554 }
555
556 fn name(&self) -> &str {
557 "LPUSHX"
558 }
559}
560
561#[derive(Clone)]
567pub struct RPushX {
568 key: CommandArg,
569 element: CommandArg,
570}
571
572impl RPushX {
573 pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
575 Self {
576 key: key.into(),
577 element: element.into(),
578 }
579 }
580}
581
582impl Command for RPushX {
583 type Response = i64;
584
585 fn to_frame(&self) -> Frame {
586 array(vec![
587 bulk("RPUSHX"),
588 bulk(self.key.as_bytes()),
589 bulk(self.element.as_bytes()),
590 ])
591 }
592
593 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
594 match frame {
595 Frame::Integer(n) => Ok(n),
596 other => Err(RedisError::UnexpectedResponse {
597 expected: "integer",
598 actual: format!("{other:?}"),
599 }),
600 }
601 }
602
603 fn name(&self) -> &str {
604 "RPUSHX"
605 }
606}
607
608#[derive(Clone)]
610pub enum ListPosition {
611 Before,
613 After,
615}
616
617impl ListPosition {
618 fn as_str(&self) -> &str {
619 match self {
620 ListPosition::Before => "BEFORE",
621 ListPosition::After => "AFTER",
622 }
623 }
624}
625
626#[derive(Clone)]
632pub struct LInsert {
633 key: CommandArg,
634 position: ListPosition,
635 pivot: CommandArg,
636 element: CommandArg,
637}
638
639impl LInsert {
640 pub fn new(
642 key: impl Into<CommandArg>,
643 position: ListPosition,
644 pivot: impl Into<CommandArg>,
645 element: impl Into<CommandArg>,
646 ) -> Self {
647 Self {
648 key: key.into(),
649 position,
650 pivot: pivot.into(),
651 element: element.into(),
652 }
653 }
654}
655
656impl Command for LInsert {
657 type Response = i64;
658
659 fn to_frame(&self) -> Frame {
660 array(vec![
661 bulk("LINSERT"),
662 bulk(self.key.as_bytes()),
663 bulk(self.position.as_str()),
664 bulk(self.pivot.as_bytes()),
665 bulk(self.element.as_bytes()),
666 ])
667 }
668
669 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
670 match frame {
671 Frame::Integer(n) => Ok(n),
672 other => Err(RedisError::UnexpectedResponse {
673 expected: "integer",
674 actual: format!("{other:?}"),
675 }),
676 }
677 }
678
679 fn name(&self) -> &str {
680 "LINSERT"
681 }
682}
683
684#[derive(Clone)]
691pub struct LRem {
692 key: CommandArg,
693 count: i64,
694 element: CommandArg,
695}
696
697impl LRem {
698 pub fn new(key: impl Into<CommandArg>, count: i64, element: impl Into<CommandArg>) -> Self {
700 Self {
701 key: key.into(),
702 count,
703 element: element.into(),
704 }
705 }
706}
707
708impl Command for LRem {
709 type Response = i64;
710
711 fn to_frame(&self) -> Frame {
712 array(vec![
713 bulk("LREM"),
714 bulk(self.key.as_bytes()),
715 bulk(self.count.to_string()),
716 bulk(self.element.as_bytes()),
717 ])
718 }
719
720 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
721 match frame {
722 Frame::Integer(n) => Ok(n),
723 other => Err(RedisError::UnexpectedResponse {
724 expected: "integer",
725 actual: format!("{other:?}"),
726 }),
727 }
728 }
729
730 fn name(&self) -> &str {
731 "LREM"
732 }
733}
734
735#[derive(Clone)]
741pub struct LTrim {
742 key: CommandArg,
743 start: i64,
744 stop: i64,
745}
746
747impl LTrim {
748 pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
750 Self {
751 key: key.into(),
752 start,
753 stop,
754 }
755 }
756}
757
758impl Command for LTrim {
759 type Response = ();
760
761 fn to_frame(&self) -> Frame {
762 array(vec![
763 bulk("LTRIM"),
764 bulk(self.key.as_bytes()),
765 bulk(self.start.to_string()),
766 bulk(self.stop.to_string()),
767 ])
768 }
769
770 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
771 match frame {
772 Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
773 other => Err(RedisError::UnexpectedResponse {
774 expected: "OK",
775 actual: format!("{other:?}"),
776 }),
777 }
778 }
779
780 fn name(&self) -> &str {
781 "LTRIM"
782 }
783}
784
785#[derive(Clone)]
791pub struct LPos {
792 key: CommandArg,
793 element: CommandArg,
794 rank: Option<i64>,
795 count: Option<u64>,
796 maxlen: Option<u64>,
797}
798
799impl LPos {
800 pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
802 Self {
803 key: key.into(),
804 element: element.into(),
805 rank: None,
806 count: None,
807 maxlen: None,
808 }
809 }
810
811 pub fn rank(mut self, rank: i64) -> Self {
814 self.rank = Some(rank);
815 self
816 }
817
818 pub fn count(mut self, count: u64) -> Self {
821 self.count = Some(count);
822 self
823 }
824
825 pub fn maxlen(mut self, maxlen: u64) -> Self {
827 self.maxlen = Some(maxlen);
828 self
829 }
830}
831
832impl Command for LPos {
833 type Response = Option<i64>;
834
835 fn to_frame(&self) -> Frame {
836 let mut args = vec![
837 bulk("LPOS"),
838 bulk(self.key.as_bytes()),
839 bulk(self.element.as_bytes()),
840 ];
841 if let Some(rank) = self.rank {
842 args.push(bulk("RANK"));
843 args.push(bulk(rank.to_string()));
844 }
845 if let Some(count) = self.count {
846 args.push(bulk("COUNT"));
847 args.push(bulk(count.to_string()));
848 }
849 if let Some(maxlen) = self.maxlen {
850 args.push(bulk("MAXLEN"));
851 args.push(bulk(maxlen.to_string()));
852 }
853 array(args)
854 }
855
856 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
857 match frame {
858 Frame::Integer(n) => Ok(Some(n)),
859 Frame::Null => Ok(None),
860 other => Err(RedisError::UnexpectedResponse {
861 expected: "integer or null",
862 actual: format!("{other:?}"),
863 }),
864 }
865 }
866
867 fn name(&self) -> &str {
868 "LPOS"
869 }
870
871 fn idempotent(&self) -> bool {
872 true
873 }
874}
875
876#[derive(Clone)]
882pub struct LMPop {
883 keys: Vec<CommandArg>,
884 direction: ListDirection,
885 count: Option<u64>,
886}
887
888impl LMPop {
889 pub fn new(
891 keys: impl IntoIterator<Item = impl Into<CommandArg>>,
892 direction: ListDirection,
893 ) -> Self {
894 Self {
895 keys: keys.into_iter().map(Into::into).collect(),
896 direction,
897 count: None,
898 }
899 }
900
901 pub fn count(mut self, count: u64) -> Self {
903 self.count = Some(count);
904 self
905 }
906}
907
908impl Command for LMPop {
909 type Response = Option<(Bytes, Vec<Bytes>)>;
910
911 fn to_frame(&self) -> Frame {
912 let mut args = vec![bulk("LMPOP"), bulk(self.keys.len().to_string())];
913 for key in &self.keys {
914 args.push(bulk(key.as_bytes()));
915 }
916 args.push(bulk(self.direction.as_str()));
917 if let Some(count) = self.count {
918 args.push(bulk("COUNT"));
919 args.push(bulk(count.to_string()));
920 }
921 array(args)
922 }
923
924 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
925 match frame {
926 Frame::Null => Ok(None),
927 Frame::Array(None) => Ok(None),
928 Frame::Array(Some(frames)) if frames.len() == 2 => {
929 let mut iter = frames.into_iter();
930 let key = match iter.next().unwrap() {
931 Frame::BulkString(Some(data)) => data,
932 other => {
933 return Err(RedisError::UnexpectedResponse {
934 expected: "bulk string (key name)",
935 actual: format!("{other:?}"),
936 });
937 }
938 };
939 let elements = match iter.next().unwrap() {
940 Frame::Array(Some(elems)) => elems
941 .into_iter()
942 .map(|f| match f {
943 Frame::BulkString(Some(data)) => Ok(data),
944 other => Err(RedisError::UnexpectedResponse {
945 expected: "bulk string",
946 actual: format!("{other:?}"),
947 }),
948 })
949 .collect::<Result<Vec<_>, _>>()?,
950 other => {
951 return Err(RedisError::UnexpectedResponse {
952 expected: "array of bulk strings",
953 actual: format!("{other:?}"),
954 });
955 }
956 };
957 Ok(Some((key, elements)))
958 }
959 other => Err(RedisError::UnexpectedResponse {
960 expected: "null or two-element array",
961 actual: format!("{other:?}"),
962 }),
963 }
964 }
965
966 fn name(&self) -> &str {
967 "LMPOP"
968 }
969}
970
971#[derive(Clone)]
976pub struct LPopCount {
977 key: CommandArg,
978 count: u64,
979}
980
981impl LPopCount {
982 pub fn new(key: impl Into<CommandArg>, count: u64) -> Self {
984 Self {
985 key: key.into(),
986 count,
987 }
988 }
989}
990
991impl Command for LPopCount {
992 type Response = Vec<Bytes>;
993
994 fn to_frame(&self) -> Frame {
995 array(vec![
996 bulk("LPOP"),
997 bulk(self.key.as_bytes()),
998 bulk(self.count.to_string()),
999 ])
1000 }
1001
1002 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1003 match frame {
1004 Frame::Array(Some(frames)) => frames
1005 .into_iter()
1006 .map(|f| match f {
1007 Frame::BulkString(Some(data)) => Ok(data),
1008 other => Err(RedisError::UnexpectedResponse {
1009 expected: "bulk string",
1010 actual: format!("{other:?}"),
1011 }),
1012 })
1013 .collect(),
1014 Frame::Array(None) | Frame::Null => Ok(Vec::new()),
1015 other => Err(RedisError::UnexpectedResponse {
1016 expected: "array or null",
1017 actual: format!("{other:?}"),
1018 }),
1019 }
1020 }
1021
1022 fn name(&self) -> &str {
1023 "LPOP"
1024 }
1025}
1026
1027#[derive(Clone)]
1032pub struct RPopCount {
1033 key: CommandArg,
1034 count: u64,
1035}
1036
1037impl RPopCount {
1038 pub fn new(key: impl Into<CommandArg>, count: u64) -> Self {
1040 Self {
1041 key: key.into(),
1042 count,
1043 }
1044 }
1045}
1046
1047impl Command for RPopCount {
1048 type Response = Vec<Bytes>;
1049
1050 fn to_frame(&self) -> Frame {
1051 array(vec![
1052 bulk("RPOP"),
1053 bulk(self.key.as_bytes()),
1054 bulk(self.count.to_string()),
1055 ])
1056 }
1057
1058 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1059 match frame {
1060 Frame::Array(Some(frames)) => frames
1061 .into_iter()
1062 .map(|f| match f {
1063 Frame::BulkString(Some(data)) => Ok(data),
1064 other => Err(RedisError::UnexpectedResponse {
1065 expected: "bulk string",
1066 actual: format!("{other:?}"),
1067 }),
1068 })
1069 .collect(),
1070 Frame::Array(None) | Frame::Null => Ok(Vec::new()),
1071 other => Err(RedisError::UnexpectedResponse {
1072 expected: "array or null",
1073 actual: format!("{other:?}"),
1074 }),
1075 }
1076 }
1077
1078 fn name(&self) -> &str {
1079 "RPOP"
1080 }
1081}
1082
1083#[derive(Clone)]
1090pub struct BlMPop {
1091 timeout: f64,
1092 keys: Vec<CommandArg>,
1093 direction: ListDirection,
1094 count: Option<u64>,
1095}
1096
1097impl BlMPop {
1098 pub fn new(
1100 timeout: f64,
1101 keys: impl IntoIterator<Item = impl Into<CommandArg>>,
1102 direction: ListDirection,
1103 ) -> Self {
1104 Self {
1105 timeout,
1106 keys: keys.into_iter().map(Into::into).collect(),
1107 direction,
1108 count: None,
1109 }
1110 }
1111
1112 pub fn count(mut self, count: u64) -> Self {
1114 self.count = Some(count);
1115 self
1116 }
1117}
1118
1119impl Command for BlMPop {
1120 type Response = Option<(Bytes, Vec<Bytes>)>;
1121
1122 fn to_frame(&self) -> Frame {
1123 let mut args = vec![
1124 bulk("BLMPOP"),
1125 bulk(self.timeout.to_string()),
1126 bulk(self.keys.len().to_string()),
1127 ];
1128 for key in &self.keys {
1129 args.push(bulk(key.as_bytes()));
1130 }
1131 args.push(bulk(self.direction.as_str()));
1132 if let Some(count) = self.count {
1133 args.push(bulk("COUNT"));
1134 args.push(bulk(count.to_string()));
1135 }
1136 array(args)
1137 }
1138
1139 fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1140 match frame {
1141 Frame::Null => Ok(None),
1142 Frame::Array(None) => Ok(None),
1143 Frame::Array(Some(frames)) if frames.len() == 2 => {
1144 let mut iter = frames.into_iter();
1145 let key = match iter.next().unwrap() {
1146 Frame::BulkString(Some(data)) => data,
1147 other => {
1148 return Err(RedisError::UnexpectedResponse {
1149 expected: "bulk string (key name)",
1150 actual: format!("{other:?}"),
1151 });
1152 }
1153 };
1154 let elements = match iter.next().unwrap() {
1155 Frame::Array(Some(elems)) => elems
1156 .into_iter()
1157 .map(|f| match f {
1158 Frame::BulkString(Some(data)) => Ok(data),
1159 other => Err(RedisError::UnexpectedResponse {
1160 expected: "bulk string",
1161 actual: format!("{other:?}"),
1162 }),
1163 })
1164 .collect::<Result<Vec<_>, _>>()?,
1165 other => {
1166 return Err(RedisError::UnexpectedResponse {
1167 expected: "array of bulk strings",
1168 actual: format!("{other:?}"),
1169 });
1170 }
1171 };
1172 Ok(Some((key, elements)))
1173 }
1174 other => Err(RedisError::UnexpectedResponse {
1175 expected: "null or two-element array",
1176 actual: format!("{other:?}"),
1177 }),
1178 }
1179 }
1180
1181 fn name(&self) -> &str {
1182 "BLMPOP"
1183 }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188 use super::*;
1189 use redis_tower_core::Command;
1190 use redis_tower_protocol::Frame;
1191 use redis_tower_protocol::helpers::{array, bulk};
1192
1193 #[test]
1196 fn lpush_single_to_frame() {
1197 let cmd = LPush::new("mylist", "a");
1198 assert_eq!(
1199 cmd.to_frame(),
1200 array(vec![bulk("LPUSH"), bulk("mylist"), bulk("a")])
1201 );
1202 }
1203
1204 #[test]
1205 fn lpush_multiple_to_frame() {
1206 let cmd = LPush::elements("mylist", vec!["a", "b", "c"]);
1207 assert_eq!(
1208 cmd.to_frame(),
1209 array(vec![
1210 bulk("LPUSH"),
1211 bulk("mylist"),
1212 bulk("a"),
1213 bulk("b"),
1214 bulk("c"),
1215 ])
1216 );
1217 }
1218
1219 #[test]
1220 fn lpush_parse_integer() {
1221 let cmd = LPush::new("mylist", "a");
1222 assert_eq!(cmd.parse_response(Frame::Integer(3)).unwrap(), 3);
1223 }
1224
1225 #[test]
1226 fn lpush_parse_error_on_string() {
1227 let cmd = LPush::new("mylist", "a");
1228 assert!(
1229 cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1230 .is_err()
1231 );
1232 }
1233
1234 #[test]
1237 fn rpush_to_frame() {
1238 let cmd = RPush::new("mylist", "x");
1239 assert_eq!(
1240 cmd.to_frame(),
1241 array(vec![bulk("RPUSH"), bulk("mylist"), bulk("x")])
1242 );
1243 }
1244
1245 #[test]
1248 fn lpop_to_frame() {
1249 let cmd = LPop::new("mylist");
1250 assert_eq!(cmd.to_frame(), array(vec![bulk("LPOP"), bulk("mylist")]));
1251 }
1252
1253 #[test]
1254 fn lpop_parse_value() {
1255 let cmd = LPop::new("mylist");
1256 let frame = Frame::BulkString(Some(Bytes::from("first")));
1257 assert_eq!(
1258 cmd.parse_response(frame).unwrap(),
1259 Some(Bytes::from("first"))
1260 );
1261 }
1262
1263 #[test]
1264 fn lpop_parse_null() {
1265 let cmd = LPop::new("mylist");
1266 assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1267 }
1268
1269 #[test]
1272 fn rpop_to_frame() {
1273 let cmd = RPop::new("mylist");
1274 assert_eq!(cmd.to_frame(), array(vec![bulk("RPOP"), bulk("mylist")]));
1275 }
1276
1277 #[test]
1280 fn lrange_to_frame() {
1281 let cmd = LRange::new("mylist", 0, -1);
1282 assert_eq!(
1283 cmd.to_frame(),
1284 array(vec![bulk("LRANGE"), bulk("mylist"), bulk("0"), bulk("-1")])
1285 );
1286 }
1287
1288 #[test]
1289 fn lrange_parse_array() {
1290 let cmd = LRange::new("mylist", 0, -1);
1291 let frame = array(vec![
1292 Frame::BulkString(Some(Bytes::from("a"))),
1293 Frame::BulkString(Some(Bytes::from("b"))),
1294 ]);
1295 let result = cmd.parse_response(frame).unwrap();
1296 assert_eq!(result, vec![Bytes::from("a"), Bytes::from("b")]);
1297 }
1298
1299 #[test]
1300 fn lrange_parse_empty() {
1301 let cmd = LRange::new("mylist", 0, -1);
1302 let frame = Frame::Array(None);
1303 let result = cmd.parse_response(frame).unwrap();
1304 assert!(result.is_empty());
1305 }
1306
1307 #[test]
1310 fn llen_to_frame() {
1311 let cmd = LLen::new("mylist");
1312 assert_eq!(cmd.to_frame(), array(vec![bulk("LLEN"), bulk("mylist")]));
1313 }
1314
1315 #[test]
1318 fn lindex_to_frame() {
1319 let cmd = LIndex::new("mylist", 0);
1320 assert_eq!(
1321 cmd.to_frame(),
1322 array(vec![bulk("LINDEX"), bulk("mylist"), bulk("0")])
1323 );
1324 }
1325
1326 #[test]
1327 fn lindex_parse_null() {
1328 let cmd = LIndex::new("mylist", 99);
1329 assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1330 }
1331
1332 #[test]
1335 fn lset_to_frame() {
1336 let cmd = LSet::new("mylist", 0, "newval");
1337 assert_eq!(
1338 cmd.to_frame(),
1339 array(vec![
1340 bulk("LSET"),
1341 bulk("mylist"),
1342 bulk("0"),
1343 bulk("newval")
1344 ])
1345 );
1346 }
1347
1348 #[test]
1349 fn lset_parse_ok() {
1350 let cmd = LSet::new("mylist", 0, "v");
1351 cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1352 .unwrap();
1353 }
1354
1355 #[test]
1358 fn lmove_to_frame() {
1359 let cmd = LMove::new("src", "dst", ListDirection::Left, ListDirection::Right);
1360 assert_eq!(
1361 cmd.to_frame(),
1362 array(vec![
1363 bulk("LMOVE"),
1364 bulk("src"),
1365 bulk("dst"),
1366 bulk("LEFT"),
1367 bulk("RIGHT"),
1368 ])
1369 );
1370 }
1371
1372 #[test]
1375 fn lmpop_to_frame() {
1376 let cmd = LMPop::new(vec!["k1", "k2"], ListDirection::Left).count(3);
1377 assert_eq!(
1378 cmd.to_frame(),
1379 array(vec![
1380 bulk("LMPOP"),
1381 bulk("2"),
1382 bulk("k1"),
1383 bulk("k2"),
1384 bulk("LEFT"),
1385 bulk("COUNT"),
1386 bulk("3"),
1387 ])
1388 );
1389 }
1390
1391 #[test]
1392 fn lmpop_parse_null() {
1393 let cmd = LMPop::new(vec!["k1"], ListDirection::Left);
1394 assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1395 }
1396
1397 #[test]
1398 fn lmpop_parse_result() {
1399 let cmd = LMPop::new(vec!["k1"], ListDirection::Left);
1400 let frame = array(vec![
1401 Frame::BulkString(Some(Bytes::from("k1"))),
1402 array(vec![Frame::BulkString(Some(Bytes::from("elem")))]),
1403 ]);
1404 let result = cmd.parse_response(frame).unwrap().unwrap();
1405 assert_eq!(result.0, Bytes::from("k1"));
1406 assert_eq!(result.1, vec![Bytes::from("elem")]);
1407 }
1408
1409 #[test]
1412 fn lpos_to_frame() {
1413 let cmd = LPos::new("mylist", "val");
1414 assert_eq!(
1415 cmd.to_frame(),
1416 array(vec![bulk("LPOS"), bulk("mylist"), bulk("val")])
1417 );
1418 }
1419
1420 #[test]
1421 fn lpos_with_options_to_frame() {
1422 let cmd = LPos::new("mylist", "val").rank(2).count(0).maxlen(100);
1423 assert_eq!(
1424 cmd.to_frame(),
1425 array(vec![
1426 bulk("LPOS"),
1427 bulk("mylist"),
1428 bulk("val"),
1429 bulk("RANK"),
1430 bulk("2"),
1431 bulk("COUNT"),
1432 bulk("0"),
1433 bulk("MAXLEN"),
1434 bulk("100"),
1435 ])
1436 );
1437 }
1438
1439 #[test]
1440 fn lpos_parse_integer() {
1441 let cmd = LPos::new("mylist", "val");
1442 assert_eq!(cmd.parse_response(Frame::Integer(3)).unwrap(), Some(3));
1443 }
1444
1445 #[test]
1446 fn lpos_parse_null() {
1447 let cmd = LPos::new("mylist", "val");
1448 assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1449 }
1450
1451 #[test]
1454 fn linsert_to_frame() {
1455 let cmd = LInsert::new("mylist", ListPosition::Before, "pivot", "elem");
1456 assert_eq!(
1457 cmd.to_frame(),
1458 array(vec![
1459 bulk("LINSERT"),
1460 bulk("mylist"),
1461 bulk("BEFORE"),
1462 bulk("pivot"),
1463 bulk("elem"),
1464 ])
1465 );
1466 }
1467
1468 #[test]
1471 fn ltrim_to_frame() {
1472 let cmd = LTrim::new("mylist", 1, -1);
1473 assert_eq!(
1474 cmd.to_frame(),
1475 array(vec![bulk("LTRIM"), bulk("mylist"), bulk("1"), bulk("-1")])
1476 );
1477 }
1478
1479 #[test]
1480 fn ltrim_parse_ok() {
1481 let cmd = LTrim::new("mylist", 0, 99);
1482 cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
1483 .unwrap();
1484 }
1485
1486 #[test]
1489 fn lpop_count_to_frame() {
1490 let cmd = LPopCount::new("mylist", 2);
1491 assert_eq!(
1492 cmd.to_frame(),
1493 array(vec![bulk("LPOP"), bulk("mylist"), bulk("2")])
1494 );
1495 }
1496
1497 #[test]
1498 fn lpop_count_parse_array() {
1499 let cmd = LPopCount::new("mylist", 2);
1500 let frame = array(vec![
1501 Frame::BulkString(Some(Bytes::from("a"))),
1502 Frame::BulkString(Some(Bytes::from("b"))),
1503 ]);
1504 let result = cmd.parse_response(frame).unwrap();
1505 assert_eq!(result, vec![Bytes::from("a"), Bytes::from("b")]);
1506 }
1507
1508 #[test]
1509 fn lpop_count_parse_null() {
1510 let cmd = LPopCount::new("mylist", 2);
1511 assert!(cmd.parse_response(Frame::Null).unwrap().is_empty());
1512 }
1513
1514 #[test]
1517 fn rpop_count_to_frame() {
1518 let cmd = RPopCount::new("mylist", 3);
1519 assert_eq!(
1520 cmd.to_frame(),
1521 array(vec![bulk("RPOP"), bulk("mylist"), bulk("3")])
1522 );
1523 }
1524
1525 #[test]
1528 fn blmpop_to_frame() {
1529 let cmd = BlMPop::new(1.5, vec!["k1", "k2"], ListDirection::Left).count(3);
1530 assert_eq!(
1531 cmd.to_frame(),
1532 array(vec![
1533 bulk("BLMPOP"),
1534 bulk("1.5"),
1535 bulk("2"),
1536 bulk("k1"),
1537 bulk("k2"),
1538 bulk("LEFT"),
1539 bulk("COUNT"),
1540 bulk("3"),
1541 ])
1542 );
1543 }
1544
1545 #[test]
1546 fn blmpop_parse_null() {
1547 let cmd = BlMPop::new(1.0, vec!["k1"], ListDirection::Right);
1548 assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
1549 }
1550
1551 #[test]
1552 fn blmpop_parse_result() {
1553 let cmd = BlMPop::new(1.0, vec!["k1"], ListDirection::Left);
1554 let frame = array(vec![
1555 Frame::BulkString(Some(Bytes::from("k1"))),
1556 array(vec![Frame::BulkString(Some(Bytes::from("elem")))]),
1557 ]);
1558 let result = cmd.parse_response(frame).unwrap().unwrap();
1559 assert_eq!(result.0, Bytes::from("k1"));
1560 assert_eq!(result.1, vec![Bytes::from("elem")]);
1561 }
1562}