Skip to main content

redis_tower_commands/
strings.rs

1//! String values, counters, conditional writes, and multi-key string commands.
2//!
3//! [`Get`] returns `Option<Bytes>` so a missing key remains distinct from an
4//! empty value; counters return integers or floats. [`Set`] keeps its original
5//! `Option<Bytes>` response for compatibility. Finish a builder with
6//! [`Set::with_outcome`] when conditional code needs an unambiguous
7//! [`SetOutcome`] containing both the write status and any requested previous
8//! value.
9//!
10//! ```
11//! use redis_tower_commands::{Get, Set};
12//! use redis_tower_core::Command;
13//!
14//! let set = Set::new("session", "ready").ex(60).nx().with_outcome();
15//! let get = Get::new("session");
16//! assert_eq!((set.name(), get.name()), ("SET", "GET"));
17//! ```
18//!
19//! See the [command cookbook] for nil, numeric, option-dependent, and binary
20//! responses.
21//!
22//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#typed-commands-and-response-shapes
23
24use bytes::Bytes;
25use redis_tower_core::{Command, Frame, RedisError};
26use redis_tower_protocol::helpers::{array, bulk};
27
28use crate::CommandArg;
29
30/// GET key
31///
32/// Returns the value of `key`, or `None` if the key does not exist.
33#[derive(Clone)]
34pub struct Get {
35    key: CommandArg,
36}
37
38impl Get {
39    /// Create a new [`Get`] command.
40    pub fn new(key: impl Into<CommandArg>) -> Self {
41        Self { key: key.into() }
42    }
43}
44
45impl Command for Get {
46    type Response = Option<Bytes>;
47
48    fn to_frame(&self) -> Frame {
49        array(vec![bulk("GET"), bulk(self.key.as_bytes())])
50    }
51
52    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
53        match frame {
54            Frame::BulkString(data) => Ok(data),
55            Frame::Null => Ok(None),
56            other => Err(RedisError::UnexpectedResponse {
57                expected: "bulk string or null",
58                actual: format!("{other:?}"),
59            }),
60        }
61    }
62
63    fn name(&self) -> &str {
64        "GET"
65    }
66
67    fn idempotent(&self) -> bool {
68        true
69    }
70}
71
72/// SET key value \[EX seconds\] \[PX milliseconds\] \[NX|XX\] \[GET\]
73///
74/// Sets `key` to hold `value`.
75///
76/// The compatibility response is `Option<Bytes>`: `GET` returns the previous
77/// value, while both `OK` and a null conditional reply become `None`. Code that
78/// must distinguish an applied write from an unmet `NX` or `XX` condition
79/// should finish the builder with [`Set::with_outcome`].
80#[derive(Clone)]
81pub struct Set {
82    key: CommandArg,
83    value: CommandArg,
84    ex: Option<u64>,
85    px: Option<u64>,
86    condition: Option<SetCondition>,
87    get: bool,
88}
89
90/// Condition for SET (NX or XX).
91#[derive(Clone)]
92pub enum SetCondition {
93    /// Only set if the key does not exist.
94    Nx,
95    /// Only set if the key already exists.
96    Xx,
97}
98
99/// Whether Redis applied a [`Set`] operation.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum SetStatus {
102    /// Redis stored the requested value.
103    Applied,
104    /// Redis left the key unchanged because an `NX` or `XX` condition failed.
105    NotApplied,
106}
107
108/// Previous-value information returned by [`Set::with_outcome`].
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum SetPreviousValue {
111    /// `GET` was not requested, so Redis did not report the previous value.
112    NotRequested,
113    /// `GET` was requested and the key had no previous value.
114    Missing,
115    /// `GET` was requested and Redis returned the previous binary value.
116    Value(Bytes),
117}
118
119/// Unambiguous response from [`Set::with_outcome`].
120///
121/// `status` and `previous` are independent: a conditional write can be applied
122/// or rejected, while the previous value can be unrequested, missing, empty,
123/// or arbitrary binary data.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct SetOutcome {
126    /// Whether Redis applied the write.
127    pub status: SetStatus,
128    /// Previous-value information, including whether `GET` was requested.
129    pub previous: SetPreviousValue,
130}
131
132impl SetOutcome {
133    /// Return `true` when Redis applied the write.
134    pub fn is_applied(&self) -> bool {
135        self.status == SetStatus::Applied
136    }
137}
138
139/// A [`Set`] command whose response is an unambiguous [`SetOutcome`].
140///
141/// Create this command by calling [`Set::with_outcome`] after configuring all
142/// desired `SET` options.
143#[derive(Clone)]
144pub struct SetWithOutcome {
145    command: Set,
146}
147
148impl Set {
149    /// Create a new [`Set`] command.
150    pub fn new(key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
151        Self {
152            key: key.into(),
153            value: value.into(),
154            ex: None,
155            px: None,
156            condition: None,
157            get: false,
158        }
159    }
160
161    /// Set expiration in seconds.
162    pub fn ex(mut self, seconds: u64) -> Self {
163        self.ex = Some(seconds);
164        self.px = None;
165        self
166    }
167
168    /// Set expiration in milliseconds.
169    pub fn px(mut self, milliseconds: u64) -> Self {
170        self.px = Some(milliseconds);
171        self.ex = None;
172        self
173    }
174
175    /// Only set if the key does not exist.
176    pub fn nx(mut self) -> Self {
177        self.condition = Some(SetCondition::Nx);
178        self
179    }
180
181    /// Only set if the key already exists.
182    pub fn xx(mut self) -> Self {
183        self.condition = Some(SetCondition::Xx);
184        self
185    }
186
187    /// Return the old value stored at `key`.
188    pub fn get(mut self) -> Self {
189        self.get = true;
190        self
191    }
192
193    /// Return an unambiguous write status and previous-value result.
194    ///
195    /// This additive response mode leaves [`Set`]'s original `Option<Bytes>`
196    /// response intact for compatibility. Call it after configuring the
197    /// command:
198    ///
199    /// ```
200    /// use redis_tower_commands::{Set, SetPreviousValue, SetStatus};
201    /// use redis_tower_core::Command;
202    ///
203    /// let command = Set::new("lease", "owner").nx().get().with_outcome();
204    /// assert_eq!(command.name(), "SET");
205    /// let _ = (SetStatus::Applied, SetPreviousValue::Missing);
206    /// ```
207    pub fn with_outcome(self) -> SetWithOutcome {
208        SetWithOutcome { command: self }
209    }
210
211    fn parse_outcome(&self, frame: Frame) -> Result<SetOutcome, RedisError> {
212        if !self.get {
213            return match frame {
214                Frame::SimpleString(value) if &value[..] == b"OK" => Ok(SetOutcome {
215                    status: SetStatus::Applied,
216                    previous: SetPreviousValue::NotRequested,
217                }),
218                Frame::Null | Frame::BulkString(None) if self.condition.is_some() => {
219                    Ok(SetOutcome {
220                        status: SetStatus::NotApplied,
221                        previous: SetPreviousValue::NotRequested,
222                    })
223                }
224                other => Err(RedisError::UnexpectedResponse {
225                    expected: "OK, or null for a conditional SET",
226                    actual: format!("{other:?}"),
227                }),
228            };
229        }
230
231        let previous = match frame {
232            Frame::BulkString(Some(value)) => SetPreviousValue::Value(value),
233            Frame::BulkString(None) | Frame::Null => SetPreviousValue::Missing,
234            other => {
235                return Err(RedisError::UnexpectedResponse {
236                    expected: "bulk string or null for SET GET",
237                    actual: format!("{other:?}"),
238                });
239            }
240        };
241
242        let status = match (&self.condition, &previous) {
243            (None, _) => SetStatus::Applied,
244            (Some(SetCondition::Nx), SetPreviousValue::Missing) => SetStatus::Applied,
245            (Some(SetCondition::Nx), SetPreviousValue::Value(_)) => SetStatus::NotApplied,
246            (Some(SetCondition::Xx), SetPreviousValue::Missing) => SetStatus::NotApplied,
247            (Some(SetCondition::Xx), SetPreviousValue::Value(_)) => SetStatus::Applied,
248            (_, SetPreviousValue::NotRequested) => unreachable!("SET GET always reports a value"),
249        };
250
251        Ok(SetOutcome { status, previous })
252    }
253}
254
255impl Command for Set {
256    type Response = Option<Bytes>;
257
258    fn to_frame(&self) -> Frame {
259        let mut args = vec![
260            bulk("SET"),
261            bulk(self.key.as_bytes()),
262            bulk(self.value.as_bytes()),
263        ];
264
265        if let Some(ex) = self.ex {
266            args.push(bulk("EX"));
267            args.push(bulk(ex.to_string()));
268        }
269        if let Some(px) = self.px {
270            args.push(bulk("PX"));
271            args.push(bulk(px.to_string()));
272        }
273        match &self.condition {
274            Some(SetCondition::Nx) => args.push(bulk("NX")),
275            Some(SetCondition::Xx) => args.push(bulk("XX")),
276            None => {}
277        }
278        if self.get {
279            args.push(bulk("GET"));
280        }
281
282        array(args)
283    }
284
285    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
286        match frame {
287            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(None),
288            Frame::BulkString(data) => Ok(data),
289            Frame::Null => Ok(None),
290            other => Err(RedisError::UnexpectedResponse {
291                expected: "OK, bulk string, or null",
292                actual: format!("{other:?}"),
293            }),
294        }
295    }
296
297    fn name(&self) -> &str {
298        "SET"
299    }
300}
301
302impl Command for SetWithOutcome {
303    type Response = SetOutcome;
304
305    fn to_frame(&self) -> Frame {
306        self.command.to_frame()
307    }
308
309    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
310        self.command.parse_outcome(frame)
311    }
312
313    fn name(&self) -> &str {
314        "SET"
315    }
316}
317
318/// INCR key
319///
320/// Increments the integer value of `key` by one.
321#[derive(Clone)]
322pub struct Incr {
323    key: CommandArg,
324}
325
326impl Incr {
327    /// Create a new [`Incr`] command.
328    pub fn new(key: impl Into<CommandArg>) -> Self {
329        Self { key: key.into() }
330    }
331}
332
333impl Command for Incr {
334    type Response = i64;
335
336    fn to_frame(&self) -> Frame {
337        array(vec![bulk("INCR"), bulk(self.key.as_bytes())])
338    }
339
340    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
341        match frame {
342            Frame::Integer(n) => Ok(n),
343            other => Err(RedisError::UnexpectedResponse {
344                expected: "integer",
345                actual: format!("{other:?}"),
346            }),
347        }
348    }
349
350    fn name(&self) -> &str {
351        "INCR"
352    }
353}
354
355/// A numeric bound for [`IncrEx`].
356///
357/// The bound type must match the command's increment mode: use an integer
358/// bound with the default or `BYINT` mode, and a floating-point bound with
359/// `BYFLOAT`.
360#[derive(Debug, Clone, Copy, PartialEq)]
361pub enum IncrExBound {
362    /// A signed 64-bit integer bound.
363    Integer(i64),
364    /// A floating-point bound.
365    Float(f64),
366}
367
368impl From<i32> for IncrExBound {
369    fn from(value: i32) -> Self {
370        Self::Integer(i64::from(value))
371    }
372}
373
374impl From<i64> for IncrExBound {
375    fn from(value: i64) -> Self {
376        Self::Integer(value)
377    }
378}
379
380impl From<f32> for IncrExBound {
381    fn from(value: f32) -> Self {
382        Self::Float(f64::from(value))
383    }
384}
385
386impl From<f64> for IncrExBound {
387    fn from(value: f64) -> Self {
388        Self::Float(value)
389    }
390}
391
392impl IncrExBound {
393    fn as_string(self) -> String {
394        match self {
395            Self::Integer(value) => value.to_string(),
396            Self::Float(value) => value.to_string(),
397        }
398    }
399}
400
401/// The result of an [`IncrEx`] operation.
402///
403/// Redis returns integer elements for the default and `BYINT` modes. In
404/// `BYFLOAT` mode, RESP2 returns bulk strings and RESP3 returns doubles; both
405/// protocol forms are normalized into [`Self::Float`].
406#[derive(Debug, Clone, Copy, PartialEq)]
407pub enum IncrExResult {
408    /// Result from the default or `BYINT` mode.
409    Integer {
410        /// The value stored at the key after the operation.
411        value: i64,
412        /// The increment that Redis actually applied.
413        actual_increment: i64,
414    },
415    /// Result from `BYFLOAT` mode.
416    Float {
417        /// The value stored at the key after the operation.
418        value: f64,
419        /// The increment that Redis actually applied.
420        actual_increment: f64,
421    },
422}
423
424#[derive(Clone, Copy)]
425enum IncrExIncrement {
426    Default,
427    Integer(i64),
428    Float(f64),
429}
430
431/// INCREX key \[BYFLOAT increment | BYINT increment\]
432/// \[LBOUND lowerbound\] \[UBOUND upperbound\] \[SATURATE\]
433/// \[EX seconds | PX milliseconds | EXAT timestamp | PXAT timestamp | PERSIST\]
434/// \[ENX\]
435///
436/// Atomically increments the numeric value stored at `key`, optionally
437/// constraining the result and changing its expiration (Redis 8.8+). The
438/// response contains both the resulting value and the increment Redis actually
439/// applied. If a bound would be exceeded without `SATURATE`, Redis leaves the
440/// value unchanged and reports an actual increment of zero.
441///
442/// If no increment is configured, Redis uses integer mode with an increment of
443/// one. `ENX` requires `EX`, `PX`, `EXAT`, or `PXAT`; Redis rejects it without
444/// one of those expiration options.
445#[derive(Clone)]
446pub struct IncrEx {
447    key: CommandArg,
448    increment: IncrExIncrement,
449    lower_bound: Option<IncrExBound>,
450    upper_bound: Option<IncrExBound>,
451    saturate: bool,
452    ex: Option<u64>,
453    px: Option<u64>,
454    exat: Option<u64>,
455    pxat: Option<u64>,
456    persist: bool,
457    enx: bool,
458}
459
460impl IncrEx {
461    /// Create an `INCREX` command in the default integer-by-one mode.
462    pub fn new(key: impl Into<CommandArg>) -> Self {
463        Self {
464            key: key.into(),
465            increment: IncrExIncrement::Default,
466            lower_bound: None,
467            upper_bound: None,
468            saturate: false,
469            ex: None,
470            px: None,
471            exat: None,
472            pxat: None,
473            persist: false,
474            enx: false,
475        }
476    }
477
478    /// Increment by a signed 64-bit integer.
479    pub fn by_int(mut self, increment: i64) -> Self {
480        self.increment = IncrExIncrement::Integer(increment);
481        self
482    }
483
484    /// Increment by a floating-point value.
485    pub fn by_float(mut self, increment: f64) -> Self {
486        self.increment = IncrExIncrement::Float(increment);
487        self
488    }
489
490    /// Set the inclusive lower bound.
491    ///
492    /// The bound's numeric type must match the selected increment mode.
493    pub fn lower_bound(mut self, bound: impl Into<IncrExBound>) -> Self {
494        self.lower_bound = Some(bound.into());
495        self
496    }
497
498    /// Set the inclusive upper bound.
499    ///
500    /// The bound's numeric type must match the selected increment mode.
501    pub fn upper_bound(mut self, bound: impl Into<IncrExBound>) -> Self {
502        self.upper_bound = Some(bound.into());
503        self
504    }
505
506    /// Cap or floor an out-of-bounds result instead of skipping the operation.
507    pub fn saturate(mut self) -> Self {
508        self.saturate = true;
509        self
510    }
511
512    /// Set expiration in seconds.
513    pub fn ex(mut self, seconds: u64) -> Self {
514        self.ex = Some(seconds);
515        self.px = None;
516        self.exat = None;
517        self.pxat = None;
518        self.persist = false;
519        self
520    }
521
522    /// Set expiration in milliseconds.
523    pub fn px(mut self, milliseconds: u64) -> Self {
524        self.px = Some(milliseconds);
525        self.ex = None;
526        self.exat = None;
527        self.pxat = None;
528        self.persist = false;
529        self
530    }
531
532    /// Set expiration as a Unix timestamp in seconds.
533    pub fn exat(mut self, timestamp: u64) -> Self {
534        self.exat = Some(timestamp);
535        self.ex = None;
536        self.px = None;
537        self.pxat = None;
538        self.persist = false;
539        self
540    }
541
542    /// Set expiration as a Unix timestamp in milliseconds.
543    pub fn pxat(mut self, timestamp: u64) -> Self {
544        self.pxat = Some(timestamp);
545        self.ex = None;
546        self.px = None;
547        self.exat = None;
548        self.persist = false;
549        self
550    }
551
552    /// Remove the key's existing expiration.
553    ///
554    /// `PERSIST` is incompatible with `ENX`, so this also clears an `ENX`
555    /// option configured earlier in the builder chain.
556    pub fn persist(mut self) -> Self {
557        self.persist = true;
558        self.ex = None;
559        self.px = None;
560        self.exat = None;
561        self.pxat = None;
562        self.enx = false;
563        self
564    }
565
566    /// Only set the configured expiration when the key has no existing TTL.
567    ///
568    /// This must be combined with `EX`, `PX`, `EXAT`, or `PXAT`.
569    pub fn enx(mut self) -> Self {
570        self.enx = true;
571        self
572    }
573}
574
575impl Command for IncrEx {
576    type Response = IncrExResult;
577
578    fn to_frame(&self) -> Frame {
579        let mut args = vec![bulk("INCREX"), bulk(self.key.as_bytes())];
580
581        match self.increment {
582            IncrExIncrement::Default => {}
583            IncrExIncrement::Integer(increment) => {
584                args.push(bulk("BYINT"));
585                args.push(bulk(increment.to_string()));
586            }
587            IncrExIncrement::Float(increment) => {
588                args.push(bulk("BYFLOAT"));
589                args.push(bulk(increment.to_string()));
590            }
591        }
592        if let Some(bound) = self.lower_bound {
593            args.push(bulk("LBOUND"));
594            args.push(bulk(bound.as_string()));
595        }
596        if let Some(bound) = self.upper_bound {
597            args.push(bulk("UBOUND"));
598            args.push(bulk(bound.as_string()));
599        }
600        if self.saturate {
601            args.push(bulk("SATURATE"));
602        }
603        if let Some(ex) = self.ex {
604            args.push(bulk("EX"));
605            args.push(bulk(ex.to_string()));
606        }
607        if let Some(px) = self.px {
608            args.push(bulk("PX"));
609            args.push(bulk(px.to_string()));
610        }
611        if let Some(exat) = self.exat {
612            args.push(bulk("EXAT"));
613            args.push(bulk(exat.to_string()));
614        }
615        if let Some(pxat) = self.pxat {
616            args.push(bulk("PXAT"));
617            args.push(bulk(pxat.to_string()));
618        }
619        if self.persist {
620            args.push(bulk("PERSIST"));
621        }
622        if self.enx {
623            args.push(bulk("ENX"));
624        }
625
626        array(args)
627    }
628
629    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
630        let frames = match frame {
631            Frame::Array(Some(frames)) if frames.len() == 2 => frames,
632            Frame::Array(Some(frames)) => {
633                return Err(RedisError::UnexpectedResponse {
634                    expected: "two-element array",
635                    actual: format!("array with {} elements", frames.len()),
636                });
637            }
638            other => {
639                return Err(RedisError::UnexpectedResponse {
640                    expected: "two-element array",
641                    actual: format!("{other:?}"),
642                });
643            }
644        };
645
646        match self.increment {
647            IncrExIncrement::Default | IncrExIncrement::Integer(_) => {
648                let mut values = frames.into_iter();
649                let value = parse_increx_integer(values.next().expect("length checked"))?;
650                let actual_increment =
651                    parse_increx_integer(values.next().expect("length checked"))?;
652                Ok(IncrExResult::Integer {
653                    value,
654                    actual_increment,
655                })
656            }
657            IncrExIncrement::Float(_) => {
658                let mut values = frames.into_iter();
659                let value = parse_increx_float(values.next().expect("length checked"))?;
660                let actual_increment = parse_increx_float(values.next().expect("length checked"))?;
661                Ok(IncrExResult::Float {
662                    value,
663                    actual_increment,
664                })
665            }
666        }
667    }
668
669    fn name(&self) -> &str {
670        "INCREX"
671    }
672}
673
674fn parse_increx_integer(frame: Frame) -> Result<i64, RedisError> {
675    match frame {
676        Frame::Integer(value) => Ok(value),
677        other => Err(RedisError::UnexpectedResponse {
678            expected: "integer",
679            actual: format!("{other:?}"),
680        }),
681    }
682}
683
684fn parse_increx_float(frame: Frame) -> Result<f64, RedisError> {
685    match frame {
686        Frame::Double(value) => Ok(value),
687        Frame::BulkString(Some(data)) => {
688            let value = std::str::from_utf8(&data).map_err(|_| RedisError::UnexpectedResponse {
689                expected: "valid UTF-8 float bulk string",
690                actual: format!("{data:?}"),
691            })?;
692            value
693                .parse::<f64>()
694                .map_err(|_| RedisError::UnexpectedResponse {
695                    expected: "float bulk string",
696                    actual: value.to_string(),
697                })
698        }
699        other => Err(RedisError::UnexpectedResponse {
700            expected: "double or float bulk string",
701            actual: format!("{other:?}"),
702        }),
703    }
704}
705
706/// MGET key [key ...]
707///
708/// Returns the values of all specified keys.
709#[derive(Clone)]
710pub struct MGet {
711    keys: Vec<CommandArg>,
712}
713
714impl MGet {
715    /// Create a new [`MGet`] command.
716    pub fn new(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
717        Self {
718            keys: keys.into_iter().map(Into::into).collect(),
719        }
720    }
721}
722
723impl Command for MGet {
724    type Response = Vec<Option<Bytes>>;
725
726    fn to_frame(&self) -> Frame {
727        let mut args = vec![bulk("MGET")];
728        for key in &self.keys {
729            args.push(bulk(key.as_bytes()));
730        }
731        array(args)
732    }
733
734    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
735        match frame {
736            Frame::Array(Some(frames)) => frames
737                .into_iter()
738                .map(|f| match f {
739                    Frame::BulkString(data) => Ok(data),
740                    Frame::Null => Ok(None),
741                    other => Err(RedisError::UnexpectedResponse {
742                        expected: "bulk string or null",
743                        actual: format!("{other:?}"),
744                    }),
745                })
746                .collect(),
747            other => Err(RedisError::UnexpectedResponse {
748                expected: "array",
749                actual: format!("{other:?}"),
750            }),
751        }
752    }
753
754    fn name(&self) -> &str {
755        "MGET"
756    }
757
758    fn idempotent(&self) -> bool {
759        true
760    }
761}
762
763/// APPEND key value
764///
765/// Appends `value` to the end of the string at `key`. Returns the length
766/// of the string after the append.
767#[derive(Clone)]
768pub struct Append {
769    key: CommandArg,
770    value: CommandArg,
771}
772
773impl Append {
774    /// Create a new [`Append`] command.
775    pub fn new(key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
776        Self {
777            key: key.into(),
778            value: value.into(),
779        }
780    }
781}
782
783impl Command for Append {
784    type Response = i64;
785
786    fn to_frame(&self) -> Frame {
787        array(vec![
788            bulk("APPEND"),
789            bulk(self.key.as_bytes()),
790            bulk(self.value.as_bytes()),
791        ])
792    }
793
794    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
795        match frame {
796            Frame::Integer(n) => Ok(n),
797            other => Err(RedisError::UnexpectedResponse {
798                expected: "integer",
799                actual: format!("{other:?}"),
800            }),
801        }
802    }
803
804    fn name(&self) -> &str {
805        "APPEND"
806    }
807}
808
809/// MSET key value \[key value ...\]
810///
811/// Sets multiple keys to their respective values atomically.
812#[derive(Clone)]
813pub struct MSet {
814    pairs: Vec<(CommandArg, CommandArg)>,
815}
816
817impl MSet {
818    /// Create a new [`MSet`] command.
819    pub fn new(
820        pairs: impl IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>,
821    ) -> Self {
822        Self {
823            pairs: pairs
824                .into_iter()
825                .map(|(k, v)| (k.into(), v.into()))
826                .collect(),
827        }
828    }
829}
830
831impl Command for MSet {
832    type Response = ();
833
834    fn to_frame(&self) -> Frame {
835        let mut args = vec![bulk("MSET")];
836        for (k, v) in &self.pairs {
837            args.push(bulk(k.as_bytes()));
838            args.push(bulk(v.as_bytes()));
839        }
840        array(args)
841    }
842
843    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
844        match frame {
845            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
846            other => Err(RedisError::UnexpectedResponse {
847                expected: "OK",
848                actual: format!("{other:?}"),
849            }),
850        }
851    }
852
853    fn name(&self) -> &str {
854        "MSET"
855    }
856}
857
858#[derive(Clone, Copy)]
859enum MSetExCondition {
860    Nx,
861    Xx,
862}
863
864/// MSETEX numkeys key value \[key value ...\] \[NX | XX\]
865/// \[EX seconds | PX milliseconds | EXAT timestamp | PXAT timestamp | KEEPTTL\]
866///
867/// Atomically sets multiple string keys with an optional shared expiration
868/// (Redis 8.4+). Returns `true` when all keys were set and `false` when a
869/// configured `NX` or `XX` condition prevented the operation.
870#[derive(Clone)]
871pub struct MSetEx {
872    pairs: Vec<(CommandArg, CommandArg)>,
873    condition: Option<MSetExCondition>,
874    ex: Option<u64>,
875    px: Option<u64>,
876    exat: Option<u64>,
877    pxat: Option<u64>,
878    keep_ttl: bool,
879}
880
881impl MSetEx {
882    /// Create an `MSETEX` command from key/value pairs.
883    pub fn new(
884        pairs: impl IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>,
885    ) -> Self {
886        Self {
887            pairs: pairs
888                .into_iter()
889                .map(|(key, value)| (key.into(), value.into()))
890                .collect(),
891            condition: None,
892            ex: None,
893            px: None,
894            exat: None,
895            pxat: None,
896            keep_ttl: false,
897        }
898    }
899
900    /// Set only if none of the specified keys exist.
901    pub fn nx(mut self) -> Self {
902        self.condition = Some(MSetExCondition::Nx);
903        self
904    }
905
906    /// Set only if all of the specified keys already exist.
907    pub fn xx(mut self) -> Self {
908        self.condition = Some(MSetExCondition::Xx);
909        self
910    }
911
912    /// Set expiration in seconds.
913    pub fn ex(mut self, seconds: u64) -> Self {
914        self.ex = Some(seconds);
915        self.px = None;
916        self.exat = None;
917        self.pxat = None;
918        self.keep_ttl = false;
919        self
920    }
921
922    /// Set expiration in milliseconds.
923    pub fn px(mut self, milliseconds: u64) -> Self {
924        self.px = Some(milliseconds);
925        self.ex = None;
926        self.exat = None;
927        self.pxat = None;
928        self.keep_ttl = false;
929        self
930    }
931
932    /// Set expiration as a Unix timestamp in seconds.
933    pub fn exat(mut self, timestamp: u64) -> Self {
934        self.exat = Some(timestamp);
935        self.ex = None;
936        self.px = None;
937        self.pxat = None;
938        self.keep_ttl = false;
939        self
940    }
941
942    /// Set expiration as a Unix timestamp in milliseconds.
943    pub fn pxat(mut self, timestamp: u64) -> Self {
944        self.pxat = Some(timestamp);
945        self.ex = None;
946        self.px = None;
947        self.exat = None;
948        self.keep_ttl = false;
949        self
950    }
951
952    /// Preserve the existing expiration of each key.
953    pub fn keep_ttl(mut self) -> Self {
954        self.keep_ttl = true;
955        self.ex = None;
956        self.px = None;
957        self.exat = None;
958        self.pxat = None;
959        self
960    }
961}
962
963impl Command for MSetEx {
964    type Response = bool;
965
966    fn to_frame(&self) -> Frame {
967        let mut args = vec![bulk("MSETEX"), bulk(self.pairs.len().to_string())];
968        for (key, value) in &self.pairs {
969            args.push(bulk(key.as_bytes()));
970            args.push(bulk(value.as_bytes()));
971        }
972        match self.condition {
973            Some(MSetExCondition::Nx) => args.push(bulk("NX")),
974            Some(MSetExCondition::Xx) => args.push(bulk("XX")),
975            None => {}
976        }
977        if let Some(ex) = self.ex {
978            args.push(bulk("EX"));
979            args.push(bulk(ex.to_string()));
980        }
981        if let Some(px) = self.px {
982            args.push(bulk("PX"));
983            args.push(bulk(px.to_string()));
984        }
985        if let Some(exat) = self.exat {
986            args.push(bulk("EXAT"));
987            args.push(bulk(exat.to_string()));
988        }
989        if let Some(pxat) = self.pxat {
990            args.push(bulk("PXAT"));
991            args.push(bulk(pxat.to_string()));
992        }
993        if self.keep_ttl {
994            args.push(bulk("KEEPTTL"));
995        }
996        array(args)
997    }
998
999    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1000        parse_zero_or_one(frame)
1001    }
1002
1003    fn name(&self) -> &str {
1004        "MSETEX"
1005    }
1006}
1007
1008/// GETEX key \[EX seconds | PX milliseconds | EXAT timestamp | PXAT timestamp | PERSIST\]
1009///
1010/// Gets the value of `key` and optionally sets its expiration.
1011/// Returns `None` if the key does not exist.
1012#[derive(Clone)]
1013pub struct GetEx {
1014    key: CommandArg,
1015    ex: Option<u64>,
1016    px: Option<u64>,
1017    exat: Option<u64>,
1018    pxat: Option<u64>,
1019    persist: bool,
1020}
1021
1022impl GetEx {
1023    /// Create a new [`GetEx`] command.
1024    pub fn new(key: impl Into<CommandArg>) -> Self {
1025        Self {
1026            key: key.into(),
1027            ex: None,
1028            px: None,
1029            exat: None,
1030            pxat: None,
1031            persist: false,
1032        }
1033    }
1034
1035    /// Set expiration in seconds.
1036    pub fn ex(mut self, seconds: u64) -> Self {
1037        self.ex = Some(seconds);
1038        self.px = None;
1039        self.exat = None;
1040        self.pxat = None;
1041        self.persist = false;
1042        self
1043    }
1044
1045    /// Set expiration in milliseconds.
1046    pub fn px(mut self, milliseconds: u64) -> Self {
1047        self.px = Some(milliseconds);
1048        self.ex = None;
1049        self.exat = None;
1050        self.pxat = None;
1051        self.persist = false;
1052        self
1053    }
1054
1055    /// Set expiration as a Unix timestamp in seconds.
1056    pub fn exat(mut self, timestamp: u64) -> Self {
1057        self.exat = Some(timestamp);
1058        self.ex = None;
1059        self.px = None;
1060        self.pxat = None;
1061        self.persist = false;
1062        self
1063    }
1064
1065    /// Set expiration as a Unix timestamp in milliseconds.
1066    pub fn pxat(mut self, timestamp: u64) -> Self {
1067        self.pxat = Some(timestamp);
1068        self.ex = None;
1069        self.px = None;
1070        self.exat = None;
1071        self.persist = false;
1072        self
1073    }
1074
1075    /// Remove the existing expiration on the key.
1076    pub fn persist(mut self) -> Self {
1077        self.persist = true;
1078        self.ex = None;
1079        self.px = None;
1080        self.exat = None;
1081        self.pxat = None;
1082        self
1083    }
1084}
1085
1086impl Command for GetEx {
1087    type Response = Option<Bytes>;
1088
1089    fn to_frame(&self) -> Frame {
1090        let mut args = vec![bulk("GETEX"), bulk(self.key.as_bytes())];
1091
1092        if let Some(ex) = self.ex {
1093            args.push(bulk("EX"));
1094            args.push(bulk(ex.to_string()));
1095        }
1096        if let Some(px) = self.px {
1097            args.push(bulk("PX"));
1098            args.push(bulk(px.to_string()));
1099        }
1100        if let Some(exat) = self.exat {
1101            args.push(bulk("EXAT"));
1102            args.push(bulk(exat.to_string()));
1103        }
1104        if let Some(pxat) = self.pxat {
1105            args.push(bulk("PXAT"));
1106            args.push(bulk(pxat.to_string()));
1107        }
1108        if self.persist {
1109            args.push(bulk("PERSIST"));
1110        }
1111
1112        array(args)
1113    }
1114
1115    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1116        match frame {
1117            Frame::BulkString(data) => Ok(data),
1118            Frame::Null => Ok(None),
1119            other => Err(RedisError::UnexpectedResponse {
1120                expected: "bulk string or null",
1121                actual: format!("{other:?}"),
1122            }),
1123        }
1124    }
1125
1126    fn name(&self) -> &str {
1127        "GETEX"
1128    }
1129}
1130
1131/// GETDEL key
1132///
1133/// Gets the value of `key` and deletes it. Returns `None` if the key does
1134/// not exist.
1135#[derive(Clone)]
1136pub struct GetDel {
1137    key: CommandArg,
1138}
1139
1140impl GetDel {
1141    /// Create a new [`GetDel`] command.
1142    pub fn new(key: impl Into<CommandArg>) -> Self {
1143        Self { key: key.into() }
1144    }
1145}
1146
1147impl Command for GetDel {
1148    type Response = Option<Bytes>;
1149
1150    fn to_frame(&self) -> Frame {
1151        array(vec![bulk("GETDEL"), bulk(self.key.as_bytes())])
1152    }
1153
1154    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1155        match frame {
1156            Frame::BulkString(data) => Ok(data),
1157            Frame::Null => Ok(None),
1158            other => Err(RedisError::UnexpectedResponse {
1159                expected: "bulk string or null",
1160                actual: format!("{other:?}"),
1161            }),
1162        }
1163    }
1164
1165    fn name(&self) -> &str {
1166        "GETDEL"
1167    }
1168}
1169
1170#[derive(Clone)]
1171enum DelExCondition {
1172    Eq(CommandArg),
1173    Ne(CommandArg),
1174    DigestEq(CommandArg),
1175    DigestNe(CommandArg),
1176}
1177
1178/// DELEX key \[IFEQ value | IFNE value | IFDEQ digest | IFDNE digest\]
1179///
1180/// Conditionally deletes `key` by comparing either its value or its
1181/// hexadecimal [`Digest`] result (Redis 8.4+). With no condition, this deletes
1182/// the key regardless of its type. Returns `true` when the key was deleted.
1183#[derive(Clone)]
1184pub struct DelEx {
1185    key: CommandArg,
1186    condition: Option<DelExCondition>,
1187}
1188
1189impl DelEx {
1190    /// Create an unconditional `DELEX` command.
1191    pub fn new(key: impl Into<CommandArg>) -> Self {
1192        Self {
1193            key: key.into(),
1194            condition: None,
1195        }
1196    }
1197
1198    /// Delete only when the current string value equals `value`.
1199    pub fn if_eq(mut self, value: impl Into<CommandArg>) -> Self {
1200        self.condition = Some(DelExCondition::Eq(value.into()));
1201        self
1202    }
1203
1204    /// Delete only when the current string value does not equal `value`.
1205    pub fn if_ne(mut self, value: impl Into<CommandArg>) -> Self {
1206        self.condition = Some(DelExCondition::Ne(value.into()));
1207        self
1208    }
1209
1210    /// Delete only when the current string digest equals `digest`.
1211    pub fn if_digest_eq(mut self, digest: impl Into<CommandArg>) -> Self {
1212        self.condition = Some(DelExCondition::DigestEq(digest.into()));
1213        self
1214    }
1215
1216    /// Delete only when the current string digest does not equal `digest`.
1217    pub fn if_digest_ne(mut self, digest: impl Into<CommandArg>) -> Self {
1218        self.condition = Some(DelExCondition::DigestNe(digest.into()));
1219        self
1220    }
1221}
1222
1223impl Command for DelEx {
1224    type Response = bool;
1225
1226    fn to_frame(&self) -> Frame {
1227        let mut args = vec![bulk("DELEX"), bulk(self.key.as_bytes())];
1228        match &self.condition {
1229            Some(DelExCondition::Eq(value)) => {
1230                args.push(bulk("IFEQ"));
1231                args.push(bulk(value.as_bytes()));
1232            }
1233            Some(DelExCondition::Ne(value)) => {
1234                args.push(bulk("IFNE"));
1235                args.push(bulk(value.as_bytes()));
1236            }
1237            Some(DelExCondition::DigestEq(digest)) => {
1238                args.push(bulk("IFDEQ"));
1239                args.push(bulk(digest.as_bytes()));
1240            }
1241            Some(DelExCondition::DigestNe(digest)) => {
1242                args.push(bulk("IFDNE"));
1243                args.push(bulk(digest.as_bytes()));
1244            }
1245            None => {}
1246        }
1247        array(args)
1248    }
1249
1250    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1251        parse_zero_or_one(frame)
1252    }
1253
1254    fn name(&self) -> &str {
1255        "DELEX"
1256    }
1257}
1258
1259/// DIGEST key
1260///
1261/// Returns the XXH3 hash digest of a string value as hexadecimal bytes (Redis
1262/// 8.4+), or `None` when `key` does not exist.
1263#[derive(Clone)]
1264pub struct Digest {
1265    key: CommandArg,
1266}
1267
1268impl Digest {
1269    /// Create a `DIGEST` command.
1270    pub fn new(key: impl Into<CommandArg>) -> Self {
1271        Self { key: key.into() }
1272    }
1273}
1274
1275impl Command for Digest {
1276    type Response = Option<Bytes>;
1277
1278    fn to_frame(&self) -> Frame {
1279        array(vec![bulk("DIGEST"), bulk(self.key.as_bytes())])
1280    }
1281
1282    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1283        match frame {
1284            Frame::BulkString(data) => Ok(data),
1285            Frame::Null => Ok(None),
1286            other => Err(RedisError::UnexpectedResponse {
1287                expected: "bulk string or null",
1288                actual: format!("{other:?}"),
1289            }),
1290        }
1291    }
1292
1293    fn name(&self) -> &str {
1294        "DIGEST"
1295    }
1296
1297    fn idempotent(&self) -> bool {
1298        true
1299    }
1300}
1301
1302fn parse_zero_or_one(frame: Frame) -> Result<bool, RedisError> {
1303    match frame {
1304        Frame::Integer(0) => Ok(false),
1305        Frame::Integer(1) => Ok(true),
1306        other => Err(RedisError::UnexpectedResponse {
1307            expected: "integer 0 or 1",
1308            actual: format!("{other:?}"),
1309        }),
1310    }
1311}
1312
1313/// SETEX key seconds value
1314///
1315/// Sets `key` to hold `value` with an expiration of `seconds`.
1316#[derive(Clone)]
1317pub struct SetEx {
1318    key: CommandArg,
1319    seconds: u64,
1320    value: CommandArg,
1321}
1322
1323impl SetEx {
1324    /// Create a new [`SetEx`] command.
1325    pub fn new(key: impl Into<CommandArg>, seconds: u64, value: impl Into<CommandArg>) -> Self {
1326        Self {
1327            key: key.into(),
1328            seconds,
1329            value: value.into(),
1330        }
1331    }
1332}
1333
1334impl Command for SetEx {
1335    type Response = ();
1336
1337    fn to_frame(&self) -> Frame {
1338        array(vec![
1339            bulk("SETEX"),
1340            bulk(self.key.as_bytes()),
1341            bulk(self.seconds.to_string()),
1342            bulk(self.value.as_bytes()),
1343        ])
1344    }
1345
1346    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1347        match frame {
1348            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1349            other => Err(RedisError::UnexpectedResponse {
1350                expected: "OK",
1351                actual: format!("{other:?}"),
1352            }),
1353        }
1354    }
1355
1356    fn name(&self) -> &str {
1357        "SETEX"
1358    }
1359}
1360
1361/// PSETEX key milliseconds value
1362///
1363/// Sets `key` to hold `value` with an expiration of `milliseconds`.
1364#[derive(Clone)]
1365pub struct PSetEx {
1366    key: CommandArg,
1367    milliseconds: u64,
1368    value: CommandArg,
1369}
1370
1371impl PSetEx {
1372    /// Create a new [`PSetEx`] command.
1373    pub fn new(
1374        key: impl Into<CommandArg>,
1375        milliseconds: u64,
1376        value: impl Into<CommandArg>,
1377    ) -> Self {
1378        Self {
1379            key: key.into(),
1380            milliseconds,
1381            value: value.into(),
1382        }
1383    }
1384}
1385
1386impl Command for PSetEx {
1387    type Response = ();
1388
1389    fn to_frame(&self) -> Frame {
1390        array(vec![
1391            bulk("PSETEX"),
1392            bulk(self.key.as_bytes()),
1393            bulk(self.milliseconds.to_string()),
1394            bulk(self.value.as_bytes()),
1395        ])
1396    }
1397
1398    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1399        match frame {
1400            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1401            other => Err(RedisError::UnexpectedResponse {
1402                expected: "OK",
1403                actual: format!("{other:?}"),
1404            }),
1405        }
1406    }
1407
1408    fn name(&self) -> &str {
1409        "PSETEX"
1410    }
1411}
1412
1413/// SETNX key value
1414///
1415/// Sets `key` to hold `value` if `key` does not exist. Returns `true` if
1416/// the key was set, `false` if the key already existed.
1417#[derive(Clone)]
1418pub struct SetNx {
1419    key: CommandArg,
1420    value: CommandArg,
1421}
1422
1423impl SetNx {
1424    /// Create a new [`SetNx`] command.
1425    pub fn new(key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
1426        Self {
1427            key: key.into(),
1428            value: value.into(),
1429        }
1430    }
1431}
1432
1433impl Command for SetNx {
1434    type Response = bool;
1435
1436    fn to_frame(&self) -> Frame {
1437        array(vec![
1438            bulk("SETNX"),
1439            bulk(self.key.as_bytes()),
1440            bulk(self.value.as_bytes()),
1441        ])
1442    }
1443
1444    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1445        match frame {
1446            Frame::Integer(1) => Ok(true),
1447            Frame::Integer(0) => Ok(false),
1448            other => Err(RedisError::UnexpectedResponse {
1449                expected: "integer 0 or 1",
1450                actual: format!("{other:?}"),
1451            }),
1452        }
1453    }
1454
1455    fn name(&self) -> &str {
1456        "SETNX"
1457    }
1458}
1459
1460/// INCRBYFLOAT key increment
1461///
1462/// Increments the floating-point value of `key` by `increment`. Returns the
1463/// new value.
1464#[derive(Clone)]
1465pub struct IncrByFloat {
1466    key: CommandArg,
1467    increment: f64,
1468}
1469
1470impl IncrByFloat {
1471    /// Create a new [`IncrByFloat`] command.
1472    pub fn new(key: impl Into<CommandArg>, increment: f64) -> Self {
1473        Self {
1474            key: key.into(),
1475            increment,
1476        }
1477    }
1478}
1479
1480impl Command for IncrByFloat {
1481    type Response = f64;
1482
1483    fn to_frame(&self) -> Frame {
1484        array(vec![
1485            bulk("INCRBYFLOAT"),
1486            bulk(self.key.as_bytes()),
1487            bulk(self.increment.to_string()),
1488        ])
1489    }
1490
1491    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1492        match frame {
1493            Frame::BulkString(Some(data)) => {
1494                let s = std::str::from_utf8(&data).map_err(|_| RedisError::UnexpectedResponse {
1495                    expected: "valid UTF-8 bulk string",
1496                    actual: format!("{data:?}"),
1497                })?;
1498                s.parse::<f64>()
1499                    .map_err(|_| RedisError::UnexpectedResponse {
1500                        expected: "float string",
1501                        actual: s.to_string(),
1502                    })
1503            }
1504            other => Err(RedisError::UnexpectedResponse {
1505                expected: "bulk string",
1506                actual: format!("{other:?}"),
1507            }),
1508        }
1509    }
1510
1511    fn name(&self) -> &str {
1512        "INCRBYFLOAT"
1513    }
1514}
1515
1516/// DECR key
1517///
1518/// Decrements the integer value of `key` by one.
1519#[derive(Clone)]
1520pub struct Decr {
1521    key: CommandArg,
1522}
1523
1524impl Decr {
1525    /// Create a new [`Decr`] command.
1526    pub fn new(key: impl Into<CommandArg>) -> Self {
1527        Self { key: key.into() }
1528    }
1529}
1530
1531impl Command for Decr {
1532    type Response = i64;
1533
1534    fn to_frame(&self) -> Frame {
1535        array(vec![bulk("DECR"), bulk(self.key.as_bytes())])
1536    }
1537
1538    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1539        match frame {
1540            Frame::Integer(n) => Ok(n),
1541            other => Err(RedisError::UnexpectedResponse {
1542                expected: "integer",
1543                actual: format!("{other:?}"),
1544            }),
1545        }
1546    }
1547
1548    fn name(&self) -> &str {
1549        "DECR"
1550    }
1551}
1552
1553/// DECRBY key decrement
1554///
1555/// Decrements the integer value of `key` by `decrement`.
1556#[derive(Clone)]
1557pub struct DecrBy {
1558    key: CommandArg,
1559    decrement: i64,
1560}
1561
1562impl DecrBy {
1563    /// Create a new [`DecrBy`] command.
1564    pub fn new(key: impl Into<CommandArg>, decrement: i64) -> Self {
1565        Self {
1566            key: key.into(),
1567            decrement,
1568        }
1569    }
1570}
1571
1572impl Command for DecrBy {
1573    type Response = i64;
1574
1575    fn to_frame(&self) -> Frame {
1576        array(vec![
1577            bulk("DECRBY"),
1578            bulk(self.key.as_bytes()),
1579            bulk(self.decrement.to_string()),
1580        ])
1581    }
1582
1583    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1584        match frame {
1585            Frame::Integer(n) => Ok(n),
1586            other => Err(RedisError::UnexpectedResponse {
1587                expected: "integer",
1588                actual: format!("{other:?}"),
1589            }),
1590        }
1591    }
1592
1593    fn name(&self) -> &str {
1594        "DECRBY"
1595    }
1596}
1597
1598/// GETRANGE key start end
1599///
1600/// Returns the substring of the string value stored at `key`, determined
1601/// by the offsets `start` and `end` (both inclusive).
1602#[derive(Clone)]
1603pub struct GetRange {
1604    key: CommandArg,
1605    start: i64,
1606    end: i64,
1607}
1608
1609impl GetRange {
1610    /// Create a new [`GetRange`] command.
1611    pub fn new(key: impl Into<CommandArg>, start: i64, end: i64) -> Self {
1612        Self {
1613            key: key.into(),
1614            start,
1615            end,
1616        }
1617    }
1618}
1619
1620impl Command for GetRange {
1621    type Response = Bytes;
1622
1623    fn to_frame(&self) -> Frame {
1624        array(vec![
1625            bulk("GETRANGE"),
1626            bulk(self.key.as_bytes()),
1627            bulk(self.start.to_string()),
1628            bulk(self.end.to_string()),
1629        ])
1630    }
1631
1632    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1633        match frame {
1634            Frame::BulkString(Some(data)) => Ok(data),
1635            other => Err(RedisError::UnexpectedResponse {
1636                expected: "bulk string",
1637                actual: format!("{other:?}"),
1638            }),
1639        }
1640    }
1641
1642    fn name(&self) -> &str {
1643        "GETRANGE"
1644    }
1645
1646    fn idempotent(&self) -> bool {
1647        true
1648    }
1649}
1650
1651/// SETRANGE key offset value
1652///
1653/// Overwrites part of the string stored at `key`, starting at the
1654/// specified byte `offset`. Returns the length of the string after the
1655/// modification.
1656#[derive(Clone)]
1657pub struct SetRange {
1658    key: CommandArg,
1659    offset: i64,
1660    value: CommandArg,
1661}
1662
1663impl SetRange {
1664    /// Create a new [`SetRange`] command.
1665    pub fn new(key: impl Into<CommandArg>, offset: i64, value: impl Into<CommandArg>) -> Self {
1666        Self {
1667            key: key.into(),
1668            offset,
1669            value: value.into(),
1670        }
1671    }
1672}
1673
1674impl Command for SetRange {
1675    type Response = i64;
1676
1677    fn to_frame(&self) -> Frame {
1678        array(vec![
1679            bulk("SETRANGE"),
1680            bulk(self.key.as_bytes()),
1681            bulk(self.offset.to_string()),
1682            bulk(self.value.as_bytes()),
1683        ])
1684    }
1685
1686    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1687        match frame {
1688            Frame::Integer(n) => Ok(n),
1689            other => Err(RedisError::UnexpectedResponse {
1690                expected: "integer",
1691                actual: format!("{other:?}"),
1692            }),
1693        }
1694    }
1695
1696    fn name(&self) -> &str {
1697        "SETRANGE"
1698    }
1699}
1700
1701/// STRLEN key
1702///
1703/// Returns the length of the string value stored at `key`, or 0 if the
1704/// key does not exist.
1705#[derive(Clone)]
1706pub struct StrLen {
1707    key: CommandArg,
1708}
1709
1710impl StrLen {
1711    /// Create a new [`StrLen`] command.
1712    pub fn new(key: impl Into<CommandArg>) -> Self {
1713        Self { key: key.into() }
1714    }
1715}
1716
1717impl Command for StrLen {
1718    type Response = i64;
1719
1720    fn to_frame(&self) -> Frame {
1721        array(vec![bulk("STRLEN"), bulk(self.key.as_bytes())])
1722    }
1723
1724    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1725        match frame {
1726            Frame::Integer(n) => Ok(n),
1727            other => Err(RedisError::UnexpectedResponse {
1728                expected: "integer",
1729                actual: format!("{other:?}"),
1730            }),
1731        }
1732    }
1733
1734    fn name(&self) -> &str {
1735        "STRLEN"
1736    }
1737
1738    fn idempotent(&self) -> bool {
1739        true
1740    }
1741}
1742
1743/// INCRBY key increment
1744///
1745/// Increments the integer value of `key` by `increment`. Returns the new
1746/// value after the increment.
1747#[derive(Clone)]
1748pub struct IncrBy {
1749    key: CommandArg,
1750    increment: i64,
1751}
1752
1753impl IncrBy {
1754    /// Create a new [`IncrBy`] command.
1755    pub fn new(key: impl Into<CommandArg>, increment: i64) -> Self {
1756        Self {
1757            key: key.into(),
1758            increment,
1759        }
1760    }
1761}
1762
1763impl Command for IncrBy {
1764    type Response = i64;
1765
1766    fn to_frame(&self) -> Frame {
1767        array(vec![
1768            bulk("INCRBY"),
1769            bulk(self.key.as_bytes()),
1770            bulk(self.increment.to_string()),
1771        ])
1772    }
1773
1774    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1775        match frame {
1776            Frame::Integer(n) => Ok(n),
1777            other => Err(RedisError::UnexpectedResponse {
1778                expected: "integer",
1779                actual: format!("{other:?}"),
1780            }),
1781        }
1782    }
1783
1784    fn name(&self) -> &str {
1785        "INCRBY"
1786    }
1787}
1788
1789/// MSETNX key value \[key value ...\]
1790///
1791/// Sets the given keys to their respective values, but only if none of the
1792/// keys already exist. Returns `true` if all keys were set, `false` if no
1793/// key was set (at least one already existed).
1794#[derive(Clone)]
1795pub struct MSetNx {
1796    pairs: Vec<(CommandArg, CommandArg)>,
1797}
1798
1799impl MSetNx {
1800    /// Create a new [`MSetNx`] command.
1801    pub fn new(
1802        pairs: impl IntoIterator<Item = (impl Into<CommandArg>, impl Into<CommandArg>)>,
1803    ) -> Self {
1804        Self {
1805            pairs: pairs
1806                .into_iter()
1807                .map(|(k, v)| (k.into(), v.into()))
1808                .collect(),
1809        }
1810    }
1811}
1812
1813impl Command for MSetNx {
1814    type Response = bool;
1815
1816    fn to_frame(&self) -> Frame {
1817        let mut args = vec![bulk("MSETNX")];
1818        for (k, v) in &self.pairs {
1819            args.push(bulk(k.as_bytes()));
1820            args.push(bulk(v.as_bytes()));
1821        }
1822        array(args)
1823    }
1824
1825    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1826        match frame {
1827            Frame::Integer(1) => Ok(true),
1828            Frame::Integer(0) => Ok(false),
1829            other => Err(RedisError::UnexpectedResponse {
1830                expected: "integer 0 or 1",
1831                actual: format!("{other:?}"),
1832            }),
1833        }
1834    }
1835
1836    fn name(&self) -> &str {
1837        "MSETNX"
1838    }
1839}
1840
1841/// Mode selector for the LCS command.
1842#[derive(Clone)]
1843pub enum LcsMode {
1844    /// Return the longest common substring as bytes.
1845    String,
1846    /// Return only the length of the longest common substring.
1847    Len,
1848    /// Return match indices. Optionally filter by minimum match length and
1849    /// include match lengths.
1850    Idx {
1851        /// Optional minimum length for reported matches.
1852        min_match_len: Option<u64>,
1853        /// Whether each reported match should include its length.
1854        with_match_len: bool,
1855    },
1856}
1857
1858/// LCS key1 key2 \[LEN\] \[IDX\] \[MINMATCHLEN len\] \[WITHMATCHLEN\]
1859///
1860/// Returns the longest common substring between the values stored at two
1861/// keys. The response type depends on the selected mode: a bulk string for
1862/// the default mode, an integer for LEN mode, or a raw Frame for IDX mode
1863/// (which returns a complex nested structure).
1864#[derive(Clone)]
1865pub struct Lcs {
1866    key1: CommandArg,
1867    key2: CommandArg,
1868    mode: LcsMode,
1869}
1870
1871impl Lcs {
1872    /// Create a new LCS command in default (string) mode.
1873    pub fn new(key1: impl Into<CommandArg>, key2: impl Into<CommandArg>) -> Self {
1874        Self {
1875            key1: key1.into(),
1876            key2: key2.into(),
1877            mode: LcsMode::String,
1878        }
1879    }
1880
1881    /// Switch to LEN mode -- returns only the length.
1882    pub fn len(mut self) -> Self {
1883        self.mode = LcsMode::Len;
1884        self
1885    }
1886
1887    /// Switch to IDX mode -- returns match positions.
1888    pub fn idx(mut self) -> Self {
1889        self.mode = LcsMode::Idx {
1890            min_match_len: None,
1891            with_match_len: false,
1892        };
1893        self
1894    }
1895
1896    /// Set the MINMATCHLEN option (only meaningful in IDX mode).
1897    pub fn min_match_len(mut self, len: u64) -> Self {
1898        match &mut self.mode {
1899            LcsMode::Idx { min_match_len, .. } => *min_match_len = Some(len),
1900            _ => {
1901                self.mode = LcsMode::Idx {
1902                    min_match_len: Some(len),
1903                    with_match_len: false,
1904                };
1905            }
1906        }
1907        self
1908    }
1909
1910    /// Enable WITHMATCHLEN (only meaningful in IDX mode).
1911    pub fn with_match_len(mut self) -> Self {
1912        match &mut self.mode {
1913            LcsMode::Idx { with_match_len, .. } => *with_match_len = true,
1914            _ => {
1915                self.mode = LcsMode::Idx {
1916                    min_match_len: None,
1917                    with_match_len: true,
1918                };
1919            }
1920        }
1921        self
1922    }
1923}
1924
1925impl Command for Lcs {
1926    /// The response is a raw `Frame` because the structure varies by mode:
1927    /// bulk string in default mode, integer in LEN mode, and a nested
1928    /// array/map in IDX mode.
1929    type Response = Frame;
1930
1931    fn to_frame(&self) -> Frame {
1932        let mut args = vec![
1933            bulk("LCS"),
1934            bulk(self.key1.as_bytes()),
1935            bulk(self.key2.as_bytes()),
1936        ];
1937
1938        match &self.mode {
1939            LcsMode::String => {}
1940            LcsMode::Len => {
1941                args.push(bulk("LEN"));
1942            }
1943            LcsMode::Idx {
1944                min_match_len,
1945                with_match_len,
1946            } => {
1947                args.push(bulk("IDX"));
1948                if let Some(len) = min_match_len {
1949                    args.push(bulk("MINMATCHLEN"));
1950                    args.push(bulk(len.to_string()));
1951                }
1952                if *with_match_len {
1953                    args.push(bulk("WITHMATCHLEN"));
1954                }
1955            }
1956        }
1957
1958        array(args)
1959    }
1960
1961    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1962        Ok(frame)
1963    }
1964
1965    fn name(&self) -> &str {
1966        "LCS"
1967    }
1968
1969    fn idempotent(&self) -> bool {
1970        true
1971    }
1972}
1973
1974/// GETSET key value
1975///
1976/// Atomically sets `key` to `value` and returns the old value stored at
1977/// `key`. Returns `None` if the key did not exist previously.
1978///
1979/// Note: GETSET is deprecated in favor of `SET key value GET`, but remains
1980/// widely used.
1981#[derive(Clone)]
1982pub struct GetSet {
1983    key: CommandArg,
1984    value: CommandArg,
1985}
1986
1987impl GetSet {
1988    /// Create a new [`GetSet`] command.
1989    pub fn new(key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
1990        Self {
1991            key: key.into(),
1992            value: value.into(),
1993        }
1994    }
1995}
1996
1997impl Command for GetSet {
1998    type Response = Option<Bytes>;
1999
2000    fn to_frame(&self) -> Frame {
2001        array(vec![
2002            bulk("GETSET"),
2003            bulk(self.key.as_bytes()),
2004            bulk(self.value.as_bytes()),
2005        ])
2006    }
2007
2008    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2009        match frame {
2010            Frame::BulkString(data) => Ok(data),
2011            Frame::Null => Ok(None),
2012            other => Err(RedisError::UnexpectedResponse {
2013                expected: "bulk string or null",
2014                actual: format!("{other:?}"),
2015            }),
2016        }
2017    }
2018
2019    fn name(&self) -> &str {
2020        "GETSET"
2021    }
2022}
2023
2024#[cfg(test)]
2025mod tests {
2026    use super::*;
2027    use redis_tower_core::Command;
2028    use redis_tower_protocol::Frame;
2029    use redis_tower_protocol::helpers::{array, bulk};
2030
2031    // -- Get --
2032
2033    #[test]
2034    fn get_to_frame() {
2035        let cmd = Get::new("mykey");
2036        let frame = cmd.to_frame();
2037        assert_eq!(frame, array(vec![bulk("GET"), bulk("mykey")]));
2038    }
2039
2040    #[test]
2041    fn get_parse_bulk_string() {
2042        let cmd = Get::new("mykey");
2043        let frame = Frame::BulkString(Some(Bytes::from("hello")));
2044        let result = cmd.parse_response(frame).unwrap();
2045        assert_eq!(result, Some(Bytes::from("hello")));
2046    }
2047
2048    #[test]
2049    fn get_parse_null() {
2050        let cmd = Get::new("mykey");
2051        let result = cmd.parse_response(Frame::Null).unwrap();
2052        assert_eq!(result, None);
2053    }
2054
2055    #[test]
2056    fn get_parse_error_on_integer() {
2057        let cmd = Get::new("mykey");
2058        assert!(cmd.parse_response(Frame::Integer(42)).is_err());
2059    }
2060
2061    // -- Set --
2062
2063    #[test]
2064    fn set_basic_to_frame() {
2065        let cmd = Set::new("k", "v");
2066        let frame = cmd.to_frame();
2067        assert_eq!(frame, array(vec![bulk("SET"), bulk("k"), bulk("v")]));
2068    }
2069
2070    #[test]
2071    fn set_with_ex_nx_to_frame() {
2072        let cmd = Set::new("k", "v").ex(60).nx();
2073        let frame = cmd.to_frame();
2074        assert_eq!(
2075            frame,
2076            array(vec![
2077                bulk("SET"),
2078                bulk("k"),
2079                bulk("v"),
2080                bulk("EX"),
2081                bulk("60"),
2082                bulk("NX"),
2083            ])
2084        );
2085    }
2086
2087    #[test]
2088    fn set_with_px_xx_get_to_frame() {
2089        let cmd = Set::new("k", "v").px(5000).xx().get();
2090        let frame = cmd.to_frame();
2091        assert_eq!(
2092            frame,
2093            array(vec![
2094                bulk("SET"),
2095                bulk("k"),
2096                bulk("v"),
2097                bulk("PX"),
2098                bulk("5000"),
2099                bulk("XX"),
2100                bulk("GET"),
2101            ])
2102        );
2103    }
2104
2105    #[test]
2106    fn set_parse_ok() {
2107        let cmd = Set::new("k", "v");
2108        let frame = Frame::SimpleString(Bytes::from("OK"));
2109        let result = cmd.parse_response(frame).unwrap();
2110        assert_eq!(result, None);
2111    }
2112
2113    #[test]
2114    fn set_parse_bulk_with_get() {
2115        let cmd = Set::new("k", "v").get();
2116        let frame = Frame::BulkString(Some(Bytes::from("old")));
2117        let result = cmd.parse_response(frame).unwrap();
2118        assert_eq!(result, Some(Bytes::from("old")));
2119    }
2120
2121    #[test]
2122    fn set_parse_null_nx_failure() {
2123        let cmd = Set::new("k", "v").nx();
2124        let result = cmd.parse_response(Frame::Null).unwrap();
2125        assert_eq!(result, None);
2126    }
2127
2128    // -- Incr --
2129
2130    #[test]
2131    fn incr_to_frame() {
2132        let cmd = Incr::new("counter");
2133        assert_eq!(cmd.to_frame(), array(vec![bulk("INCR"), bulk("counter")]));
2134    }
2135
2136    #[test]
2137    fn incr_parse_integer() {
2138        let cmd = Incr::new("counter");
2139        assert_eq!(cmd.parse_response(Frame::Integer(5)).unwrap(), 5);
2140    }
2141
2142    #[test]
2143    fn incr_parse_error_on_string() {
2144        let cmd = Incr::new("counter");
2145        assert!(
2146            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2147                .is_err()
2148        );
2149    }
2150
2151    // -- IncrBy --
2152
2153    #[test]
2154    fn incrby_to_frame() {
2155        let cmd = IncrBy::new("counter", 10);
2156        assert_eq!(
2157            cmd.to_frame(),
2158            array(vec![bulk("INCRBY"), bulk("counter"), bulk("10")])
2159        );
2160    }
2161
2162    // -- IncrByFloat --
2163
2164    #[test]
2165    fn incrbyfloat_to_frame() {
2166        let cmd = IncrByFloat::new("key", 1.5);
2167        assert_eq!(
2168            cmd.to_frame(),
2169            array(vec![bulk("INCRBYFLOAT"), bulk("key"), bulk("1.5")])
2170        );
2171    }
2172
2173    #[test]
2174    fn incrbyfloat_parse_response() {
2175        let cmd = IncrByFloat::new("key", 1.5);
2176        let frame = Frame::BulkString(Some(Bytes::from("11.5")));
2177        let result = cmd.parse_response(frame).unwrap();
2178        assert!((result - 11.5).abs() < f64::EPSILON);
2179    }
2180
2181    // -- MGet --
2182
2183    #[test]
2184    fn mget_to_frame() {
2185        let cmd = MGet::new(vec!["a", "b", "c"]);
2186        assert_eq!(
2187            cmd.to_frame(),
2188            array(vec![bulk("MGET"), bulk("a"), bulk("b"), bulk("c")])
2189        );
2190    }
2191
2192    #[test]
2193    fn mget_parse_mixed_results() {
2194        let cmd = MGet::new(vec!["a", "b"]);
2195        let frame = array(vec![
2196            Frame::BulkString(Some(Bytes::from("val_a"))),
2197            Frame::Null,
2198        ]);
2199        let result = cmd.parse_response(frame).unwrap();
2200        assert_eq!(result, vec![Some(Bytes::from("val_a")), None]);
2201    }
2202
2203    #[test]
2204    fn mget_parse_error_on_integer() {
2205        let cmd = MGet::new(vec!["a"]);
2206        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2207    }
2208
2209    // -- MSet --
2210
2211    #[test]
2212    fn mset_to_frame() {
2213        let cmd = MSet::new(vec![("a", "1"), ("b", "2")]);
2214        assert_eq!(
2215            cmd.to_frame(),
2216            array(vec![
2217                bulk("MSET"),
2218                bulk("a"),
2219                bulk("1"),
2220                bulk("b"),
2221                bulk("2")
2222            ])
2223        );
2224    }
2225
2226    #[test]
2227    fn mset_parse_ok() {
2228        let cmd = MSet::new(vec![("a", "1")]);
2229        let frame = Frame::SimpleString(Bytes::from("OK"));
2230        cmd.parse_response(frame).unwrap();
2231    }
2232
2233    // -- SetNx --
2234
2235    #[test]
2236    fn setnx_parse_true() {
2237        let cmd = SetNx::new("k", "v");
2238        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2239    }
2240
2241    #[test]
2242    fn setnx_parse_false() {
2243        let cmd = SetNx::new("k", "v");
2244        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
2245    }
2246
2247    // -- GetEx --
2248
2249    #[test]
2250    fn getex_with_persist_to_frame() {
2251        let cmd = GetEx::new("mykey").persist();
2252        assert_eq!(
2253            cmd.to_frame(),
2254            array(vec![bulk("GETEX"), bulk("mykey"), bulk("PERSIST")])
2255        );
2256    }
2257
2258    #[test]
2259    fn getex_with_exat_to_frame() {
2260        let cmd = GetEx::new("mykey").exat(1000);
2261        assert_eq!(
2262            cmd.to_frame(),
2263            array(vec![
2264                bulk("GETEX"),
2265                bulk("mykey"),
2266                bulk("EXAT"),
2267                bulk("1000")
2268            ])
2269        );
2270    }
2271
2272    // -- Append --
2273
2274    #[test]
2275    fn append_to_frame() {
2276        let cmd = Append::new("mykey", "world");
2277        assert_eq!(
2278            cmd.to_frame(),
2279            array(vec![bulk("APPEND"), bulk("mykey"), bulk("world")])
2280        );
2281    }
2282
2283    #[test]
2284    fn append_parse_integer() {
2285        let cmd = Append::new("mykey", "world");
2286        assert_eq!(cmd.parse_response(Frame::Integer(10)).unwrap(), 10);
2287    }
2288
2289    // -- MSetNx --
2290
2291    #[test]
2292    fn msetnx_to_frame() {
2293        let cmd = MSetNx::new(vec![("a", "1"), ("b", "2")]);
2294        assert_eq!(
2295            cmd.to_frame(),
2296            array(vec![
2297                bulk("MSETNX"),
2298                bulk("a"),
2299                bulk("1"),
2300                bulk("b"),
2301                bulk("2")
2302            ])
2303        );
2304    }
2305
2306    #[test]
2307    fn msetnx_parse_true() {
2308        let cmd = MSetNx::new(vec![("a", "1")]);
2309        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2310    }
2311
2312    // -- Lcs --
2313
2314    #[test]
2315    fn lcs_len_to_frame() {
2316        let cmd = Lcs::new("k1", "k2").len();
2317        assert_eq!(
2318            cmd.to_frame(),
2319            array(vec![bulk("LCS"), bulk("k1"), bulk("k2"), bulk("LEN")])
2320        );
2321    }
2322
2323    // -- DelEx --
2324
2325    #[test]
2326    fn delex_unconditional_to_frame() {
2327        let cmd = DelEx::new("key");
2328        assert_eq!(cmd.to_frame(), array(vec![bulk("DELEX"), bulk("key")]));
2329    }
2330
2331    #[test]
2332    fn delex_value_conditions_to_frame() {
2333        assert_eq!(
2334            DelEx::new("key").if_eq("value").to_frame(),
2335            array(vec![
2336                bulk("DELEX"),
2337                bulk("key"),
2338                bulk("IFEQ"),
2339                bulk("value"),
2340            ])
2341        );
2342        assert_eq!(
2343            DelEx::new("key").if_ne("value").to_frame(),
2344            array(vec![
2345                bulk("DELEX"),
2346                bulk("key"),
2347                bulk("IFNE"),
2348                bulk("value"),
2349            ])
2350        );
2351    }
2352
2353    #[test]
2354    fn delex_digest_conditions_to_frame() {
2355        assert_eq!(
2356            DelEx::new("key").if_digest_eq("abc123").to_frame(),
2357            array(vec![
2358                bulk("DELEX"),
2359                bulk("key"),
2360                bulk("IFDEQ"),
2361                bulk("abc123"),
2362            ])
2363        );
2364        assert_eq!(
2365            DelEx::new("key").if_digest_ne("abc123").to_frame(),
2366            array(vec![
2367                bulk("DELEX"),
2368                bulk("key"),
2369                bulk("IFDNE"),
2370                bulk("abc123"),
2371            ])
2372        );
2373    }
2374
2375    #[test]
2376    fn delex_last_condition_wins() {
2377        let cmd = DelEx::new("key")
2378            .if_eq("old")
2379            .if_ne("new")
2380            .if_digest_eq("first")
2381            .if_digest_ne("last");
2382        assert_eq!(
2383            cmd.to_frame(),
2384            array(vec![
2385                bulk("DELEX"),
2386                bulk("key"),
2387                bulk("IFDNE"),
2388                bulk("last"),
2389            ])
2390        );
2391    }
2392
2393    #[test]
2394    fn delex_parse_zero_or_one() {
2395        let cmd = DelEx::new("key");
2396        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2397        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
2398    }
2399
2400    #[test]
2401    fn delex_rejects_invalid_response() {
2402        let cmd = DelEx::new("key");
2403        assert!(cmd.parse_response(Frame::Integer(2)).is_err());
2404        assert!(
2405            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2406                .is_err()
2407        );
2408    }
2409
2410    // -- Digest --
2411
2412    #[test]
2413    fn digest_to_frame() {
2414        let cmd = Digest::new("key");
2415        assert_eq!(cmd.to_frame(), array(vec![bulk("DIGEST"), bulk("key")]));
2416    }
2417
2418    #[test]
2419    fn digest_parse_value_and_nulls() {
2420        let cmd = Digest::new("key");
2421        let digest = Bytes::from("b6acb9d84a38ff74");
2422        assert_eq!(
2423            cmd.parse_response(Frame::BulkString(Some(digest.clone())))
2424                .unwrap(),
2425            Some(digest)
2426        );
2427        assert_eq!(cmd.parse_response(Frame::BulkString(None)).unwrap(), None);
2428        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
2429    }
2430
2431    #[test]
2432    fn digest_rejects_non_bulk_response() {
2433        let cmd = Digest::new("key");
2434        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2435    }
2436
2437    // -- MSetEx --
2438
2439    #[test]
2440    fn msetex_to_frame_and_key_positions() {
2441        let cmd = MSetEx::new(vec![("key1", "value1"), ("key2", "value2")]);
2442        let expected = array(vec![
2443            bulk("MSETEX"),
2444            bulk("2"),
2445            bulk("key1"),
2446            bulk("value1"),
2447            bulk("key2"),
2448            bulk("value2"),
2449        ]);
2450        let frame = cmd.to_frame();
2451        assert_eq!(frame, expected);
2452
2453        let Frame::Array(Some(args)) = frame else {
2454            panic!("MSETEX request must be an array");
2455        };
2456        assert_eq!(args[1], bulk("2"), "argv[1] is the key count");
2457        assert_eq!(args[2], bulk("key1"), "the first key is at argv[2]");
2458        assert_eq!(args[4], bulk("key2"), "keys repeat every two arguments");
2459    }
2460
2461    #[test]
2462    fn msetex_nx_ex_to_frame() {
2463        let cmd = MSetEx::new(vec![("key", "value")]).nx().ex(60);
2464        assert_eq!(
2465            cmd.to_frame(),
2466            array(vec![
2467                bulk("MSETEX"),
2468                bulk("1"),
2469                bulk("key"),
2470                bulk("value"),
2471                bulk("NX"),
2472                bulk("EX"),
2473                bulk("60"),
2474            ])
2475        );
2476    }
2477
2478    #[test]
2479    fn msetex_xx_px_to_frame() {
2480        let cmd = MSetEx::new(vec![("key", "value")]).xx().px(1500);
2481        assert_eq!(
2482            cmd.to_frame(),
2483            array(vec![
2484                bulk("MSETEX"),
2485                bulk("1"),
2486                bulk("key"),
2487                bulk("value"),
2488                bulk("XX"),
2489                bulk("PX"),
2490                bulk("1500"),
2491            ])
2492        );
2493    }
2494
2495    #[test]
2496    fn msetex_absolute_expirations_to_frame() {
2497        let base = || MSetEx::new(vec![("key", "value")]);
2498        assert_eq!(
2499            base().exat(1_700_000_000).to_frame(),
2500            array(vec![
2501                bulk("MSETEX"),
2502                bulk("1"),
2503                bulk("key"),
2504                bulk("value"),
2505                bulk("EXAT"),
2506                bulk("1700000000"),
2507            ])
2508        );
2509        assert_eq!(
2510            base().pxat(1_700_000_000_000).to_frame(),
2511            array(vec![
2512                bulk("MSETEX"),
2513                bulk("1"),
2514                bulk("key"),
2515                bulk("value"),
2516                bulk("PXAT"),
2517                bulk("1700000000000"),
2518            ])
2519        );
2520    }
2521
2522    #[test]
2523    fn msetex_latest_condition_and_expiration_win() {
2524        let cmd = MSetEx::new(vec![("key", "value")])
2525            .nx()
2526            .xx()
2527            .ex(1)
2528            .px(2)
2529            .exat(3)
2530            .pxat(4)
2531            .keep_ttl();
2532        assert_eq!(
2533            cmd.to_frame(),
2534            array(vec![
2535                bulk("MSETEX"),
2536                bulk("1"),
2537                bulk("key"),
2538                bulk("value"),
2539                bulk("XX"),
2540                bulk("KEEPTTL"),
2541            ])
2542        );
2543    }
2544
2545    #[test]
2546    fn msetex_parse_zero_or_one() {
2547        let cmd = MSetEx::new(vec![("key", "value")]);
2548        assert!(cmd.parse_response(Frame::Integer(1)).unwrap());
2549        assert!(!cmd.parse_response(Frame::Integer(0)).unwrap());
2550    }
2551
2552    #[test]
2553    fn msetex_rejects_invalid_response() {
2554        let cmd = MSetEx::new(vec![("key", "value")]);
2555        assert!(cmd.parse_response(Frame::Integer(2)).is_err());
2556        assert!(
2557            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2558                .is_err()
2559        );
2560    }
2561
2562    // -- IncrEx --
2563
2564    #[test]
2565    fn increx_default_to_frame() {
2566        let cmd = IncrEx::new("counter");
2567        assert_eq!(cmd.to_frame(), array(vec![bulk("INCREX"), bulk("counter")]));
2568    }
2569
2570    #[test]
2571    fn increx_integer_and_float_increments_to_frame() {
2572        assert_eq!(
2573            IncrEx::new("counter").by_int(-5).to_frame(),
2574            array(vec![
2575                bulk("INCREX"),
2576                bulk("counter"),
2577                bulk("BYINT"),
2578                bulk("-5"),
2579            ])
2580        );
2581        assert_eq!(
2582            IncrEx::new("counter").by_float(0.25).to_frame(),
2583            array(vec![
2584                bulk("INCREX"),
2585                bulk("counter"),
2586                bulk("BYFLOAT"),
2587                bulk("0.25"),
2588            ])
2589        );
2590    }
2591
2592    #[test]
2593    fn increx_bounds_saturate_and_enx_to_frame() {
2594        let cmd = IncrEx::new("counter")
2595            .by_int(5)
2596            .lower_bound(-10)
2597            .upper_bound(100_i64)
2598            .saturate()
2599            .ex(60)
2600            .enx();
2601        assert_eq!(
2602            cmd.to_frame(),
2603            array(vec![
2604                bulk("INCREX"),
2605                bulk("counter"),
2606                bulk("BYINT"),
2607                bulk("5"),
2608                bulk("LBOUND"),
2609                bulk("-10"),
2610                bulk("UBOUND"),
2611                bulk("100"),
2612                bulk("SATURATE"),
2613                bulk("EX"),
2614                bulk("60"),
2615                bulk("ENX"),
2616            ])
2617        );
2618    }
2619
2620    #[test]
2621    fn increx_float_bounds_to_frame() {
2622        let cmd = IncrEx::new("counter")
2623            .by_float(0.5)
2624            .lower_bound(-1.25_f32)
2625            .upper_bound(9.75);
2626        assert_eq!(
2627            cmd.to_frame(),
2628            array(vec![
2629                bulk("INCREX"),
2630                bulk("counter"),
2631                bulk("BYFLOAT"),
2632                bulk("0.5"),
2633                bulk("LBOUND"),
2634                bulk("-1.25"),
2635                bulk("UBOUND"),
2636                bulk("9.75"),
2637            ])
2638        );
2639    }
2640
2641    #[test]
2642    fn increx_expiration_variants_to_frame() {
2643        let base = || IncrEx::new("counter");
2644        assert_eq!(
2645            base().px(1500).to_frame(),
2646            array(vec![
2647                bulk("INCREX"),
2648                bulk("counter"),
2649                bulk("PX"),
2650                bulk("1500"),
2651            ])
2652        );
2653        assert_eq!(
2654            base().exat(1_700_000_000).to_frame(),
2655            array(vec![
2656                bulk("INCREX"),
2657                bulk("counter"),
2658                bulk("EXAT"),
2659                bulk("1700000000"),
2660            ])
2661        );
2662        assert_eq!(
2663            base().pxat(1_700_000_000_000).to_frame(),
2664            array(vec![
2665                bulk("INCREX"),
2666                bulk("counter"),
2667                bulk("PXAT"),
2668                bulk("1700000000000"),
2669            ])
2670        );
2671    }
2672
2673    #[test]
2674    fn increx_persist_clears_expiration_and_enx() {
2675        let cmd = IncrEx::new("counter").ex(60).enx().px(100).persist();
2676        assert_eq!(
2677            cmd.to_frame(),
2678            array(vec![bulk("INCREX"), bulk("counter"), bulk("PERSIST")])
2679        );
2680    }
2681
2682    #[test]
2683    fn increx_parse_integer_result() {
2684        let cmd = IncrEx::new("counter").by_int(5);
2685        let result = cmd
2686            .parse_response(array(vec![Frame::Integer(15), Frame::Integer(5)]))
2687            .unwrap();
2688        assert_eq!(
2689            result,
2690            IncrExResult::Integer {
2691                value: 15,
2692                actual_increment: 5,
2693            }
2694        );
2695    }
2696
2697    #[test]
2698    fn increx_parse_resp2_float_result() {
2699        let cmd = IncrEx::new("counter").by_float(0.25);
2700        let result = cmd
2701            .parse_response(array(vec![
2702                Frame::BulkString(Some(Bytes::from("1.75"))),
2703                Frame::BulkString(Some(Bytes::from("0.25"))),
2704            ]))
2705            .unwrap();
2706        assert_eq!(
2707            result,
2708            IncrExResult::Float {
2709                value: 1.75,
2710                actual_increment: 0.25,
2711            }
2712        );
2713    }
2714
2715    #[test]
2716    fn increx_parse_resp3_float_result() {
2717        let cmd = IncrEx::new("counter").by_float(0.25);
2718        let result = cmd
2719            .parse_response(array(vec![Frame::Double(1.75), Frame::Double(0.25)]))
2720            .unwrap();
2721        assert_eq!(
2722            result,
2723            IncrExResult::Float {
2724                value: 1.75,
2725                actual_increment: 0.25,
2726            }
2727        );
2728    }
2729
2730    #[test]
2731    fn increx_rejects_malformed_results() {
2732        let integer = IncrEx::new("counter");
2733        assert!(
2734            integer
2735                .parse_response(array(vec![Frame::Integer(1)]))
2736                .is_err()
2737        );
2738        assert!(
2739            integer
2740                .parse_response(array(vec![Frame::Integer(1), Frame::Double(1.0)]))
2741                .is_err()
2742        );
2743        assert!(integer.parse_response(Frame::Array(None)).is_err());
2744
2745        let float = IncrEx::new("counter").by_float(0.5);
2746        assert!(
2747            float
2748                .parse_response(array(vec![
2749                    Frame::BulkString(Some(Bytes::from("not-a-float"))),
2750                    Frame::BulkString(Some(Bytes::from("0.5"))),
2751                ]))
2752                .is_err()
2753        );
2754        assert!(
2755            float
2756                .parse_response(array(vec![
2757                    Frame::BulkString(Some(Bytes::from_static(&[0xff]))),
2758                    Frame::Double(0.5),
2759                ]))
2760                .is_err()
2761        );
2762    }
2763
2764    #[test]
2765    fn new_string_command_metadata() {
2766        let delex = DelEx::new("delex-key");
2767        assert_eq!(delex.name(), "DELEX");
2768        assert!(!delex.idempotent());
2769
2770        let msetex = MSetEx::new(vec![("msetex-key", "value")]);
2771        assert_eq!(msetex.name(), "MSETEX");
2772        assert!(!msetex.idempotent());
2773
2774        let digest = Digest::new("digest-key");
2775        assert_eq!(digest.name(), "DIGEST");
2776        assert!(digest.idempotent());
2777
2778        let increx = IncrEx::new("increx-key");
2779        assert_eq!(increx.name(), "INCREX");
2780        assert!(!increx.idempotent());
2781    }
2782}