Skip to main content

redis_tower_commands/
sorted_sets.rs

1//! Score-ordered sets, ranges, ranks, and set algebra.
2//!
3//! [`ZAdd`] returns a mutation count (modified count with `CH`), rank/score
4//! lookups are optional, and range commands preserve score order. Multi-key
5//! operations require one Cluster hash slot.
6//!
7//! ```
8//! use redis_tower_commands::{ZAdd, ZScore};
9//! use redis_tower_core::Command;
10//!
11//! let add = ZAdd::new("leaders").member(42.0, "ada");
12//! let score = ZScore::new("leaders", "ada");
13//! assert_eq!((add.name(), score.name()), ("ZADD", "ZSCORE"));
14//! ```
15//!
16//! See the [command cookbook] for response and Cluster guidance.
17//!
18//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#pipelines-transactions-and-cluster-slots
19
20use bytes::Bytes;
21use redis_tower_core::{Command, Frame, RedisError};
22use redis_tower_protocol::helpers::{array, bulk};
23
24use crate::CommandArg;
25
26/// ZADD key score member \[score member ...\]
27///
28/// Adds the specified members with scores to the sorted set stored at `key`.
29/// Returns the number of members added (excluding members already present
30/// whose score was updated).
31#[derive(Clone)]
32pub struct ZAdd {
33    key: CommandArg,
34    members: Vec<(f64, CommandArg)>,
35    nx: bool,
36    xx: bool,
37    gt: bool,
38    lt: bool,
39    ch: bool,
40}
41
42impl ZAdd {
43    /// Create a new [`ZAdd`] command.
44    pub fn new(key: impl Into<CommandArg>) -> Self {
45        Self {
46            key: key.into(),
47            members: Vec::new(),
48            nx: false,
49            xx: false,
50            gt: false,
51            lt: false,
52            ch: false,
53        }
54    }
55
56    /// Constructs a [`ZAdd`] pre-populated from an iterator of `(score, member)` pairs.
57    ///
58    /// This is the bulk-insert constructor: equivalent to calling `.member()` for every
59    /// pair in the iterator. Accepts any `IntoIterator<Item = (f64, impl Into<CommandArg>)>`,
60    /// including `Vec<(f64, String)>` and similar collections.
61    ///
62    /// Option flags (`nx`, `xx`, `gt`, `lt`, `ch`) can be chained as usual:
63    ///
64    /// ```no_run
65    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
66    /// use redis_tower_commands::ZAdd;
67    /// use redis_tower_core::RedisConnection;
68    ///
69    /// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
70    ///
71    /// let scores = vec![(100.0, "alice"), (200.0, "bob")];
72    /// let added = conn
73    ///     .execute(ZAdd::from_members("leaderboard", scores).ch())
74    ///     .await?;
75    /// # let _ = added;
76    /// # Ok(())
77    /// # }
78    /// ```
79    ///
80    /// Produces the same wire frame as the incremental builder for the same members:
81    ///
82    /// ```no_run
83    /// use redis_tower_commands::ZAdd;
84    /// use redis_tower_core::Command;
85    ///
86    /// // These two are equivalent:
87    /// let a = ZAdd::new("z").member(1.0, "a").member(2.0, "b");
88    /// let b = ZAdd::from_members("z", [(1.0, "a"), (2.0, "b")]);
89    /// assert_eq!(a.to_frame(), b.to_frame());
90    /// ```
91    pub fn from_members(
92        key: impl Into<CommandArg>,
93        members: impl IntoIterator<Item = (f64, impl Into<CommandArg>)>,
94    ) -> Self {
95        Self {
96            key: key.into(),
97            members: members
98                .into_iter()
99                .map(|(score, member)| (score, member.into()))
100                .collect(),
101            nx: false,
102            xx: false,
103            gt: false,
104            lt: false,
105            ch: false,
106        }
107    }
108
109    /// Adds a member with the given score.
110    pub fn member(mut self, score: f64, member: impl Into<CommandArg>) -> Self {
111        self.members.push((score, member.into()));
112        self
113    }
114
115    /// Only add new members; do not update existing members (NX).
116    pub fn nx(mut self) -> Self {
117        self.nx = true;
118        self
119    }
120
121    /// Only update existing members; do not add new members (XX).
122    pub fn xx(mut self) -> Self {
123        self.xx = true;
124        self
125    }
126
127    /// Only update existing members if the new score is greater (GT).
128    pub fn gt(mut self) -> Self {
129        self.gt = true;
130        self
131    }
132
133    /// Only update existing members if the new score is less (LT).
134    pub fn lt(mut self) -> Self {
135        self.lt = true;
136        self
137    }
138
139    /// Return the number of changed members rather than only added ones (CH).
140    pub fn ch(mut self) -> Self {
141        self.ch = true;
142        self
143    }
144}
145
146impl Command for ZAdd {
147    type Response = i64;
148
149    fn to_frame(&self) -> Frame {
150        let mut args = vec![bulk("ZADD"), bulk(self.key.as_bytes())];
151        if self.nx {
152            args.push(bulk("NX"));
153        }
154        if self.xx {
155            args.push(bulk("XX"));
156        }
157        if self.gt {
158            args.push(bulk("GT"));
159        }
160        if self.lt {
161            args.push(bulk("LT"));
162        }
163        if self.ch {
164            args.push(bulk("CH"));
165        }
166        for (score, member) in &self.members {
167            args.push(bulk(score.to_string()));
168            args.push(bulk(member.as_bytes()));
169        }
170        array(args)
171    }
172
173    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
174        match frame {
175            Frame::Integer(n) => Ok(n),
176            other => Err(RedisError::UnexpectedResponse {
177                expected: "integer",
178                actual: format!("{other:?}"),
179            }),
180        }
181    }
182
183    fn name(&self) -> &str {
184        "ZADD"
185    }
186}
187
188/// ZREM key member \[member ...\]
189///
190/// Removes the specified members from the sorted set stored at `key`. Returns
191/// the number of members that were removed.
192#[derive(Clone)]
193pub struct ZRem {
194    key: CommandArg,
195    members: Vec<CommandArg>,
196}
197
198impl ZRem {
199    /// Create a new [`ZRem`] command.
200    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
201        Self {
202            key: key.into(),
203            members: vec![member.into()],
204        }
205    }
206
207    /// Create the [`ZRem`] command for the supplied members.
208    pub fn members(
209        key: impl Into<CommandArg>,
210        members: impl IntoIterator<Item = impl Into<CommandArg>>,
211    ) -> Self {
212        Self {
213            key: key.into(),
214            members: members.into_iter().map(Into::into).collect(),
215        }
216    }
217}
218
219impl Command for ZRem {
220    type Response = i64;
221
222    fn to_frame(&self) -> Frame {
223        let mut args = vec![bulk("ZREM"), bulk(self.key.as_bytes())];
224        for member in &self.members {
225            args.push(bulk(member.as_bytes()));
226        }
227        array(args)
228    }
229
230    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
231        match frame {
232            Frame::Integer(n) => Ok(n),
233            other => Err(RedisError::UnexpectedResponse {
234                expected: "integer",
235                actual: format!("{other:?}"),
236            }),
237        }
238    }
239
240    fn name(&self) -> &str {
241        "ZREM"
242    }
243}
244
245/// ZRANGE key start stop
246///
247/// Returns the specified range of members in the sorted set stored at `key`,
248/// ordered from lowest to highest score. `start` and `stop` are zero-based
249/// indices, where -1 is the last element.
250#[derive(Clone)]
251pub struct ZRange {
252    key: CommandArg,
253    start: i64,
254    stop: i64,
255}
256
257impl ZRange {
258    /// Create a new [`ZRange`] command.
259    pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
260        Self {
261            key: key.into(),
262            start,
263            stop,
264        }
265    }
266}
267
268impl Command for ZRange {
269    type Response = Vec<Bytes>;
270
271    fn to_frame(&self) -> Frame {
272        array(vec![
273            bulk("ZRANGE"),
274            bulk(self.key.as_bytes()),
275            bulk(self.start.to_string()),
276            bulk(self.stop.to_string()),
277        ])
278    }
279
280    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
281        match frame {
282            Frame::Array(Some(frames)) => frames
283                .into_iter()
284                .map(|f| match f {
285                    Frame::BulkString(Some(data)) => Ok(data),
286                    other => Err(RedisError::UnexpectedResponse {
287                        expected: "bulk string",
288                        actual: format!("{other:?}"),
289                    }),
290                })
291                .collect(),
292            other => Err(RedisError::UnexpectedResponse {
293                expected: "array",
294                actual: format!("{other:?}"),
295            }),
296        }
297    }
298
299    fn name(&self) -> &str {
300        "ZRANGE"
301    }
302
303    fn idempotent(&self) -> bool {
304        true
305    }
306}
307
308/// ZSCORE key member
309///
310/// Returns the score of `member` in the sorted set at `key`, or `None` if
311/// the \[member\] or key does not exist.
312#[derive(Clone)]
313pub struct ZScore {
314    key: CommandArg,
315    member: CommandArg,
316}
317
318impl ZScore {
319    /// Create a new [`ZScore`] command.
320    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
321        Self {
322            key: key.into(),
323            member: member.into(),
324        }
325    }
326}
327
328impl Command for ZScore {
329    type Response = Option<f64>;
330
331    fn to_frame(&self) -> Frame {
332        array(vec![
333            bulk("ZSCORE"),
334            bulk(self.key.as_bytes()),
335            bulk(self.member.as_bytes()),
336        ])
337    }
338
339    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
340        match frame {
341            Frame::BulkString(Some(data)) => {
342                let s = String::from_utf8_lossy(&data);
343                let score = s
344                    .parse::<f64>()
345                    .map_err(|_| RedisError::UnexpectedResponse {
346                        expected: "float string",
347                        actual: format!("{s}"),
348                    })?;
349                Ok(Some(score))
350            }
351            Frame::Double(d) => Ok(Some(d)),
352            Frame::BulkString(None) | Frame::Null => Ok(None),
353            other => Err(RedisError::UnexpectedResponse {
354                expected: "bulk string, double, or null",
355                actual: format!("{other:?}"),
356            }),
357        }
358    }
359
360    fn name(&self) -> &str {
361        "ZSCORE"
362    }
363
364    fn idempotent(&self) -> bool {
365        true
366    }
367}
368
369/// ZCARD key
370///
371/// Returns the number of members in the sorted set stored at `key`.
372#[derive(Clone)]
373pub struct ZCard {
374    key: CommandArg,
375}
376
377impl ZCard {
378    /// Create a new [`ZCard`] command.
379    pub fn new(key: impl Into<CommandArg>) -> Self {
380        Self { key: key.into() }
381    }
382}
383
384impl Command for ZCard {
385    type Response = i64;
386
387    fn to_frame(&self) -> Frame {
388        array(vec![bulk("ZCARD"), bulk(self.key.as_bytes())])
389    }
390
391    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
392        match frame {
393            Frame::Integer(n) => Ok(n),
394            other => Err(RedisError::UnexpectedResponse {
395                expected: "integer",
396                actual: format!("{other:?}"),
397            }),
398        }
399    }
400
401    fn name(&self) -> &str {
402        "ZCARD"
403    }
404
405    fn idempotent(&self) -> bool {
406        true
407    }
408}
409
410/// ZINCRBY key increment member
411///
412/// Increments the score of `member` in the sorted set at `key` by
413/// `increment`. Returns the new score of the \[member\].
414#[derive(Clone)]
415pub struct ZIncrBy {
416    key: CommandArg,
417    increment: f64,
418    member: CommandArg,
419}
420
421impl ZIncrBy {
422    /// Create a new [`ZIncrBy`] command.
423    pub fn new(key: impl Into<CommandArg>, increment: f64, member: impl Into<CommandArg>) -> Self {
424        Self {
425            key: key.into(),
426            increment,
427            member: member.into(),
428        }
429    }
430}
431
432impl Command for ZIncrBy {
433    type Response = f64;
434
435    fn to_frame(&self) -> Frame {
436        array(vec![
437            bulk("ZINCRBY"),
438            bulk(self.key.as_bytes()),
439            bulk(self.increment.to_string()),
440            bulk(self.member.as_bytes()),
441        ])
442    }
443
444    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
445        match frame {
446            Frame::BulkString(Some(data)) => {
447                let s = String::from_utf8_lossy(&data);
448                s.parse::<f64>()
449                    .map_err(|_| RedisError::UnexpectedResponse {
450                        expected: "float string",
451                        actual: format!("{s}"),
452                    })
453            }
454            Frame::Double(d) => Ok(d),
455            other => Err(RedisError::UnexpectedResponse {
456                expected: "bulk string or double",
457                actual: format!("{other:?}"),
458            }),
459        }
460    }
461
462    fn name(&self) -> &str {
463        "ZINCRBY"
464    }
465}
466
467/// ZRANK key member
468///
469/// Returns the rank of `member` in the sorted set at `key` (zero-based,
470/// lowest score = rank 0), or `None` if the \[member\] or key does not exist.
471#[derive(Clone)]
472pub struct ZRank {
473    key: CommandArg,
474    member: CommandArg,
475}
476
477impl ZRank {
478    /// Create a new [`ZRank`] command.
479    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
480        Self {
481            key: key.into(),
482            member: member.into(),
483        }
484    }
485}
486
487impl Command for ZRank {
488    type Response = Option<i64>;
489
490    fn to_frame(&self) -> Frame {
491        array(vec![
492            bulk("ZRANK"),
493            bulk(self.key.as_bytes()),
494            bulk(self.member.as_bytes()),
495        ])
496    }
497
498    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
499        match frame {
500            Frame::Integer(n) => Ok(Some(n)),
501            Frame::Null | Frame::BulkString(None) => Ok(None),
502            other => Err(RedisError::UnexpectedResponse {
503                expected: "integer or null",
504                actual: format!("{other:?}"),
505            }),
506        }
507    }
508
509    fn name(&self) -> &str {
510        "ZRANK"
511    }
512
513    fn idempotent(&self) -> bool {
514        true
515    }
516}
517
518/// ZRANGEBYSCORE key min max
519///
520/// Returns all members in the sorted set at `key` with a score between
521/// `min` and `max` (inclusive). The `min` and `max` arguments can be
522/// `"-inf"`, `"+inf"`, or numeric strings.
523#[derive(Clone)]
524pub struct ZRangeByScore {
525    key: CommandArg,
526    min: CommandArg,
527    max: CommandArg,
528}
529
530impl ZRangeByScore {
531    /// Create a new [`ZRangeByScore`] command.
532    pub fn new(
533        key: impl Into<CommandArg>,
534        min: impl Into<CommandArg>,
535        max: impl Into<CommandArg>,
536    ) -> Self {
537        Self {
538            key: key.into(),
539            min: min.into(),
540            max: max.into(),
541        }
542    }
543}
544
545impl Command for ZRangeByScore {
546    type Response = Vec<Bytes>;
547
548    fn to_frame(&self) -> Frame {
549        array(vec![
550            bulk("ZRANGEBYSCORE"),
551            bulk(self.key.as_bytes()),
552            bulk(self.min.as_bytes()),
553            bulk(self.max.as_bytes()),
554        ])
555    }
556
557    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
558        match frame {
559            Frame::Array(Some(frames)) => frames
560                .into_iter()
561                .map(|f| match f {
562                    Frame::BulkString(Some(data)) => Ok(data),
563                    other => Err(RedisError::UnexpectedResponse {
564                        expected: "bulk string",
565                        actual: format!("{other:?}"),
566                    }),
567                })
568                .collect(),
569            other => Err(RedisError::UnexpectedResponse {
570                expected: "array",
571                actual: format!("{other:?}"),
572            }),
573        }
574    }
575
576    fn name(&self) -> &str {
577        "ZRANGEBYSCORE"
578    }
579
580    fn idempotent(&self) -> bool {
581        true
582    }
583}
584
585/// ZPOPMIN key \[count\]
586///
587/// Removes and returns the members with the lowest scores in the sorted set
588/// stored at `key`. Returns a list of `(member, score)` pairs.
589#[derive(Clone)]
590pub struct ZPopMin {
591    key: CommandArg,
592    count: Option<i64>,
593}
594
595impl ZPopMin {
596    /// Create a new [`ZPopMin`] command.
597    pub fn new(key: impl Into<CommandArg>) -> Self {
598        Self {
599            key: key.into(),
600            count: None,
601        }
602    }
603
604    /// Sets the number of members to pop.
605    pub fn count(mut self, count: i64) -> Self {
606        self.count = Some(count);
607        self
608    }
609}
610
611impl Command for ZPopMin {
612    type Response = Vec<(Bytes, f64)>;
613
614    fn to_frame(&self) -> Frame {
615        let mut args = vec![bulk("ZPOPMIN"), bulk(self.key.as_bytes())];
616        if let Some(count) = self.count {
617            args.push(bulk(count.to_string()));
618        }
619        array(args)
620    }
621
622    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
623        match frame {
624            Frame::Array(Some(frames)) => {
625                if frames.len() % 2 != 0 {
626                    return Err(RedisError::UnexpectedResponse {
627                        expected: "even number of elements (member/score pairs)",
628                        actual: format!("array of length {}", frames.len()),
629                    });
630                }
631                frames
632                    .chunks(2)
633                    .map(|pair| {
634                        let member = match &pair[0] {
635                            Frame::BulkString(Some(data)) => data.clone(),
636                            other => {
637                                return Err(RedisError::UnexpectedResponse {
638                                    expected: "bulk string",
639                                    actual: format!("{other:?}"),
640                                });
641                            }
642                        };
643                        let score = match &pair[1] {
644                            Frame::BulkString(Some(data)) => {
645                                let s = String::from_utf8_lossy(data);
646                                s.parse::<f64>()
647                                    .map_err(|_| RedisError::UnexpectedResponse {
648                                        expected: "float string",
649                                        actual: format!("{s}"),
650                                    })?
651                            }
652                            Frame::Double(d) => *d,
653                            other => {
654                                return Err(RedisError::UnexpectedResponse {
655                                    expected: "bulk string or double",
656                                    actual: format!("{other:?}"),
657                                });
658                            }
659                        };
660                        Ok((member, score))
661                    })
662                    .collect()
663            }
664            Frame::Array(None) => Ok(Vec::new()),
665            other => Err(RedisError::UnexpectedResponse {
666                expected: "array",
667                actual: format!("{other:?}"),
668            }),
669        }
670    }
671
672    fn name(&self) -> &str {
673        "ZPOPMIN"
674    }
675}
676
677/// ZPOPMAX key \[count\]
678///
679/// Removes and returns the members with the highest scores in the sorted set
680/// stored at `key`. Returns a list of `(member, score)` pairs.
681#[derive(Clone)]
682pub struct ZPopMax {
683    key: CommandArg,
684    count: Option<i64>,
685}
686
687impl ZPopMax {
688    /// Create a new [`ZPopMax`] command.
689    pub fn new(key: impl Into<CommandArg>) -> Self {
690        Self {
691            key: key.into(),
692            count: None,
693        }
694    }
695
696    /// Sets the number of members to pop.
697    pub fn count(mut self, count: i64) -> Self {
698        self.count = Some(count);
699        self
700    }
701}
702
703impl Command for ZPopMax {
704    type Response = Vec<(Bytes, f64)>;
705
706    fn to_frame(&self) -> Frame {
707        let mut args = vec![bulk("ZPOPMAX"), bulk(self.key.as_bytes())];
708        if let Some(count) = self.count {
709            args.push(bulk(count.to_string()));
710        }
711        array(args)
712    }
713
714    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
715        match frame {
716            Frame::Array(Some(frames)) => {
717                if frames.len() % 2 != 0 {
718                    return Err(RedisError::UnexpectedResponse {
719                        expected: "even number of elements (member/score pairs)",
720                        actual: format!("array of length {}", frames.len()),
721                    });
722                }
723                frames
724                    .chunks(2)
725                    .map(|pair| {
726                        let member = match &pair[0] {
727                            Frame::BulkString(Some(data)) => data.clone(),
728                            other => {
729                                return Err(RedisError::UnexpectedResponse {
730                                    expected: "bulk string",
731                                    actual: format!("{other:?}"),
732                                });
733                            }
734                        };
735                        let score = match &pair[1] {
736                            Frame::BulkString(Some(data)) => {
737                                let s = String::from_utf8_lossy(data);
738                                s.parse::<f64>()
739                                    .map_err(|_| RedisError::UnexpectedResponse {
740                                        expected: "float string",
741                                        actual: format!("{s}"),
742                                    })?
743                            }
744                            Frame::Double(d) => *d,
745                            other => {
746                                return Err(RedisError::UnexpectedResponse {
747                                    expected: "bulk string or double",
748                                    actual: format!("{other:?}"),
749                                });
750                            }
751                        };
752                        Ok((member, score))
753                    })
754                    .collect()
755            }
756            Frame::Array(None) => Ok(Vec::new()),
757            other => Err(RedisError::UnexpectedResponse {
758                expected: "array",
759                actual: format!("{other:?}"),
760            }),
761        }
762    }
763
764    fn name(&self) -> &str {
765        "ZPOPMAX"
766    }
767}
768
769/// ZCOUNT key min max
770///
771/// Returns the number of members in the sorted set at `key` with a score
772/// between `min` and `max` (inclusive by default). The `min` and `max`
773/// arguments can be `"-inf"`, `"+inf"`, or numeric strings (prefix with
774/// `"("` for exclusive bounds).
775#[derive(Clone)]
776pub struct ZCount {
777    key: CommandArg,
778    min: CommandArg,
779    max: CommandArg,
780}
781
782impl ZCount {
783    /// Create a new [`ZCount`] command.
784    pub fn new(
785        key: impl Into<CommandArg>,
786        min: impl Into<CommandArg>,
787        max: impl Into<CommandArg>,
788    ) -> Self {
789        Self {
790            key: key.into(),
791            min: min.into(),
792            max: max.into(),
793        }
794    }
795}
796
797impl Command for ZCount {
798    type Response = i64;
799
800    fn to_frame(&self) -> Frame {
801        array(vec![
802            bulk("ZCOUNT"),
803            bulk(self.key.as_bytes()),
804            bulk(self.min.as_bytes()),
805            bulk(self.max.as_bytes()),
806        ])
807    }
808
809    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
810        match frame {
811            Frame::Integer(n) => Ok(n),
812            other => Err(RedisError::UnexpectedResponse {
813                expected: "integer",
814                actual: format!("{other:?}"),
815            }),
816        }
817    }
818
819    fn name(&self) -> &str {
820        "ZCOUNT"
821    }
822
823    fn idempotent(&self) -> bool {
824        true
825    }
826}
827
828/// ZLEXCOUNT key min max
829///
830/// Returns the number of members in the sorted set at `key` between the
831/// lexicographical range specified by `min` and `max`. Valid values for
832/// `min` and `max` are `"-"`, `"+"`, `"[value"` (inclusive), or `"(value"`
833/// (exclusive).
834#[derive(Clone)]
835pub struct ZLexCount {
836    key: CommandArg,
837    min: CommandArg,
838    max: CommandArg,
839}
840
841impl ZLexCount {
842    /// Create a new [`ZLexCount`] command.
843    pub fn new(
844        key: impl Into<CommandArg>,
845        min: impl Into<CommandArg>,
846        max: impl Into<CommandArg>,
847    ) -> Self {
848        Self {
849            key: key.into(),
850            min: min.into(),
851            max: max.into(),
852        }
853    }
854}
855
856impl Command for ZLexCount {
857    type Response = i64;
858
859    fn to_frame(&self) -> Frame {
860        array(vec![
861            bulk("ZLEXCOUNT"),
862            bulk(self.key.as_bytes()),
863            bulk(self.min.as_bytes()),
864            bulk(self.max.as_bytes()),
865        ])
866    }
867
868    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
869        match frame {
870            Frame::Integer(n) => Ok(n),
871            other => Err(RedisError::UnexpectedResponse {
872                expected: "integer",
873                actual: format!("{other:?}"),
874            }),
875        }
876    }
877
878    fn name(&self) -> &str {
879        "ZLEXCOUNT"
880    }
881
882    fn idempotent(&self) -> bool {
883        true
884    }
885}
886
887/// ZRANDMEMBER key \[count\]
888///
889/// Returns one or more random members from the sorted set at `key`.
890/// When called without `count`, returns a single random member.
891/// When called with `count`, returns up to that many distinct members.
892#[derive(Clone)]
893pub struct ZRandMember {
894    key: CommandArg,
895    count: Option<i64>,
896}
897
898impl ZRandMember {
899    /// Create a new [`ZRandMember`] command.
900    pub fn new(key: impl Into<CommandArg>) -> Self {
901        Self {
902            key: key.into(),
903            count: None,
904        }
905    }
906
907    /// Sets the number of members to return.
908    pub fn count(mut self, count: i64) -> Self {
909        self.count = Some(count);
910        self
911    }
912}
913
914impl Command for ZRandMember {
915    type Response = Vec<Bytes>;
916
917    fn to_frame(&self) -> Frame {
918        let mut args = vec![bulk("ZRANDMEMBER"), bulk(self.key.as_bytes())];
919        if let Some(count) = self.count {
920            args.push(bulk(count.to_string()));
921        }
922        array(args)
923    }
924
925    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
926        match frame {
927            Frame::Array(Some(frames)) => frames
928                .into_iter()
929                .map(|f| match f {
930                    Frame::BulkString(Some(data)) => Ok(data),
931                    other => Err(RedisError::UnexpectedResponse {
932                        expected: "bulk string",
933                        actual: format!("{other:?}"),
934                    }),
935                })
936                .collect(),
937            Frame::BulkString(Some(data)) => Ok(vec![data]),
938            Frame::BulkString(None) | Frame::Null => Ok(Vec::new()),
939            other => Err(RedisError::UnexpectedResponse {
940                expected: "array or bulk string",
941                actual: format!("{other:?}"),
942            }),
943        }
944    }
945
946    fn name(&self) -> &str {
947        "ZRANDMEMBER"
948    }
949
950    fn idempotent(&self) -> bool {
951        true
952    }
953}
954
955/// ZMSCORE key member \[member ...\]
956///
957/// Returns the scores associated with the specified members in the sorted
958/// set at `key`. For each member, returns `Some(score)` if the member
959/// exists, or `None` if it does not.
960#[derive(Clone)]
961pub struct ZMScore {
962    key: CommandArg,
963    members: Vec<CommandArg>,
964}
965
966impl ZMScore {
967    /// Create a new [`ZMScore`] command.
968    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
969        Self {
970            key: key.into(),
971            members: vec![member.into()],
972        }
973    }
974
975    /// Create the [`ZMScore`] command for the supplied members.
976    pub fn members(
977        key: impl Into<CommandArg>,
978        members: impl IntoIterator<Item = impl Into<CommandArg>>,
979    ) -> Self {
980        Self {
981            key: key.into(),
982            members: members.into_iter().map(Into::into).collect(),
983        }
984    }
985}
986
987impl Command for ZMScore {
988    type Response = Vec<Option<f64>>;
989
990    fn to_frame(&self) -> Frame {
991        let mut args = vec![bulk("ZMSCORE"), bulk(self.key.as_bytes())];
992        for member in &self.members {
993            args.push(bulk(member.as_bytes()));
994        }
995        array(args)
996    }
997
998    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
999        match frame {
1000            Frame::Array(Some(frames)) => frames
1001                .into_iter()
1002                .map(|f| match f {
1003                    Frame::BulkString(Some(data)) => {
1004                        let s = String::from_utf8_lossy(&data);
1005                        let score =
1006                            s.parse::<f64>()
1007                                .map_err(|_| RedisError::UnexpectedResponse {
1008                                    expected: "float string",
1009                                    actual: format!("{s}"),
1010                                })?;
1011                        Ok(Some(score))
1012                    }
1013                    Frame::Double(d) => Ok(Some(d)),
1014                    Frame::BulkString(None) | Frame::Null => Ok(None),
1015                    other => Err(RedisError::UnexpectedResponse {
1016                        expected: "bulk string, double, or null",
1017                        actual: format!("{other:?}"),
1018                    }),
1019                })
1020                .collect(),
1021            other => Err(RedisError::UnexpectedResponse {
1022                expected: "array",
1023                actual: format!("{other:?}"),
1024            }),
1025        }
1026    }
1027
1028    fn name(&self) -> &str {
1029        "ZMSCORE"
1030    }
1031
1032    fn idempotent(&self) -> bool {
1033        true
1034    }
1035}
1036
1037/// Aggregation function used by ZINTERSTORE, ZUNIONSTORE, and similar commands.
1038#[derive(Debug, Clone, Copy)]
1039pub enum Aggregate {
1040    /// Select the `Sum` mode.
1041    Sum,
1042    /// Select the `Min` mode.
1043    Min,
1044    /// Select the `Max` mode.
1045    Max,
1046}
1047
1048impl Aggregate {
1049    fn as_str(&self) -> &str {
1050        match self {
1051            Aggregate::Sum => "SUM",
1052            Aggregate::Min => "MIN",
1053            Aggregate::Max => "MAX",
1054        }
1055    }
1056}
1057
1058/// ZINTERSTORE destination numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\]
1059///
1060/// Computes the intersection of the sorted sets given by the specified keys,
1061/// and stores the result in `destination`. Returns the number of elements in
1062/// the resulting sorted set.
1063#[derive(Clone)]
1064pub struct ZInterStore {
1065    destination: CommandArg,
1066    keys: Vec<CommandArg>,
1067    weights: Option<Vec<f64>>,
1068    aggregate: Option<Aggregate>,
1069}
1070
1071impl ZInterStore {
1072    /// Create a new [`ZInterStore`] command.
1073    pub fn new(
1074        destination: impl Into<CommandArg>,
1075        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
1076    ) -> Self {
1077        Self {
1078            destination: destination.into(),
1079            keys: keys.into_iter().map(Into::into).collect(),
1080            weights: None,
1081            aggregate: None,
1082        }
1083    }
1084
1085    /// Sets the weight multipliers for each input sorted set.
1086    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
1087        self.weights = Some(weights.into_iter().collect());
1088        self
1089    }
1090
1091    /// Sets the aggregation function for combining scores.
1092    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
1093        self.aggregate = Some(aggregate);
1094        self
1095    }
1096}
1097
1098impl Command for ZInterStore {
1099    type Response = i64;
1100
1101    fn to_frame(&self) -> Frame {
1102        let mut args = vec![
1103            bulk("ZINTERSTORE"),
1104            bulk(self.destination.as_bytes()),
1105            bulk(self.keys.len().to_string()),
1106        ];
1107        for key in &self.keys {
1108            args.push(bulk(key.as_bytes()));
1109        }
1110        if let Some(weights) = &self.weights {
1111            args.push(bulk("WEIGHTS"));
1112            for w in weights {
1113                args.push(bulk(w.to_string()));
1114            }
1115        }
1116        if let Some(agg) = &self.aggregate {
1117            args.push(bulk("AGGREGATE"));
1118            args.push(bulk(agg.as_str()));
1119        }
1120        array(args)
1121    }
1122
1123    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1124        match frame {
1125            Frame::Integer(n) => Ok(n),
1126            other => Err(RedisError::UnexpectedResponse {
1127                expected: "integer",
1128                actual: format!("{other:?}"),
1129            }),
1130        }
1131    }
1132
1133    fn name(&self) -> &str {
1134        "ZINTERSTORE"
1135    }
1136}
1137
1138/// ZUNIONSTORE destination numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\]
1139///
1140/// Computes the union of the sorted sets given by the specified keys, and
1141/// stores the result in `destination`. Returns the number of elements in
1142/// the resulting sorted set.
1143#[derive(Clone)]
1144pub struct ZUnionStore {
1145    destination: CommandArg,
1146    keys: Vec<CommandArg>,
1147    weights: Option<Vec<f64>>,
1148    aggregate: Option<Aggregate>,
1149}
1150
1151impl ZUnionStore {
1152    /// Create a new [`ZUnionStore`] command.
1153    pub fn new(
1154        destination: impl Into<CommandArg>,
1155        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
1156    ) -> Self {
1157        Self {
1158            destination: destination.into(),
1159            keys: keys.into_iter().map(Into::into).collect(),
1160            weights: None,
1161            aggregate: None,
1162        }
1163    }
1164
1165    /// Sets the weight multipliers for each input sorted set.
1166    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
1167        self.weights = Some(weights.into_iter().collect());
1168        self
1169    }
1170
1171    /// Sets the aggregation function for combining scores.
1172    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
1173        self.aggregate = Some(aggregate);
1174        self
1175    }
1176}
1177
1178impl Command for ZUnionStore {
1179    type Response = i64;
1180
1181    fn to_frame(&self) -> Frame {
1182        let mut args = vec![
1183            bulk("ZUNIONSTORE"),
1184            bulk(self.destination.as_bytes()),
1185            bulk(self.keys.len().to_string()),
1186        ];
1187        for key in &self.keys {
1188            args.push(bulk(key.as_bytes()));
1189        }
1190        if let Some(weights) = &self.weights {
1191            args.push(bulk("WEIGHTS"));
1192            for w in weights {
1193                args.push(bulk(w.to_string()));
1194            }
1195        }
1196        if let Some(agg) = &self.aggregate {
1197            args.push(bulk("AGGREGATE"));
1198            args.push(bulk(agg.as_str()));
1199        }
1200        array(args)
1201    }
1202
1203    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1204        match frame {
1205            Frame::Integer(n) => Ok(n),
1206            other => Err(RedisError::UnexpectedResponse {
1207                expected: "integer",
1208                actual: format!("{other:?}"),
1209            }),
1210        }
1211    }
1212
1213    fn name(&self) -> &str {
1214        "ZUNIONSTORE"
1215    }
1216}
1217
1218/// ZDIFFSTORE destination numkeys key \[key ...\]
1219///
1220/// Computes the difference between the first sorted set and all successive
1221/// sorted sets given by the specified keys, and stores the result in
1222/// `destination`. Returns the number of elements in the resulting sorted set.
1223#[derive(Clone)]
1224pub struct ZDiffStore {
1225    destination: CommandArg,
1226    keys: Vec<CommandArg>,
1227}
1228
1229impl ZDiffStore {
1230    /// Create a new [`ZDiffStore`] command.
1231    pub fn new(
1232        destination: impl Into<CommandArg>,
1233        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
1234    ) -> Self {
1235        Self {
1236            destination: destination.into(),
1237            keys: keys.into_iter().map(Into::into).collect(),
1238        }
1239    }
1240}
1241
1242impl Command for ZDiffStore {
1243    type Response = i64;
1244
1245    fn to_frame(&self) -> Frame {
1246        let mut args = vec![
1247            bulk("ZDIFFSTORE"),
1248            bulk(self.destination.as_bytes()),
1249            bulk(self.keys.len().to_string()),
1250        ];
1251        for key in &self.keys {
1252            args.push(bulk(key.as_bytes()));
1253        }
1254        array(args)
1255    }
1256
1257    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1258        match frame {
1259            Frame::Integer(n) => Ok(n),
1260            other => Err(RedisError::UnexpectedResponse {
1261                expected: "integer",
1262                actual: format!("{other:?}"),
1263            }),
1264        }
1265    }
1266
1267    fn name(&self) -> &str {
1268        "ZDIFFSTORE"
1269    }
1270}
1271
1272/// ZINTERCARD numkeys key \[key ...\] \[LIMIT limit\]
1273///
1274/// Returns the cardinality of the intersection of the sorted sets given by
1275/// the specified keys. The optional `LIMIT` argument caps the work done
1276/// when the intersection cardinality reaches the limit.
1277#[derive(Clone)]
1278pub struct ZInterCard {
1279    keys: Vec<CommandArg>,
1280    limit: Option<i64>,
1281}
1282
1283impl ZInterCard {
1284    /// Create a new [`ZInterCard`] command.
1285    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
1286        Self {
1287            keys: keys.into_iter().map(Into::into).collect(),
1288            limit: None,
1289        }
1290    }
1291
1292    /// Sets the upper bound for the returned cardinality.
1293    pub fn limit(mut self, limit: i64) -> Self {
1294        self.limit = Some(limit);
1295        self
1296    }
1297}
1298
1299impl Command for ZInterCard {
1300    type Response = i64;
1301
1302    fn to_frame(&self) -> Frame {
1303        let mut args = vec![bulk("ZINTERCARD"), bulk(self.keys.len().to_string())];
1304        for key in &self.keys {
1305            args.push(bulk(key.as_bytes()));
1306        }
1307        if let Some(limit) = self.limit {
1308            args.push(bulk("LIMIT"));
1309            args.push(bulk(limit.to_string()));
1310        }
1311        array(args)
1312    }
1313
1314    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1315        match frame {
1316            Frame::Integer(n) => Ok(n),
1317            other => Err(RedisError::UnexpectedResponse {
1318                expected: "integer",
1319                actual: format!("{other:?}"),
1320            }),
1321        }
1322    }
1323
1324    fn name(&self) -> &str {
1325        "ZINTERCARD"
1326    }
1327
1328    fn idempotent(&self) -> bool {
1329        true
1330    }
1331}
1332
1333/// ZRANGESTORE dst src min max \[BYSCORE|BYLEX\] \[REV\] \[LIMIT offset count\]
1334///
1335/// Stores the specified range of members from the sorted set at `src` into
1336/// `dst`. Returns the number of elements in the resulting sorted set.
1337#[derive(Clone)]
1338pub struct ZRangeStore {
1339    dst: CommandArg,
1340    src: CommandArg,
1341    min: CommandArg,
1342    max: CommandArg,
1343    by_score: bool,
1344    by_lex: bool,
1345    rev: bool,
1346    limit: Option<(i64, i64)>,
1347}
1348
1349impl ZRangeStore {
1350    /// Create a new [`ZRangeStore`] command.
1351    pub fn new(
1352        dst: impl Into<CommandArg>,
1353        src: impl Into<CommandArg>,
1354        min: impl Into<CommandArg>,
1355        max: impl Into<CommandArg>,
1356    ) -> Self {
1357        Self {
1358            dst: dst.into(),
1359            src: src.into(),
1360            min: min.into(),
1361            max: max.into(),
1362            by_score: false,
1363            by_lex: false,
1364            rev: false,
1365            limit: None,
1366        }
1367    }
1368
1369    /// Uses score-based range interpretation.
1370    pub fn by_score(mut self) -> Self {
1371        self.by_score = true;
1372        self.by_lex = false;
1373        self
1374    }
1375
1376    /// Uses lexicographic range interpretation.
1377    pub fn by_lex(mut self) -> Self {
1378        self.by_lex = true;
1379        self.by_score = false;
1380        self
1381    }
1382
1383    /// Reverses the sort order.
1384    pub fn rev(mut self) -> Self {
1385        self.rev = true;
1386        self
1387    }
1388
1389    /// Limits the results to `count` elements starting at `offset`.
1390    pub fn limit(mut self, offset: i64, count: i64) -> Self {
1391        self.limit = Some((offset, count));
1392        self
1393    }
1394}
1395
1396impl Command for ZRangeStore {
1397    type Response = i64;
1398
1399    fn to_frame(&self) -> Frame {
1400        let mut args = vec![
1401            bulk("ZRANGESTORE"),
1402            bulk(self.dst.as_bytes()),
1403            bulk(self.src.as_bytes()),
1404            bulk(self.min.as_bytes()),
1405            bulk(self.max.as_bytes()),
1406        ];
1407        if self.by_score {
1408            args.push(bulk("BYSCORE"));
1409        } else if self.by_lex {
1410            args.push(bulk("BYLEX"));
1411        }
1412        if self.rev {
1413            args.push(bulk("REV"));
1414        }
1415        if let Some((offset, count)) = self.limit {
1416            args.push(bulk("LIMIT"));
1417            args.push(bulk(offset.to_string()));
1418            args.push(bulk(count.to_string()));
1419        }
1420        array(args)
1421    }
1422
1423    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1424        match frame {
1425            Frame::Integer(n) => Ok(n),
1426            other => Err(RedisError::UnexpectedResponse {
1427                expected: "integer",
1428                actual: format!("{other:?}"),
1429            }),
1430        }
1431    }
1432
1433    fn name(&self) -> &str {
1434        "ZRANGESTORE"
1435    }
1436}
1437
1438/// The direction argument for ZMPOP.
1439#[derive(Debug, Clone, Copy)]
1440pub enum ZMPopDirection {
1441    /// Select the `Min` mode.
1442    Min,
1443    /// Select the `Max` mode.
1444    Max,
1445}
1446
1447impl ZMPopDirection {
1448    fn as_str(&self) -> &str {
1449        match self {
1450            ZMPopDirection::Min => "MIN",
1451            ZMPopDirection::Max => "MAX",
1452        }
1453    }
1454}
1455
1456/// ZMPOP numkeys key \[key ...\] MIN|MAX \[COUNT count\]
1457///
1458/// Pops one or more members with the lowest or highest scores from the first
1459/// non-empty sorted set among the specified keys. Returns `None` when no
1460/// elements could be popped from any of the sorted sets, or
1461/// `Some((key, members))` where `key` is the name of the sorted set and
1462/// `members` is a list of `(member, score)` pairs.
1463#[derive(Clone)]
1464pub struct ZMPop {
1465    keys: Vec<CommandArg>,
1466    direction: ZMPopDirection,
1467    count: Option<i64>,
1468}
1469
1470impl ZMPop {
1471    /// Create a new [`ZMPop`] command.
1472    pub fn new(
1473        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
1474        direction: ZMPopDirection,
1475    ) -> Self {
1476        Self {
1477            keys: keys.into_iter().map(Into::into).collect(),
1478            direction,
1479            count: None,
1480        }
1481    }
1482
1483    /// Sets the number of members to pop.
1484    pub fn count(mut self, count: i64) -> Self {
1485        self.count = Some(count);
1486        self
1487    }
1488}
1489
1490impl Command for ZMPop {
1491    type Response = Option<(Bytes, Vec<(Bytes, f64)>)>;
1492
1493    fn to_frame(&self) -> Frame {
1494        let mut args = vec![bulk("ZMPOP"), bulk(self.keys.len().to_string())];
1495        for key in &self.keys {
1496            args.push(bulk(key.as_bytes()));
1497        }
1498        args.push(bulk(self.direction.as_str()));
1499        if let Some(count) = self.count {
1500            args.push(bulk("COUNT"));
1501            args.push(bulk(count.to_string()));
1502        }
1503        array(args)
1504    }
1505
1506    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1507        match frame {
1508            Frame::Array(Some(frames)) if frames.len() == 2 => {
1509                let key = match &frames[0] {
1510                    Frame::BulkString(Some(data)) => data.clone(),
1511                    other => {
1512                        return Err(RedisError::UnexpectedResponse {
1513                            expected: "bulk string (key name)",
1514                            actual: format!("{other:?}"),
1515                        });
1516                    }
1517                };
1518                let members = match &frames[1] {
1519                    Frame::Array(Some(pairs)) => pairs
1520                        .iter()
1521                        .map(|pair| match pair {
1522                            Frame::Array(Some(inner)) if inner.len() == 2 => {
1523                                let member = match &inner[0] {
1524                                    Frame::BulkString(Some(data)) => data.clone(),
1525                                    other => {
1526                                        return Err(RedisError::UnexpectedResponse {
1527                                            expected: "bulk string (member)",
1528                                            actual: format!("{other:?}"),
1529                                        });
1530                                    }
1531                                };
1532                                let score = match &inner[1] {
1533                                    Frame::BulkString(Some(data)) => {
1534                                        let s = String::from_utf8_lossy(data);
1535                                        s.parse::<f64>().map_err(|_| {
1536                                            RedisError::UnexpectedResponse {
1537                                                expected: "float string",
1538                                                actual: format!("{s}"),
1539                                            }
1540                                        })?
1541                                    }
1542                                    Frame::Double(d) => *d,
1543                                    other => {
1544                                        return Err(RedisError::UnexpectedResponse {
1545                                            expected: "bulk string or double (score)",
1546                                            actual: format!("{other:?}"),
1547                                        });
1548                                    }
1549                                };
1550                                Ok((member, score))
1551                            }
1552                            other => Err(RedisError::UnexpectedResponse {
1553                                expected: "array of [member, score]",
1554                                actual: format!("{other:?}"),
1555                            }),
1556                        })
1557                        .collect::<Result<Vec<_>, _>>()?,
1558                    other => {
1559                        return Err(RedisError::UnexpectedResponse {
1560                            expected: "array of member/score pairs",
1561                            actual: format!("{other:?}"),
1562                        });
1563                    }
1564                };
1565                Ok(Some((key, members)))
1566            }
1567            Frame::Array(None) | Frame::Null | Frame::BulkString(None) => Ok(None),
1568            other => Err(RedisError::UnexpectedResponse {
1569                expected: "two-element array or null",
1570                actual: format!("{other:?}"),
1571            }),
1572        }
1573    }
1574
1575    fn name(&self) -> &str {
1576        "ZMPOP"
1577    }
1578}
1579
1580/// ZREMRANGEBYRANK key start stop
1581///
1582/// Removes all members in the sorted set stored at `key` with rank between
1583/// `start` and `stop` (inclusive, zero-based). Returns the number of members
1584/// removed.
1585#[derive(Clone)]
1586pub struct ZRemRangeByRank {
1587    key: CommandArg,
1588    start: i64,
1589    stop: i64,
1590}
1591
1592impl ZRemRangeByRank {
1593    /// Create a new [`ZRemRangeByRank`] command.
1594    pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
1595        Self {
1596            key: key.into(),
1597            start,
1598            stop,
1599        }
1600    }
1601}
1602
1603impl Command for ZRemRangeByRank {
1604    type Response = i64;
1605
1606    fn to_frame(&self) -> Frame {
1607        array(vec![
1608            bulk("ZREMRANGEBYRANK"),
1609            bulk(self.key.as_bytes()),
1610            bulk(self.start.to_string()),
1611            bulk(self.stop.to_string()),
1612        ])
1613    }
1614
1615    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1616        match frame {
1617            Frame::Integer(n) => Ok(n),
1618            other => Err(RedisError::UnexpectedResponse {
1619                expected: "integer",
1620                actual: format!("{other:?}"),
1621            }),
1622        }
1623    }
1624
1625    fn name(&self) -> &str {
1626        "ZREMRANGEBYRANK"
1627    }
1628}
1629
1630/// ZREMRANGEBYSCORE key min max
1631///
1632/// Removes all members in the sorted set stored at `key` with a score between
1633/// `min` and `max` (inclusive). The `min` and `max` arguments can be `"-inf"`,
1634/// `"+inf"`, or numeric strings (prefix with `"("` for exclusive bounds).
1635/// Returns the number of members removed.
1636#[derive(Clone)]
1637pub struct ZRemRangeByScore {
1638    key: CommandArg,
1639    min: CommandArg,
1640    max: CommandArg,
1641}
1642
1643impl ZRemRangeByScore {
1644    /// Create a new [`ZRemRangeByScore`] command.
1645    pub fn new(
1646        key: impl Into<CommandArg>,
1647        min: impl Into<CommandArg>,
1648        max: impl Into<CommandArg>,
1649    ) -> Self {
1650        Self {
1651            key: key.into(),
1652            min: min.into(),
1653            max: max.into(),
1654        }
1655    }
1656}
1657
1658impl Command for ZRemRangeByScore {
1659    type Response = i64;
1660
1661    fn to_frame(&self) -> Frame {
1662        array(vec![
1663            bulk("ZREMRANGEBYSCORE"),
1664            bulk(self.key.as_bytes()),
1665            bulk(self.min.as_bytes()),
1666            bulk(self.max.as_bytes()),
1667        ])
1668    }
1669
1670    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1671        match frame {
1672            Frame::Integer(n) => Ok(n),
1673            other => Err(RedisError::UnexpectedResponse {
1674                expected: "integer",
1675                actual: format!("{other:?}"),
1676            }),
1677        }
1678    }
1679
1680    fn name(&self) -> &str {
1681        "ZREMRANGEBYSCORE"
1682    }
1683}
1684
1685/// ZREMRANGEBYLEX key min max
1686///
1687/// Removes all members in the sorted set stored at `key` between the
1688/// lexicographical range specified by `min` and `max`. Valid values for
1689/// `min` and `max` are `"-"`, `"+"`, `"[value"` (inclusive), or `"(value"`
1690/// (exclusive). Returns the number of members removed.
1691#[derive(Clone)]
1692pub struct ZRemRangeByLex {
1693    key: CommandArg,
1694    min: CommandArg,
1695    max: CommandArg,
1696}
1697
1698impl ZRemRangeByLex {
1699    /// Create a new [`ZRemRangeByLex`] command.
1700    pub fn new(
1701        key: impl Into<CommandArg>,
1702        min: impl Into<CommandArg>,
1703        max: impl Into<CommandArg>,
1704    ) -> Self {
1705        Self {
1706            key: key.into(),
1707            min: min.into(),
1708            max: max.into(),
1709        }
1710    }
1711}
1712
1713impl Command for ZRemRangeByLex {
1714    type Response = i64;
1715
1716    fn to_frame(&self) -> Frame {
1717        array(vec![
1718            bulk("ZREMRANGEBYLEX"),
1719            bulk(self.key.as_bytes()),
1720            bulk(self.min.as_bytes()),
1721            bulk(self.max.as_bytes()),
1722        ])
1723    }
1724
1725    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1726        match frame {
1727            Frame::Integer(n) => Ok(n),
1728            other => Err(RedisError::UnexpectedResponse {
1729                expected: "integer",
1730                actual: format!("{other:?}"),
1731            }),
1732        }
1733    }
1734
1735    fn name(&self) -> &str {
1736        "ZREMRANGEBYLEX"
1737    }
1738}
1739
1740/// ZREVRANK key member
1741///
1742/// Returns the rank of `member` in the sorted set at `key` with scores
1743/// ordered from high to low (zero-based, highest score = rank 0), or `None`
1744/// if the member or key does not exist.
1745#[derive(Clone)]
1746pub struct ZRevRank {
1747    key: CommandArg,
1748    member: CommandArg,
1749}
1750
1751impl ZRevRank {
1752    /// Create a new [`ZRevRank`] command.
1753    pub fn new(key: impl Into<CommandArg>, member: impl Into<CommandArg>) -> Self {
1754        Self {
1755            key: key.into(),
1756            member: member.into(),
1757        }
1758    }
1759}
1760
1761impl Command for ZRevRank {
1762    type Response = Option<i64>;
1763
1764    fn to_frame(&self) -> Frame {
1765        array(vec![
1766            bulk("ZREVRANK"),
1767            bulk(self.key.as_bytes()),
1768            bulk(self.member.as_bytes()),
1769        ])
1770    }
1771
1772    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1773        match frame {
1774            Frame::Integer(n) => Ok(Some(n)),
1775            Frame::Null | Frame::BulkString(None) => Ok(None),
1776            other => Err(RedisError::UnexpectedResponse {
1777                expected: "integer or null",
1778                actual: format!("{other:?}"),
1779            }),
1780        }
1781    }
1782
1783    fn name(&self) -> &str {
1784        "ZREVRANK"
1785    }
1786
1787    fn idempotent(&self) -> bool {
1788        true
1789    }
1790}
1791
1792/// Parse a flat array of bulk-string members into a `Vec<Bytes>`.
1793fn parse_member_array(frame: Frame) -> Result<Vec<Bytes>, RedisError> {
1794    match frame {
1795        Frame::Array(Some(frames)) => frames
1796            .into_iter()
1797            .map(|f| match f {
1798                Frame::BulkString(Some(data)) => Ok(data),
1799                other => Err(RedisError::UnexpectedResponse {
1800                    expected: "bulk string",
1801                    actual: format!("{other:?}"),
1802                }),
1803            })
1804            .collect(),
1805        Frame::Array(None) => Ok(Vec::new()),
1806        other => Err(RedisError::UnexpectedResponse {
1807            expected: "array",
1808            actual: format!("{other:?}"),
1809        }),
1810    }
1811}
1812
1813/// Parse a WITHSCORES response (flat `[member, score, ...]` array in RESP2 or
1814/// an array of `[member, score]` pairs in RESP3) into `Vec<(Bytes, f64)>`.
1815fn parse_member_score_pairs(frame: Frame) -> Result<Vec<(Bytes, f64)>, RedisError> {
1816    fn parse_score(frame: &Frame) -> Result<f64, RedisError> {
1817        match frame {
1818            Frame::BulkString(Some(data)) => {
1819                let s = String::from_utf8_lossy(data);
1820                s.parse::<f64>()
1821                    .map_err(|_| RedisError::UnexpectedResponse {
1822                        expected: "float string",
1823                        actual: format!("{s}"),
1824                    })
1825            }
1826            Frame::Double(d) => Ok(*d),
1827            other => Err(RedisError::UnexpectedResponse {
1828                expected: "bulk string or double",
1829                actual: format!("{other:?}"),
1830            }),
1831        }
1832    }
1833    fn parse_member(frame: &Frame) -> Result<Bytes, RedisError> {
1834        match frame {
1835            Frame::BulkString(Some(data)) => Ok(data.clone()),
1836            other => Err(RedisError::UnexpectedResponse {
1837                expected: "bulk string",
1838                actual: format!("{other:?}"),
1839            }),
1840        }
1841    }
1842    match frame {
1843        Frame::Array(None) => Ok(Vec::new()),
1844        Frame::Array(Some(frames)) => {
1845            // RESP3: array of [member, score] pairs.
1846            if frames
1847                .iter()
1848                .all(|f| matches!(f, Frame::Array(Some(inner)) if inner.len() == 2))
1849            {
1850                return frames
1851                    .iter()
1852                    .map(|pair| match pair {
1853                        Frame::Array(Some(inner)) => {
1854                            Ok((parse_member(&inner[0])?, parse_score(&inner[1])?))
1855                        }
1856                        other => Err(RedisError::UnexpectedResponse {
1857                            expected: "array of [member, score]",
1858                            actual: format!("{other:?}"),
1859                        }),
1860                    })
1861                    .collect();
1862            }
1863            // RESP2: flat [member, score, member, score, ...] array.
1864            if frames.len() % 2 != 0 {
1865                return Err(RedisError::UnexpectedResponse {
1866                    expected: "even number of elements (member/score pairs)",
1867                    actual: format!("array of length {}", frames.len()),
1868                });
1869            }
1870            frames
1871                .chunks(2)
1872                .map(|pair| Ok((parse_member(&pair[0])?, parse_score(&pair[1])?)))
1873                .collect()
1874        }
1875        other => Err(RedisError::UnexpectedResponse {
1876            expected: "array",
1877            actual: format!("{other:?}"),
1878        }),
1879    }
1880}
1881
1882/// ZADD key INCR score member
1883///
1884/// Increments the score of `member` by `score` (ZADD with the INCR flag). When
1885/// used together with NX/XX the operation may be skipped, in which case `None`
1886/// is returned; otherwise returns the new score of the member.
1887#[derive(Clone)]
1888pub struct ZAddIncr {
1889    key: CommandArg,
1890    score: f64,
1891    member: CommandArg,
1892}
1893
1894impl ZAddIncr {
1895    /// Create a new [`ZAddIncr`] command.
1896    pub fn new(key: impl Into<CommandArg>, score: f64, member: impl Into<CommandArg>) -> Self {
1897        Self {
1898            key: key.into(),
1899            score,
1900            member: member.into(),
1901        }
1902    }
1903}
1904
1905impl Command for ZAddIncr {
1906    type Response = Option<f64>;
1907
1908    fn to_frame(&self) -> Frame {
1909        array(vec![
1910            bulk("ZADD"),
1911            bulk(self.key.as_bytes()),
1912            bulk("INCR"),
1913            bulk(self.score.to_string()),
1914            bulk(self.member.as_bytes()),
1915        ])
1916    }
1917
1918    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1919        match frame {
1920            Frame::BulkString(Some(data)) => {
1921                let s = String::from_utf8_lossy(&data);
1922                let score = s
1923                    .parse::<f64>()
1924                    .map_err(|_| RedisError::UnexpectedResponse {
1925                        expected: "float string",
1926                        actual: format!("{s}"),
1927                    })?;
1928                Ok(Some(score))
1929            }
1930            Frame::Double(d) => Ok(Some(d)),
1931            Frame::BulkString(None) | Frame::Null => Ok(None),
1932            other => Err(RedisError::UnexpectedResponse {
1933                expected: "bulk string, double, or null",
1934                actual: format!("{other:?}"),
1935            }),
1936        }
1937    }
1938
1939    fn name(&self) -> &str {
1940        "ZADD"
1941    }
1942}
1943
1944/// ZDIFF numkeys key \[key ...\]
1945///
1946/// Returns the difference between the first sorted set and all successive
1947/// sorted sets. Returns only the members (without scores).
1948#[derive(Clone)]
1949pub struct ZDiff {
1950    keys: Vec<CommandArg>,
1951}
1952
1953impl ZDiff {
1954    /// Create a new [`ZDiff`] command.
1955    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
1956        Self {
1957            keys: keys.into_iter().map(Into::into).collect(),
1958        }
1959    }
1960}
1961
1962impl Command for ZDiff {
1963    type Response = Vec<Bytes>;
1964
1965    fn to_frame(&self) -> Frame {
1966        let mut args = vec![bulk("ZDIFF"), bulk(self.keys.len().to_string())];
1967        for key in &self.keys {
1968            args.push(bulk(key.as_bytes()));
1969        }
1970        array(args)
1971    }
1972
1973    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1974        parse_member_array(frame)
1975    }
1976
1977    fn name(&self) -> &str {
1978        "ZDIFF"
1979    }
1980
1981    fn idempotent(&self) -> bool {
1982        true
1983    }
1984}
1985
1986/// ZDIFF numkeys key \[key ...\] WITHSCORES
1987///
1988/// Returns the difference between the first sorted set and all successive
1989/// sorted sets, including each member's score.
1990#[derive(Clone)]
1991pub struct ZDiffWithScores {
1992    keys: Vec<CommandArg>,
1993}
1994
1995impl ZDiffWithScores {
1996    /// Create a new [`ZDiffWithScores`] command.
1997    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
1998        Self {
1999            keys: keys.into_iter().map(Into::into).collect(),
2000        }
2001    }
2002}
2003
2004impl Command for ZDiffWithScores {
2005    type Response = Vec<(Bytes, f64)>;
2006
2007    fn to_frame(&self) -> Frame {
2008        let mut args = vec![bulk("ZDIFF"), bulk(self.keys.len().to_string())];
2009        for key in &self.keys {
2010            args.push(bulk(key.as_bytes()));
2011        }
2012        args.push(bulk("WITHSCORES"));
2013        array(args)
2014    }
2015
2016    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2017        parse_member_score_pairs(frame)
2018    }
2019
2020    fn name(&self) -> &str {
2021        "ZDIFF"
2022    }
2023
2024    fn idempotent(&self) -> bool {
2025        true
2026    }
2027}
2028
2029/// ZUNION numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\]
2030///
2031/// Returns the union of the sorted sets given by the specified keys. Returns
2032/// only the members (without scores).
2033#[derive(Clone)]
2034pub struct ZUnion {
2035    keys: Vec<CommandArg>,
2036    weights: Option<Vec<f64>>,
2037    aggregate: Option<Aggregate>,
2038}
2039
2040impl ZUnion {
2041    /// Create a new [`ZUnion`] command.
2042    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
2043        Self {
2044            keys: keys.into_iter().map(Into::into).collect(),
2045            weights: None,
2046            aggregate: None,
2047        }
2048    }
2049
2050    /// Sets the weight multipliers for each input sorted set.
2051    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
2052        self.weights = Some(weights.into_iter().collect());
2053        self
2054    }
2055
2056    /// Sets the aggregation function for combining scores.
2057    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
2058        self.aggregate = Some(aggregate);
2059        self
2060    }
2061}
2062
2063impl Command for ZUnion {
2064    type Response = Vec<Bytes>;
2065
2066    fn to_frame(&self) -> Frame {
2067        let mut args = vec![bulk("ZUNION"), bulk(self.keys.len().to_string())];
2068        for key in &self.keys {
2069            args.push(bulk(key.as_bytes()));
2070        }
2071        if let Some(weights) = &self.weights {
2072            args.push(bulk("WEIGHTS"));
2073            for w in weights {
2074                args.push(bulk(w.to_string()));
2075            }
2076        }
2077        if let Some(agg) = &self.aggregate {
2078            args.push(bulk("AGGREGATE"));
2079            args.push(bulk(agg.as_str()));
2080        }
2081        array(args)
2082    }
2083
2084    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2085        parse_member_array(frame)
2086    }
2087
2088    fn name(&self) -> &str {
2089        "ZUNION"
2090    }
2091
2092    fn idempotent(&self) -> bool {
2093        true
2094    }
2095}
2096
2097/// ZUNION numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\] WITHSCORES
2098///
2099/// Returns the union of the sorted sets given by the specified keys, including
2100/// each member's score.
2101#[derive(Clone)]
2102pub struct ZUnionWithScores {
2103    keys: Vec<CommandArg>,
2104    weights: Option<Vec<f64>>,
2105    aggregate: Option<Aggregate>,
2106}
2107
2108impl ZUnionWithScores {
2109    /// Create a new [`ZUnionWithScores`] command.
2110    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
2111        Self {
2112            keys: keys.into_iter().map(Into::into).collect(),
2113            weights: None,
2114            aggregate: None,
2115        }
2116    }
2117
2118    /// Sets the weight multipliers for each input sorted set.
2119    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
2120        self.weights = Some(weights.into_iter().collect());
2121        self
2122    }
2123
2124    /// Sets the aggregation function for combining scores.
2125    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
2126        self.aggregate = Some(aggregate);
2127        self
2128    }
2129}
2130
2131impl Command for ZUnionWithScores {
2132    type Response = Vec<(Bytes, f64)>;
2133
2134    fn to_frame(&self) -> Frame {
2135        let mut args = vec![bulk("ZUNION"), bulk(self.keys.len().to_string())];
2136        for key in &self.keys {
2137            args.push(bulk(key.as_bytes()));
2138        }
2139        if let Some(weights) = &self.weights {
2140            args.push(bulk("WEIGHTS"));
2141            for w in weights {
2142                args.push(bulk(w.to_string()));
2143            }
2144        }
2145        if let Some(agg) = &self.aggregate {
2146            args.push(bulk("AGGREGATE"));
2147            args.push(bulk(agg.as_str()));
2148        }
2149        args.push(bulk("WITHSCORES"));
2150        array(args)
2151    }
2152
2153    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2154        parse_member_score_pairs(frame)
2155    }
2156
2157    fn name(&self) -> &str {
2158        "ZUNION"
2159    }
2160
2161    fn idempotent(&self) -> bool {
2162        true
2163    }
2164}
2165
2166/// ZINTER numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\]
2167///
2168/// Returns the intersection of the sorted sets given by the specified keys.
2169/// Returns only the members (without scores).
2170#[derive(Clone)]
2171pub struct ZInter {
2172    keys: Vec<CommandArg>,
2173    weights: Option<Vec<f64>>,
2174    aggregate: Option<Aggregate>,
2175}
2176
2177impl ZInter {
2178    /// Create a new [`ZInter`] command.
2179    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
2180        Self {
2181            keys: keys.into_iter().map(Into::into).collect(),
2182            weights: None,
2183            aggregate: None,
2184        }
2185    }
2186
2187    /// Sets the weight multipliers for each input sorted set.
2188    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
2189        self.weights = Some(weights.into_iter().collect());
2190        self
2191    }
2192
2193    /// Sets the aggregation function for combining scores.
2194    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
2195        self.aggregate = Some(aggregate);
2196        self
2197    }
2198}
2199
2200impl Command for ZInter {
2201    type Response = Vec<Bytes>;
2202
2203    fn to_frame(&self) -> Frame {
2204        let mut args = vec![bulk("ZINTER"), bulk(self.keys.len().to_string())];
2205        for key in &self.keys {
2206            args.push(bulk(key.as_bytes()));
2207        }
2208        if let Some(weights) = &self.weights {
2209            args.push(bulk("WEIGHTS"));
2210            for w in weights {
2211                args.push(bulk(w.to_string()));
2212            }
2213        }
2214        if let Some(agg) = &self.aggregate {
2215            args.push(bulk("AGGREGATE"));
2216            args.push(bulk(agg.as_str()));
2217        }
2218        array(args)
2219    }
2220
2221    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2222        parse_member_array(frame)
2223    }
2224
2225    fn name(&self) -> &str {
2226        "ZINTER"
2227    }
2228
2229    fn idempotent(&self) -> bool {
2230        true
2231    }
2232}
2233
2234/// ZINTER numkeys key \[key ...\] \[WEIGHTS weight ...\] \[AGGREGATE SUM|MIN|MAX\] WITHSCORES
2235///
2236/// Returns the intersection of the sorted sets given by the specified keys,
2237/// including each member's score.
2238#[derive(Clone)]
2239pub struct ZInterWithScores {
2240    keys: Vec<CommandArg>,
2241    weights: Option<Vec<f64>>,
2242    aggregate: Option<Aggregate>,
2243}
2244
2245impl ZInterWithScores {
2246    /// Create a new [`ZInterWithScores`] command.
2247    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
2248        Self {
2249            keys: keys.into_iter().map(Into::into).collect(),
2250            weights: None,
2251            aggregate: None,
2252        }
2253    }
2254
2255    /// Sets the weight multipliers for each input sorted set.
2256    pub fn weights(mut self, weights: impl IntoIterator<Item = f64>) -> Self {
2257        self.weights = Some(weights.into_iter().collect());
2258        self
2259    }
2260
2261    /// Sets the aggregation function for combining scores.
2262    pub fn aggregate(mut self, aggregate: Aggregate) -> Self {
2263        self.aggregate = Some(aggregate);
2264        self
2265    }
2266}
2267
2268impl Command for ZInterWithScores {
2269    type Response = Vec<(Bytes, f64)>;
2270
2271    fn to_frame(&self) -> Frame {
2272        let mut args = vec![bulk("ZINTER"), bulk(self.keys.len().to_string())];
2273        for key in &self.keys {
2274            args.push(bulk(key.as_bytes()));
2275        }
2276        if let Some(weights) = &self.weights {
2277            args.push(bulk("WEIGHTS"));
2278            for w in weights {
2279                args.push(bulk(w.to_string()));
2280            }
2281        }
2282        if let Some(agg) = &self.aggregate {
2283            args.push(bulk("AGGREGATE"));
2284            args.push(bulk(agg.as_str()));
2285        }
2286        args.push(bulk("WITHSCORES"));
2287        array(args)
2288    }
2289
2290    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2291        parse_member_score_pairs(frame)
2292    }
2293
2294    fn name(&self) -> &str {
2295        "ZINTER"
2296    }
2297
2298    fn idempotent(&self) -> bool {
2299        true
2300    }
2301}
2302
2303/// BZMPOP timeout numkeys key \[key ...\] MIN|MAX \[COUNT count\]
2304///
2305/// Blocking variant of ZMPOP. Pops one or more members with the lowest or
2306/// highest scores from the first non-empty sorted set among the specified
2307/// keys, blocking up to `timeout` seconds (0 to block indefinitely). Returns
2308/// `None` on timeout, or `Some((key, members))` where `members` is a list of
2309/// `(member, score)` pairs.
2310#[derive(Clone)]
2311pub struct BZMPop {
2312    timeout: f64,
2313    keys: Vec<CommandArg>,
2314    direction: ZMPopDirection,
2315    count: Option<u64>,
2316}
2317
2318impl BZMPop {
2319    /// Create a new [`BZMPop`] command.
2320    pub fn new(
2321        timeout: f64,
2322        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
2323        direction: ZMPopDirection,
2324    ) -> Self {
2325        Self {
2326            timeout,
2327            keys: keys.into_iter().map(Into::into).collect(),
2328            direction,
2329            count: None,
2330        }
2331    }
2332
2333    /// Sets the number of members to pop.
2334    pub fn count(mut self, count: u64) -> Self {
2335        self.count = Some(count);
2336        self
2337    }
2338}
2339
2340impl Command for BZMPop {
2341    type Response = Option<(Bytes, Vec<(Bytes, f64)>)>;
2342
2343    fn to_frame(&self) -> Frame {
2344        let mut args = vec![
2345            bulk("BZMPOP"),
2346            bulk(self.timeout.to_string()),
2347            bulk(self.keys.len().to_string()),
2348        ];
2349        for key in &self.keys {
2350            args.push(bulk(key.as_bytes()));
2351        }
2352        args.push(bulk(self.direction.as_str()));
2353        if let Some(count) = self.count {
2354            args.push(bulk("COUNT"));
2355            args.push(bulk(count.to_string()));
2356        }
2357        array(args)
2358    }
2359
2360    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2361        match frame {
2362            Frame::Array(Some(frames)) if frames.len() == 2 => {
2363                let key = match &frames[0] {
2364                    Frame::BulkString(Some(data)) => data.clone(),
2365                    other => {
2366                        return Err(RedisError::UnexpectedResponse {
2367                            expected: "bulk string (key name)",
2368                            actual: format!("{other:?}"),
2369                        });
2370                    }
2371                };
2372                let members = match &frames[1] {
2373                    Frame::Array(Some(pairs)) => pairs
2374                        .iter()
2375                        .map(|pair| match pair {
2376                            Frame::Array(Some(inner)) if inner.len() == 2 => {
2377                                let member = match &inner[0] {
2378                                    Frame::BulkString(Some(data)) => data.clone(),
2379                                    other => {
2380                                        return Err(RedisError::UnexpectedResponse {
2381                                            expected: "bulk string (member)",
2382                                            actual: format!("{other:?}"),
2383                                        });
2384                                    }
2385                                };
2386                                let score = match &inner[1] {
2387                                    Frame::BulkString(Some(data)) => {
2388                                        let s = String::from_utf8_lossy(data);
2389                                        s.parse::<f64>().map_err(|_| {
2390                                            RedisError::UnexpectedResponse {
2391                                                expected: "float string",
2392                                                actual: format!("{s}"),
2393                                            }
2394                                        })?
2395                                    }
2396                                    Frame::Double(d) => *d,
2397                                    other => {
2398                                        return Err(RedisError::UnexpectedResponse {
2399                                            expected: "bulk string or double (score)",
2400                                            actual: format!("{other:?}"),
2401                                        });
2402                                    }
2403                                };
2404                                Ok((member, score))
2405                            }
2406                            other => Err(RedisError::UnexpectedResponse {
2407                                expected: "array of [member, score]",
2408                                actual: format!("{other:?}"),
2409                            }),
2410                        })
2411                        .collect::<Result<Vec<_>, _>>()?,
2412                    other => {
2413                        return Err(RedisError::UnexpectedResponse {
2414                            expected: "array of member/score pairs",
2415                            actual: format!("{other:?}"),
2416                        });
2417                    }
2418                };
2419                Ok(Some((key, members)))
2420            }
2421            Frame::Array(None) | Frame::Null | Frame::BulkString(None) => Ok(None),
2422            other => Err(RedisError::UnexpectedResponse {
2423                expected: "two-element array or null",
2424                actual: format!("{other:?}"),
2425            }),
2426        }
2427    }
2428
2429    fn name(&self) -> &str {
2430        "BZMPOP"
2431    }
2432}
2433
2434/// ZREVRANGE key start stop
2435///
2436/// Returns the specified range of members in the sorted set stored at `key`,
2437/// ordered from highest to lowest score. `start` and `stop` are zero-based
2438/// indices, where -1 is the last element.
2439///
2440/// Deprecated since Redis 6.2 in favor of `ZRANGE ... REV`, but still widely
2441/// used. Use [`ZRevRangeWithScores`] to also return each member's score.
2442#[derive(Clone)]
2443pub struct ZRevRange {
2444    key: CommandArg,
2445    start: i64,
2446    stop: i64,
2447}
2448
2449impl ZRevRange {
2450    /// Create a new [`ZRevRange`] command.
2451    pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
2452        Self {
2453            key: key.into(),
2454            start,
2455            stop,
2456        }
2457    }
2458}
2459
2460impl Command for ZRevRange {
2461    type Response = Vec<Bytes>;
2462
2463    fn to_frame(&self) -> Frame {
2464        array(vec![
2465            bulk("ZREVRANGE"),
2466            bulk(self.key.as_bytes()),
2467            bulk(self.start.to_string()),
2468            bulk(self.stop.to_string()),
2469        ])
2470    }
2471
2472    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2473        parse_member_array(frame)
2474    }
2475
2476    fn name(&self) -> &str {
2477        "ZREVRANGE"
2478    }
2479
2480    fn idempotent(&self) -> bool {
2481        true
2482    }
2483}
2484
2485/// ZREVRANGE key start stop WITHSCORES
2486///
2487/// Returns the specified range of members in the sorted set stored at `key`,
2488/// ordered from highest to lowest score, including each member's score.
2489///
2490/// Deprecated since Redis 6.2 in favor of `ZRANGE ... REV WITHSCORES`.
2491#[derive(Clone)]
2492pub struct ZRevRangeWithScores {
2493    key: CommandArg,
2494    start: i64,
2495    stop: i64,
2496}
2497
2498impl ZRevRangeWithScores {
2499    /// Create a new [`ZRevRangeWithScores`] command.
2500    pub fn new(key: impl Into<CommandArg>, start: i64, stop: i64) -> Self {
2501        Self {
2502            key: key.into(),
2503            start,
2504            stop,
2505        }
2506    }
2507}
2508
2509impl Command for ZRevRangeWithScores {
2510    type Response = Vec<(Bytes, f64)>;
2511
2512    fn to_frame(&self) -> Frame {
2513        array(vec![
2514            bulk("ZREVRANGE"),
2515            bulk(self.key.as_bytes()),
2516            bulk(self.start.to_string()),
2517            bulk(self.stop.to_string()),
2518            bulk("WITHSCORES"),
2519        ])
2520    }
2521
2522    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2523        parse_member_score_pairs(frame)
2524    }
2525
2526    fn name(&self) -> &str {
2527        "ZREVRANGE"
2528    }
2529
2530    fn idempotent(&self) -> bool {
2531        true
2532    }
2533}
2534
2535/// ZRANGEBYLEX key min max \[LIMIT offset count\]
2536///
2537/// Returns all members in the sorted set at `key` between the lexicographical
2538/// range specified by `min` and `max`. Valid values for `min` and `max` are
2539/// `"-"`, `"+"`, `"[value"` (inclusive), or `"(value"` (exclusive). Assumes
2540/// all members share the same score.
2541///
2542/// Deprecated since Redis 6.2 in favor of `ZRANGE ... BYLEX`.
2543#[derive(Clone)]
2544pub struct ZRangeByLex {
2545    key: CommandArg,
2546    min: CommandArg,
2547    max: CommandArg,
2548    limit: Option<(i64, i64)>,
2549}
2550
2551impl ZRangeByLex {
2552    /// Create a new [`ZRangeByLex`] command.
2553    pub fn new(
2554        key: impl Into<CommandArg>,
2555        min: impl Into<CommandArg>,
2556        max: impl Into<CommandArg>,
2557    ) -> Self {
2558        Self {
2559            key: key.into(),
2560            min: min.into(),
2561            max: max.into(),
2562            limit: None,
2563        }
2564    }
2565
2566    /// Limits the results to `count` elements starting at `offset`.
2567    pub fn limit(mut self, offset: i64, count: i64) -> Self {
2568        self.limit = Some((offset, count));
2569        self
2570    }
2571}
2572
2573impl Command for ZRangeByLex {
2574    type Response = Vec<Bytes>;
2575
2576    fn to_frame(&self) -> Frame {
2577        let mut args = vec![
2578            bulk("ZRANGEBYLEX"),
2579            bulk(self.key.as_bytes()),
2580            bulk(self.min.as_bytes()),
2581            bulk(self.max.as_bytes()),
2582        ];
2583        if let Some((offset, count)) = self.limit {
2584            args.push(bulk("LIMIT"));
2585            args.push(bulk(offset.to_string()));
2586            args.push(bulk(count.to_string()));
2587        }
2588        array(args)
2589    }
2590
2591    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2592        parse_member_array(frame)
2593    }
2594
2595    fn name(&self) -> &str {
2596        "ZRANGEBYLEX"
2597    }
2598
2599    fn idempotent(&self) -> bool {
2600        true
2601    }
2602}
2603
2604/// ZREVRANGEBYLEX key max min \[LIMIT offset count\]
2605///
2606/// Returns all members in the sorted set at `key` between the lexicographical
2607/// range specified by `max` and `min`, ordered from higher to lower. Note the
2608/// reversed argument order: `max` comes before `min`. Valid values for `min`
2609/// and `max` are `"-"`, `"+"`, `"[value"` (inclusive), or `"(value"`
2610/// (exclusive). Assumes all members share the same score.
2611///
2612/// Deprecated since Redis 6.2 in favor of `ZRANGE ... BYLEX REV`.
2613#[derive(Clone)]
2614pub struct ZRevRangeByLex {
2615    key: CommandArg,
2616    max: CommandArg,
2617    min: CommandArg,
2618    limit: Option<(i64, i64)>,
2619}
2620
2621impl ZRevRangeByLex {
2622    /// Create a new [`ZRevRangeByLex`] command.
2623    pub fn new(
2624        key: impl Into<CommandArg>,
2625        max: impl Into<CommandArg>,
2626        min: impl Into<CommandArg>,
2627    ) -> Self {
2628        Self {
2629            key: key.into(),
2630            max: max.into(),
2631            min: min.into(),
2632            limit: None,
2633        }
2634    }
2635
2636    /// Limits the results to `count` elements starting at `offset`.
2637    pub fn limit(mut self, offset: i64, count: i64) -> Self {
2638        self.limit = Some((offset, count));
2639        self
2640    }
2641}
2642
2643impl Command for ZRevRangeByLex {
2644    type Response = Vec<Bytes>;
2645
2646    fn to_frame(&self) -> Frame {
2647        let mut args = vec![
2648            bulk("ZREVRANGEBYLEX"),
2649            bulk(self.key.as_bytes()),
2650            bulk(self.max.as_bytes()),
2651            bulk(self.min.as_bytes()),
2652        ];
2653        if let Some((offset, count)) = self.limit {
2654            args.push(bulk("LIMIT"));
2655            args.push(bulk(offset.to_string()));
2656            args.push(bulk(count.to_string()));
2657        }
2658        array(args)
2659    }
2660
2661    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2662        parse_member_array(frame)
2663    }
2664
2665    fn name(&self) -> &str {
2666        "ZREVRANGEBYLEX"
2667    }
2668
2669    fn idempotent(&self) -> bool {
2670        true
2671    }
2672}
2673
2674/// ZREVRANGEBYSCORE key max min \[LIMIT offset count\]
2675///
2676/// Returns all members in the sorted set at `key` with a score between `min`
2677/// and `max`, ordered from highest to lowest score. Note the reversed argument
2678/// order: `max` comes before `min`. The `min` and `max` arguments can be
2679/// `"-inf"`, `"+inf"`, or numeric strings (prefix with `"("` for exclusive
2680/// bounds). Use [`ZRevRangeByScoreWithScores`] to also return each member's
2681/// score.
2682///
2683/// Deprecated since Redis 6.2 in favor of `ZRANGE ... BYSCORE REV`.
2684#[derive(Clone)]
2685pub struct ZRevRangeByScore {
2686    key: CommandArg,
2687    max: CommandArg,
2688    min: CommandArg,
2689    limit: Option<(i64, i64)>,
2690}
2691
2692impl ZRevRangeByScore {
2693    /// Create a new [`ZRevRangeByScore`] command.
2694    pub fn new(
2695        key: impl Into<CommandArg>,
2696        max: impl Into<CommandArg>,
2697        min: impl Into<CommandArg>,
2698    ) -> Self {
2699        Self {
2700            key: key.into(),
2701            max: max.into(),
2702            min: min.into(),
2703            limit: None,
2704        }
2705    }
2706
2707    /// Limits the results to `count` elements starting at `offset`.
2708    pub fn limit(mut self, offset: i64, count: i64) -> Self {
2709        self.limit = Some((offset, count));
2710        self
2711    }
2712}
2713
2714impl Command for ZRevRangeByScore {
2715    type Response = Vec<Bytes>;
2716
2717    fn to_frame(&self) -> Frame {
2718        let mut args = vec![
2719            bulk("ZREVRANGEBYSCORE"),
2720            bulk(self.key.as_bytes()),
2721            bulk(self.max.as_bytes()),
2722            bulk(self.min.as_bytes()),
2723        ];
2724        if let Some((offset, count)) = self.limit {
2725            args.push(bulk("LIMIT"));
2726            args.push(bulk(offset.to_string()));
2727            args.push(bulk(count.to_string()));
2728        }
2729        array(args)
2730    }
2731
2732    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2733        parse_member_array(frame)
2734    }
2735
2736    fn name(&self) -> &str {
2737        "ZREVRANGEBYSCORE"
2738    }
2739
2740    fn idempotent(&self) -> bool {
2741        true
2742    }
2743}
2744
2745/// ZREVRANGEBYSCORE key max min WITHSCORES \[LIMIT offset count\]
2746///
2747/// Returns all members in the sorted set at `key` with a score between `min`
2748/// and `max`, ordered from highest to lowest score, including each member's
2749/// score. Note the reversed argument order: `max` comes before `min`.
2750///
2751/// Deprecated since Redis 6.2 in favor of `ZRANGE ... BYSCORE REV WITHSCORES`.
2752#[derive(Clone)]
2753pub struct ZRevRangeByScoreWithScores {
2754    key: CommandArg,
2755    max: CommandArg,
2756    min: CommandArg,
2757    limit: Option<(i64, i64)>,
2758}
2759
2760impl ZRevRangeByScoreWithScores {
2761    /// Create a new [`ZRevRangeByScoreWithScores`] command.
2762    pub fn new(
2763        key: impl Into<CommandArg>,
2764        max: impl Into<CommandArg>,
2765        min: impl Into<CommandArg>,
2766    ) -> Self {
2767        Self {
2768            key: key.into(),
2769            max: max.into(),
2770            min: min.into(),
2771            limit: None,
2772        }
2773    }
2774
2775    /// Limits the results to `count` elements starting at `offset`.
2776    pub fn limit(mut self, offset: i64, count: i64) -> Self {
2777        self.limit = Some((offset, count));
2778        self
2779    }
2780}
2781
2782impl Command for ZRevRangeByScoreWithScores {
2783    type Response = Vec<(Bytes, f64)>;
2784
2785    fn to_frame(&self) -> Frame {
2786        let mut args = vec![
2787            bulk("ZREVRANGEBYSCORE"),
2788            bulk(self.key.as_bytes()),
2789            bulk(self.max.as_bytes()),
2790            bulk(self.min.as_bytes()),
2791            bulk("WITHSCORES"),
2792        ];
2793        if let Some((offset, count)) = self.limit {
2794            args.push(bulk("LIMIT"));
2795            args.push(bulk(offset.to_string()));
2796            args.push(bulk(count.to_string()));
2797        }
2798        array(args)
2799    }
2800
2801    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2802        parse_member_score_pairs(frame)
2803    }
2804
2805    fn name(&self) -> &str {
2806        "ZREVRANGEBYSCORE"
2807    }
2808
2809    fn idempotent(&self) -> bool {
2810        true
2811    }
2812}
2813
2814#[cfg(test)]
2815mod tests {
2816    use super::*;
2817    use redis_tower_core::Command;
2818    use redis_tower_protocol::Frame;
2819    use redis_tower_protocol::helpers::{array, bulk};
2820
2821    // -- ZAdd --
2822
2823    #[test]
2824    fn zadd_to_frame() {
2825        let cmd = ZAdd::new("myzset").member(1.0, "a").member(2.0, "b");
2826        assert_eq!(
2827            cmd.to_frame(),
2828            array(vec![
2829                bulk("ZADD"),
2830                bulk("myzset"),
2831                bulk("1"),
2832                bulk("a"),
2833                bulk("2"),
2834                bulk("b"),
2835            ])
2836        );
2837    }
2838
2839    #[test]
2840    fn zadd_parse_integer() {
2841        let cmd = ZAdd::new("myzset").member(1.0, "a");
2842        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
2843    }
2844
2845    #[test]
2846    fn zadd_parse_error_on_string() {
2847        let cmd = ZAdd::new("myzset").member(1.0, "a");
2848        assert!(
2849            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2850                .is_err()
2851        );
2852    }
2853
2854    #[test]
2855    fn zadd_from_members_to_frame() {
2856        let cmd = ZAdd::from_members("myzset", [(1.0_f64, "a"), (2.0_f64, "b")]);
2857        assert_eq!(
2858            cmd.to_frame(),
2859            array(vec![
2860                bulk("ZADD"),
2861                bulk("myzset"),
2862                bulk("1"),
2863                bulk("a"),
2864                bulk("2"),
2865                bulk("b"),
2866            ])
2867        );
2868    }
2869
2870    #[test]
2871    fn zadd_from_members_matches_incremental() {
2872        let incremental = ZAdd::new("z").member(1.0, "a").member(2.0, "b");
2873        let bulk = ZAdd::from_members("z", [(1.0_f64, "a"), (2.0_f64, "b")]);
2874        assert_eq!(incremental.to_frame(), bulk.to_frame());
2875    }
2876
2877    #[test]
2878    fn zadd_from_members_vec() {
2879        let scores: Vec<(f64, &str)> = vec![(100.0, "alice"), (200.0, "bob"), (150.0, "carol")];
2880        let cmd = ZAdd::from_members("leaderboard", scores);
2881        assert_eq!(
2882            cmd.to_frame(),
2883            array(vec![
2884                bulk("ZADD"),
2885                bulk("leaderboard"),
2886                bulk("100"),
2887                bulk("alice"),
2888                bulk("200"),
2889                bulk("bob"),
2890                bulk("150"),
2891                bulk("carol"),
2892            ])
2893        );
2894    }
2895
2896    #[test]
2897    fn zadd_from_members_with_options() {
2898        // Verify that option flags can be chained after from_members
2899        let cmd = ZAdd::from_members("z", [(1.0_f64, "a")]).ch();
2900        match cmd.to_frame() {
2901            Frame::Array(Some(args)) => {
2902                assert_eq!(args[0], bulk("ZADD"));
2903                assert_eq!(args[1], bulk("z"));
2904                assert!(args.contains(&bulk("CH")));
2905            }
2906            _ => panic!("expected array"),
2907        }
2908    }
2909
2910    // -- ZRem --
2911
2912    #[test]
2913    fn zrem_to_frame() {
2914        let cmd = ZRem::new("myzset", "a");
2915        assert_eq!(
2916            cmd.to_frame(),
2917            array(vec![bulk("ZREM"), bulk("myzset"), bulk("a")])
2918        );
2919    }
2920
2921    // -- ZRange --
2922
2923    #[test]
2924    fn zrange_to_frame() {
2925        let cmd = ZRange::new("myzset", 0, -1);
2926        assert_eq!(
2927            cmd.to_frame(),
2928            array(vec![bulk("ZRANGE"), bulk("myzset"), bulk("0"), bulk("-1"),])
2929        );
2930    }
2931
2932    #[test]
2933    fn zrange_parse_array() {
2934        let cmd = ZRange::new("myzset", 0, -1);
2935        let frame = array(vec![
2936            Frame::BulkString(Some(Bytes::from("a"))),
2937            Frame::BulkString(Some(Bytes::from("b"))),
2938        ]);
2939        let result = cmd.parse_response(frame).unwrap();
2940        assert_eq!(result, vec![Bytes::from("a"), Bytes::from("b")]);
2941    }
2942
2943    #[test]
2944    fn zrange_parse_error_on_integer() {
2945        let cmd = ZRange::new("myzset", 0, -1);
2946        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2947    }
2948
2949    // -- ZScore --
2950
2951    #[test]
2952    fn zscore_to_frame() {
2953        let cmd = ZScore::new("myzset", "a");
2954        assert_eq!(
2955            cmd.to_frame(),
2956            array(vec![bulk("ZSCORE"), bulk("myzset"), bulk("a")])
2957        );
2958    }
2959
2960    #[test]
2961    fn zscore_parse_bulk_string() {
2962        let cmd = ZScore::new("myzset", "a");
2963        let frame = Frame::BulkString(Some(Bytes::from("1.5")));
2964        let result = cmd.parse_response(frame).unwrap().unwrap();
2965        assert!((result - 1.5).abs() < f64::EPSILON);
2966    }
2967
2968    #[test]
2969    fn zscore_parse_double() {
2970        let cmd = ZScore::new("myzset", "a");
2971        let result = cmd.parse_response(Frame::Double(2.5)).unwrap().unwrap();
2972        assert!((result - 2.5).abs() < f64::EPSILON);
2973    }
2974
2975    #[test]
2976    fn zscore_parse_null() {
2977        let cmd = ZScore::new("myzset", "missing");
2978        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
2979    }
2980
2981    #[test]
2982    fn zscore_parse_error_on_integer() {
2983        let cmd = ZScore::new("myzset", "a");
2984        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2985    }
2986
2987    // -- ZCard --
2988
2989    #[test]
2990    fn zcard_to_frame() {
2991        let cmd = ZCard::new("myzset");
2992        assert_eq!(cmd.to_frame(), array(vec![bulk("ZCARD"), bulk("myzset")]));
2993    }
2994
2995    // -- ZIncrBy --
2996
2997    #[test]
2998    fn zincrby_to_frame() {
2999        let cmd = ZIncrBy::new("myzset", 2.0, "member");
3000        assert_eq!(
3001            cmd.to_frame(),
3002            array(vec![
3003                bulk("ZINCRBY"),
3004                bulk("myzset"),
3005                bulk("2"),
3006                bulk("member"),
3007            ])
3008        );
3009    }
3010
3011    #[test]
3012    fn zincrby_parse_bulk_string() {
3013        let cmd = ZIncrBy::new("myzset", 2.0, "m");
3014        let frame = Frame::BulkString(Some(Bytes::from("5.0")));
3015        let result = cmd.parse_response(frame).unwrap();
3016        assert!((result - 5.0).abs() < f64::EPSILON);
3017    }
3018
3019    #[test]
3020    fn zincrby_parse_double() {
3021        let cmd = ZIncrBy::new("myzset", 2.0, "m");
3022        assert!((cmd.parse_response(Frame::Double(5.0)).unwrap() - 5.0).abs() < f64::EPSILON);
3023    }
3024
3025    // -- ZRank --
3026
3027    #[test]
3028    fn zrank_to_frame() {
3029        let cmd = ZRank::new("myzset", "member");
3030        assert_eq!(
3031            cmd.to_frame(),
3032            array(vec![bulk("ZRANK"), bulk("myzset"), bulk("member")])
3033        );
3034    }
3035
3036    #[test]
3037    fn zrank_parse_integer() {
3038        let cmd = ZRank::new("myzset", "m");
3039        assert_eq!(cmd.parse_response(Frame::Integer(0)).unwrap(), Some(0));
3040    }
3041
3042    #[test]
3043    fn zrank_parse_null() {
3044        let cmd = ZRank::new("myzset", "m");
3045        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
3046    }
3047
3048    // -- ZPopMin --
3049
3050    #[test]
3051    fn zpopmin_to_frame() {
3052        let cmd = ZPopMin::new("myzset").count(2);
3053        assert_eq!(
3054            cmd.to_frame(),
3055            array(vec![bulk("ZPOPMIN"), bulk("myzset"), bulk("2")])
3056        );
3057    }
3058
3059    #[test]
3060    fn zpopmin_parse_pairs() {
3061        let cmd = ZPopMin::new("myzset");
3062        let frame = array(vec![
3063            Frame::BulkString(Some(Bytes::from("a"))),
3064            Frame::BulkString(Some(Bytes::from("1.0"))),
3065            Frame::BulkString(Some(Bytes::from("b"))),
3066            Frame::BulkString(Some(Bytes::from("2.0"))),
3067        ]);
3068        let result = cmd.parse_response(frame).unwrap();
3069        assert_eq!(result.len(), 2);
3070        assert_eq!(result[0].0, Bytes::from("a"));
3071        assert!((result[0].1 - 1.0).abs() < f64::EPSILON);
3072        assert_eq!(result[1].0, Bytes::from("b"));
3073    }
3074
3075    #[test]
3076    fn zpopmin_parse_empty() {
3077        let cmd = ZPopMin::new("myzset");
3078        let result = cmd.parse_response(Frame::Array(None)).unwrap();
3079        assert!(result.is_empty());
3080    }
3081
3082    // -- ZInterStore --
3083
3084    #[test]
3085    fn zinterstore_to_frame() {
3086        let cmd = ZInterStore::new("dest", vec!["s1", "s2"])
3087            .weights(vec![1.0, 2.0])
3088            .aggregate(Aggregate::Max);
3089        let frame = cmd.to_frame();
3090        match frame {
3091            Frame::Array(Some(args)) => {
3092                assert_eq!(args[0], bulk("ZINTERSTORE"));
3093                assert_eq!(args[1], bulk("dest"));
3094                assert_eq!(args[2], bulk("2"));
3095                assert_eq!(args[3], bulk("s1"));
3096                assert_eq!(args[4], bulk("s2"));
3097                assert!(args.contains(&bulk("WEIGHTS")));
3098                assert!(args.contains(&bulk("AGGREGATE")));
3099                assert!(args.contains(&bulk("MAX")));
3100            }
3101            _ => panic!("expected array"),
3102        }
3103    }
3104
3105    // -- ZMScore --
3106
3107    #[test]
3108    fn zmscore_to_frame() {
3109        let cmd = ZMScore::members("myzset", vec!["a", "b"]);
3110        assert_eq!(
3111            cmd.to_frame(),
3112            array(vec![bulk("ZMSCORE"), bulk("myzset"), bulk("a"), bulk("b"),])
3113        );
3114    }
3115
3116    #[test]
3117    fn zmscore_parse_mixed() {
3118        let cmd = ZMScore::members("myzset", vec!["a", "b"]);
3119        let frame = array(vec![
3120            Frame::BulkString(Some(Bytes::from("1.5"))),
3121            Frame::Null,
3122        ]);
3123        let result = cmd.parse_response(frame).unwrap();
3124        assert!((result[0].unwrap() - 1.5).abs() < f64::EPSILON);
3125        assert_eq!(result[1], None);
3126    }
3127
3128    // -- ZRangeByScore --
3129
3130    #[test]
3131    fn zrangebyscore_to_frame() {
3132        let cmd = ZRangeByScore::new("myzset", "-inf", "+inf");
3133        assert_eq!(
3134            cmd.to_frame(),
3135            array(vec![
3136                bulk("ZRANGEBYSCORE"),
3137                bulk("myzset"),
3138                bulk("-inf"),
3139                bulk("+inf"),
3140            ])
3141        );
3142    }
3143
3144    // -- ZAdd options --
3145
3146    #[test]
3147    fn zadd_with_options_to_frame() {
3148        let cmd = ZAdd::new("myzset").nx().ch().member(1.0, "a");
3149        assert_eq!(
3150            cmd.to_frame(),
3151            array(vec![
3152                bulk("ZADD"),
3153                bulk("myzset"),
3154                bulk("NX"),
3155                bulk("CH"),
3156                bulk("1"),
3157                bulk("a"),
3158            ])
3159        );
3160    }
3161
3162    #[test]
3163    fn zadd_gt_lt_to_frame() {
3164        let cmd = ZAdd::new("myzset").gt().lt().member(2.0, "b");
3165        match cmd.to_frame() {
3166            Frame::Array(Some(args)) => {
3167                assert!(args.contains(&bulk("GT")));
3168                assert!(args.contains(&bulk("LT")));
3169                assert!(!args.contains(&bulk("XX")));
3170            }
3171            _ => panic!("expected array"),
3172        }
3173    }
3174
3175    // -- ZAddIncr --
3176
3177    #[test]
3178    fn zadd_incr_to_frame() {
3179        let cmd = ZAddIncr::new("myzset", 5.0, "member");
3180        assert_eq!(
3181            cmd.to_frame(),
3182            array(vec![
3183                bulk("ZADD"),
3184                bulk("myzset"),
3185                bulk("INCR"),
3186                bulk("5"),
3187                bulk("member"),
3188            ])
3189        );
3190    }
3191
3192    #[test]
3193    fn zadd_incr_parse_score() {
3194        let cmd = ZAddIncr::new("myzset", 5.0, "m");
3195        let frame = Frame::BulkString(Some(Bytes::from("7.5")));
3196        let result = cmd.parse_response(frame).unwrap().unwrap();
3197        assert!((result - 7.5).abs() < f64::EPSILON);
3198    }
3199
3200    #[test]
3201    fn zadd_incr_parse_null() {
3202        let cmd = ZAddIncr::new("myzset", 5.0, "m");
3203        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
3204    }
3205
3206    // -- ZDiff --
3207
3208    #[test]
3209    fn zdiff_to_frame() {
3210        let cmd = ZDiff::new(vec!["s1", "s2"]);
3211        assert_eq!(
3212            cmd.to_frame(),
3213            array(vec![bulk("ZDIFF"), bulk("2"), bulk("s1"), bulk("s2")])
3214        );
3215    }
3216
3217    #[test]
3218    fn zdiff_parse_members() {
3219        let cmd = ZDiff::new(vec!["s1"]);
3220        let frame = array(vec![
3221            Frame::BulkString(Some(Bytes::from("a"))),
3222            Frame::BulkString(Some(Bytes::from("b"))),
3223        ]);
3224        let result = cmd.parse_response(frame).unwrap();
3225        assert_eq!(result, vec![Bytes::from("a"), Bytes::from("b")]);
3226    }
3227
3228    #[test]
3229    fn zdiff_with_scores_to_frame() {
3230        let cmd = ZDiffWithScores::new(vec!["s1", "s2"]);
3231        assert_eq!(
3232            cmd.to_frame(),
3233            array(vec![
3234                bulk("ZDIFF"),
3235                bulk("2"),
3236                bulk("s1"),
3237                bulk("s2"),
3238                bulk("WITHSCORES"),
3239            ])
3240        );
3241    }
3242
3243    #[test]
3244    fn zdiff_with_scores_parse_flat() {
3245        let cmd = ZDiffWithScores::new(vec!["s1"]);
3246        let frame = array(vec![
3247            Frame::BulkString(Some(Bytes::from("a"))),
3248            Frame::BulkString(Some(Bytes::from("1.5"))),
3249        ]);
3250        let result = cmd.parse_response(frame).unwrap();
3251        assert_eq!(result.len(), 1);
3252        assert_eq!(result[0].0, Bytes::from("a"));
3253        assert!((result[0].1 - 1.5).abs() < f64::EPSILON);
3254    }
3255
3256    // -- ZUnion / ZInter --
3257
3258    #[test]
3259    fn zunion_to_frame() {
3260        let cmd = ZUnion::new(vec!["s1", "s2"]).aggregate(Aggregate::Max);
3261        match cmd.to_frame() {
3262            Frame::Array(Some(args)) => {
3263                assert_eq!(args[0], bulk("ZUNION"));
3264                assert_eq!(args[1], bulk("2"));
3265                assert!(args.contains(&bulk("AGGREGATE")));
3266                assert!(args.contains(&bulk("MAX")));
3267                assert!(!args.contains(&bulk("WITHSCORES")));
3268            }
3269            _ => panic!("expected array"),
3270        }
3271    }
3272
3273    #[test]
3274    fn zunion_with_scores_to_frame() {
3275        let cmd = ZUnionWithScores::new(vec!["s1"]).weights(vec![2.0]);
3276        match cmd.to_frame() {
3277            Frame::Array(Some(args)) => {
3278                assert_eq!(args[0], bulk("ZUNION"));
3279                assert!(args.contains(&bulk("WEIGHTS")));
3280                assert!(args.contains(&bulk("WITHSCORES")));
3281            }
3282            _ => panic!("expected array"),
3283        }
3284    }
3285
3286    #[test]
3287    fn zinter_to_frame() {
3288        let cmd = ZInter::new(vec!["s1", "s2"]);
3289        assert_eq!(
3290            cmd.to_frame(),
3291            array(vec![bulk("ZINTER"), bulk("2"), bulk("s1"), bulk("s2")])
3292        );
3293    }
3294
3295    #[test]
3296    fn zinter_with_scores_parse_pairs_resp3() {
3297        let cmd = ZInterWithScores::new(vec!["s1"]);
3298        let frame = array(vec![array(vec![
3299            Frame::BulkString(Some(Bytes::from("a"))),
3300            Frame::Double(3.0),
3301        ])]);
3302        let result = cmd.parse_response(frame).unwrap();
3303        assert_eq!(result.len(), 1);
3304        assert_eq!(result[0].0, Bytes::from("a"));
3305        assert!((result[0].1 - 3.0).abs() < f64::EPSILON);
3306    }
3307
3308    // -- BZMPop --
3309
3310    #[test]
3311    fn bzmpop_to_frame() {
3312        let cmd = BZMPop::new(1.5, vec!["k1", "k2"], ZMPopDirection::Min).count(2);
3313        assert_eq!(
3314            cmd.to_frame(),
3315            array(vec![
3316                bulk("BZMPOP"),
3317                bulk("1.5"),
3318                bulk("2"),
3319                bulk("k1"),
3320                bulk("k2"),
3321                bulk("MIN"),
3322                bulk("COUNT"),
3323                bulk("2"),
3324            ])
3325        );
3326    }
3327
3328    #[test]
3329    fn bzmpop_parse_null() {
3330        let cmd = BZMPop::new(1.0, vec!["k1"], ZMPopDirection::Max);
3331        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
3332    }
3333
3334    #[test]
3335    fn bzmpop_parse_result() {
3336        let cmd = BZMPop::new(1.0, vec!["k1"], ZMPopDirection::Min);
3337        let frame = array(vec![
3338            Frame::BulkString(Some(Bytes::from("k1"))),
3339            array(vec![array(vec![
3340                Frame::BulkString(Some(Bytes::from("a"))),
3341                Frame::BulkString(Some(Bytes::from("1.0"))),
3342            ])]),
3343        ]);
3344        let result = cmd.parse_response(frame).unwrap().unwrap();
3345        assert_eq!(result.0, Bytes::from("k1"));
3346        assert_eq!(result.1[0].0, Bytes::from("a"));
3347        assert!((result.1[0].1 - 1.0).abs() < f64::EPSILON);
3348    }
3349
3350    // -- ZRevRange --
3351
3352    #[test]
3353    fn zrevrange_to_frame() {
3354        let cmd = ZRevRange::new("myzset", 0, -1);
3355        assert_eq!(
3356            cmd.to_frame(),
3357            array(vec![
3358                bulk("ZREVRANGE"),
3359                bulk("myzset"),
3360                bulk("0"),
3361                bulk("-1"),
3362            ])
3363        );
3364    }
3365
3366    #[test]
3367    fn zrevrange_parse_members() {
3368        let cmd = ZRevRange::new("myzset", 0, -1);
3369        let frame = array(vec![
3370            Frame::BulkString(Some(Bytes::from("b"))),
3371            Frame::BulkString(Some(Bytes::from("a"))),
3372        ]);
3373        let result = cmd.parse_response(frame).unwrap();
3374        assert_eq!(result, vec![Bytes::from("b"), Bytes::from("a")]);
3375    }
3376
3377    #[test]
3378    fn zrevrange_parse_error_on_integer() {
3379        let cmd = ZRevRange::new("myzset", 0, -1);
3380        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
3381    }
3382
3383    #[test]
3384    fn zrevrange_with_scores_to_frame() {
3385        let cmd = ZRevRangeWithScores::new("myzset", 0, -1);
3386        assert_eq!(
3387            cmd.to_frame(),
3388            array(vec![
3389                bulk("ZREVRANGE"),
3390                bulk("myzset"),
3391                bulk("0"),
3392                bulk("-1"),
3393                bulk("WITHSCORES"),
3394            ])
3395        );
3396    }
3397
3398    #[test]
3399    fn zrevrange_with_scores_parse_flat() {
3400        let cmd = ZRevRangeWithScores::new("myzset", 0, -1);
3401        let frame = array(vec![
3402            Frame::BulkString(Some(Bytes::from("b"))),
3403            Frame::BulkString(Some(Bytes::from("2.0"))),
3404            Frame::BulkString(Some(Bytes::from("a"))),
3405            Frame::BulkString(Some(Bytes::from("1.0"))),
3406        ]);
3407        let result = cmd.parse_response(frame).unwrap();
3408        assert_eq!(result.len(), 2);
3409        assert_eq!(result[0].0, Bytes::from("b"));
3410        assert!((result[0].1 - 2.0).abs() < f64::EPSILON);
3411        assert_eq!(result[1].0, Bytes::from("a"));
3412    }
3413
3414    // -- ZRangeByLex --
3415
3416    #[test]
3417    fn zrangebylex_to_frame() {
3418        let cmd = ZRangeByLex::new("myzset", "-", "+");
3419        assert_eq!(
3420            cmd.to_frame(),
3421            array(vec![
3422                bulk("ZRANGEBYLEX"),
3423                bulk("myzset"),
3424                bulk("-"),
3425                bulk("+"),
3426            ])
3427        );
3428    }
3429
3430    #[test]
3431    fn zrangebylex_with_limit_to_frame() {
3432        let cmd = ZRangeByLex::new("myzset", "[a", "(c").limit(0, 10);
3433        assert_eq!(
3434            cmd.to_frame(),
3435            array(vec![
3436                bulk("ZRANGEBYLEX"),
3437                bulk("myzset"),
3438                bulk("[a"),
3439                bulk("(c"),
3440                bulk("LIMIT"),
3441                bulk("0"),
3442                bulk("10"),
3443            ])
3444        );
3445    }
3446
3447    #[test]
3448    fn zrangebylex_parse_members() {
3449        let cmd = ZRangeByLex::new("myzset", "-", "+");
3450        let frame = array(vec![
3451            Frame::BulkString(Some(Bytes::from("a"))),
3452            Frame::BulkString(Some(Bytes::from("b"))),
3453        ]);
3454        let result = cmd.parse_response(frame).unwrap();
3455        assert_eq!(result, vec![Bytes::from("a"), Bytes::from("b")]);
3456    }
3457
3458    // -- ZRevRangeByLex --
3459
3460    #[test]
3461    fn zrevrangebylex_to_frame() {
3462        let cmd = ZRevRangeByLex::new("myzset", "+", "-");
3463        assert_eq!(
3464            cmd.to_frame(),
3465            array(vec![
3466                bulk("ZREVRANGEBYLEX"),
3467                bulk("myzset"),
3468                bulk("+"),
3469                bulk("-"),
3470            ])
3471        );
3472    }
3473
3474    #[test]
3475    fn zrevrangebylex_with_limit_to_frame() {
3476        let cmd = ZRevRangeByLex::new("myzset", "(c", "[a").limit(1, 5);
3477        assert_eq!(
3478            cmd.to_frame(),
3479            array(vec![
3480                bulk("ZREVRANGEBYLEX"),
3481                bulk("myzset"),
3482                bulk("(c"),
3483                bulk("[a"),
3484                bulk("LIMIT"),
3485                bulk("1"),
3486                bulk("5"),
3487            ])
3488        );
3489    }
3490
3491    // -- ZRevRangeByScore --
3492
3493    #[test]
3494    fn zrevrangebyscore_to_frame() {
3495        let cmd = ZRevRangeByScore::new("myzset", "+inf", "-inf");
3496        assert_eq!(
3497            cmd.to_frame(),
3498            array(vec![
3499                bulk("ZREVRANGEBYSCORE"),
3500                bulk("myzset"),
3501                bulk("+inf"),
3502                bulk("-inf"),
3503            ])
3504        );
3505    }
3506
3507    #[test]
3508    fn zrevrangebyscore_with_limit_to_frame() {
3509        let cmd = ZRevRangeByScore::new("myzset", "10", "0").limit(2, 3);
3510        assert_eq!(
3511            cmd.to_frame(),
3512            array(vec![
3513                bulk("ZREVRANGEBYSCORE"),
3514                bulk("myzset"),
3515                bulk("10"),
3516                bulk("0"),
3517                bulk("LIMIT"),
3518                bulk("2"),
3519                bulk("3"),
3520            ])
3521        );
3522    }
3523
3524    #[test]
3525    fn zrevrangebyscore_parse_members() {
3526        let cmd = ZRevRangeByScore::new("myzset", "+inf", "-inf");
3527        let frame = array(vec![
3528            Frame::BulkString(Some(Bytes::from("b"))),
3529            Frame::BulkString(Some(Bytes::from("a"))),
3530        ]);
3531        let result = cmd.parse_response(frame).unwrap();
3532        assert_eq!(result, vec![Bytes::from("b"), Bytes::from("a")]);
3533    }
3534
3535    #[test]
3536    fn zrevrangebyscore_with_scores_to_frame() {
3537        let cmd = ZRevRangeByScoreWithScores::new("myzset", "+inf", "-inf").limit(0, 2);
3538        assert_eq!(
3539            cmd.to_frame(),
3540            array(vec![
3541                bulk("ZREVRANGEBYSCORE"),
3542                bulk("myzset"),
3543                bulk("+inf"),
3544                bulk("-inf"),
3545                bulk("WITHSCORES"),
3546                bulk("LIMIT"),
3547                bulk("0"),
3548                bulk("2"),
3549            ])
3550        );
3551    }
3552
3553    #[test]
3554    fn zrevrangebyscore_with_scores_parse_pairs_resp3() {
3555        let cmd = ZRevRangeByScoreWithScores::new("myzset", "+inf", "-inf");
3556        let frame = array(vec![array(vec![
3557            Frame::BulkString(Some(Bytes::from("b"))),
3558            Frame::Double(2.0),
3559        ])]);
3560        let result = cmd.parse_response(frame).unwrap();
3561        assert_eq!(result.len(), 1);
3562        assert_eq!(result[0].0, Bytes::from("b"));
3563        assert!((result[0].1 - 2.0).abs() < f64::EPSILON);
3564    }
3565}