Skip to main content

redis_tower_commands/
array.rs

1//! Redis 8.8 array commands.
2//!
3//! This native command family is available in Redis 8.8. Array indexes are
4//! unsigned: ordinary commands accept values through `u64::MAX - 1`;
5//! [`ArSeek`] uniquely accepts `u64::MAX` to place the insert cursor in its
6//! terminal state.
7//!
8//! Commands return typed array entries, counts, booleans, or optional byte
9//! values according to the Redis command. Check the server version before
10//! enabling an array-backed code path.
11//!
12//! ```
13//! use redis_tower_commands::ArGet;
14//! use redis_tower_core::Command;
15//!
16//! let command = ArGet::new("queue", 0);
17//! assert_eq!(command.name(), "ARGET");
18//! ```
19//!
20//! See the [command cookbook] for feature and server prerequisites.
21//!
22//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#feature-gated-and-versioned-families
23
24use std::collections::HashMap;
25
26use bytes::Bytes;
27use redis_tower_core::{Command, Frame, FromFrame, RedisError};
28use redis_tower_protocol::helpers::{array, bulk};
29
30fn owned_bytes(value: impl AsRef<[u8]>) -> Bytes {
31    Bytes::copy_from_slice(value.as_ref())
32}
33
34fn parse_u64(frame: Frame) -> Result<u64, RedisError> {
35    u64::from_frame(frame)
36}
37
38fn parse_i64(frame: Frame) -> Result<i64, RedisError> {
39    i64::from_frame(frame)
40}
41
42fn parse_bool(frame: Frame) -> Result<bool, RedisError> {
43    match frame {
44        Frame::Integer(0) => Ok(false),
45        Frame::Integer(1) => Ok(true),
46        Frame::Boolean(value) => Ok(value),
47        other => Err(RedisError::UnexpectedResponse {
48            expected: "integer 0 or 1, or boolean",
49            actual: format!("{other:?}"),
50        }),
51    }
52}
53
54fn parse_optional_bytes(frame: Frame) -> Result<Option<Bytes>, RedisError> {
55    Option::<Bytes>::from_frame(frame)
56}
57
58fn parse_optional_values(frame: Frame) -> Result<Vec<Option<Bytes>>, RedisError> {
59    Vec::<Option<Bytes>>::from_frame(frame)
60}
61
62/// An existing value and its unsigned array index.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct ArrayEntry {
65    /// The zero-based array index.
66    pub index: u64,
67    /// The binary-safe value stored at `index`.
68    pub value: Bytes,
69}
70
71impl FromFrame for ArrayEntry {
72    fn from_frame(frame: Frame) -> Result<Self, RedisError> {
73        let (index, value) = <(u64, Bytes)>::from_frame(frame)?;
74        Ok(Self { index, value })
75    }
76}
77
78/// A range accepted by [`ArGrep`].
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum ArGrepBound {
81    /// A concrete zero-based array index.
82    Index(u64),
83    /// The logical first index, encoded as `-`.
84    Start,
85    /// The logical last index, encoded as `+`.
86    End,
87}
88
89impl From<u64> for ArGrepBound {
90    fn from(value: u64) -> Self {
91        Self::Index(value)
92    }
93}
94
95impl ArGrepBound {
96    fn append_to(&self, args: &mut Vec<Frame>) {
97        match self {
98            Self::Index(index) => args.push(bulk(index.to_string())),
99            Self::Start => args.push(bulk("-")),
100            Self::End => args.push(bulk("+")),
101        }
102    }
103}
104
105/// A textual predicate accepted by [`ArGrep`].
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum ArGrepPredicate {
108    /// Match values that equal the supplied bytes exactly.
109    Exact(Bytes),
110    /// Match values containing the supplied bytes as a substring.
111    Match(Bytes),
112    /// Match values using Redis glob syntax.
113    Glob(Bytes),
114    /// Match values using a Redis/TRE regular expression.
115    Regex(Bytes),
116}
117
118impl ArGrepPredicate {
119    /// Construct an `EXACT` predicate.
120    pub fn exact(value: impl AsRef<[u8]>) -> Self {
121        Self::Exact(owned_bytes(value))
122    }
123
124    /// Construct a `MATCH` substring predicate.
125    pub fn matches(value: impl AsRef<[u8]>) -> Self {
126        Self::Match(owned_bytes(value))
127    }
128
129    /// Construct a `GLOB` predicate.
130    pub fn glob(pattern: impl AsRef<[u8]>) -> Self {
131        Self::Glob(owned_bytes(pattern))
132    }
133
134    /// Construct an `RE` regular-expression predicate.
135    ///
136    /// Redis 8.8 requires a non-empty pattern of at most 2048 bytes and does
137    /// not support backreferences. Redis validates those constraints.
138    pub fn regex(pattern: impl AsRef<[u8]>) -> Self {
139        Self::Regex(owned_bytes(pattern))
140    }
141
142    fn append_to(&self, args: &mut Vec<Frame>) {
143        let (token, value) = match self {
144            Self::Exact(value) => ("EXACT", value),
145            Self::Match(value) => ("MATCH", value),
146            Self::Glob(value) => ("GLOB", value),
147            Self::Regex(value) => ("RE", value),
148        };
149        args.push(bulk(token));
150        args.push(bulk(value));
151    }
152}
153
154/// How multiple [`ArGrepPredicate`] values are combined.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum ArGrepCombinator {
157    /// Require every predicate to match.
158    And,
159    /// Require at least one predicate to match (the Redis default).
160    Or,
161}
162
163/// The response returned by [`ArGrep`].
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub enum ArGrepResult {
166    /// Matching indexes when `WITHVALUES` is not enabled.
167    Indices(Vec<u64>),
168    /// Matching index-value pairs when `WITHVALUES` is enabled.
169    Entries(Vec<ArrayEntry>),
170}
171
172/// An aggregate operation accepted by [`ArOp`].
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum ArOpOperation {
175    /// Sum numeric values and return bulk numeric text.
176    Sum,
177    /// Return the minimum numeric value as bulk numeric text.
178    Min,
179    /// Return the maximum numeric value as bulk numeric text.
180    Max,
181    /// Apply signed 64-bit bitwise AND.
182    And,
183    /// Apply signed 64-bit bitwise OR.
184    Or,
185    /// Apply signed 64-bit bitwise XOR.
186    Xor,
187    /// Count values equal to the supplied binary-safe value.
188    Match(Bytes),
189    /// Count populated slots in the range.
190    Used,
191}
192
193impl ArOpOperation {
194    /// Construct a binary-safe `MATCH value` operation.
195    pub fn matches(value: impl AsRef<[u8]>) -> Self {
196        Self::Match(owned_bytes(value))
197    }
198
199    fn append_to(&self, args: &mut Vec<Frame>) {
200        match self {
201            Self::Sum => args.push(bulk("SUM")),
202            Self::Min => args.push(bulk("MIN")),
203            Self::Max => args.push(bulk("MAX")),
204            Self::And => args.push(bulk("AND")),
205            Self::Or => args.push(bulk("OR")),
206            Self::Xor => args.push(bulk("XOR")),
207            Self::Match(value) => {
208                args.push(bulk("MATCH"));
209                args.push(bulk(value));
210            }
211            Self::Used => args.push(bulk("USED")),
212        }
213    }
214}
215
216/// The operation-dependent response returned by [`ArOp`].
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub enum ArOpResult {
219    /// `SUM`, `MIN`, or `MAX`: binary-safe numeric text, or `None` when no
220    /// numeric element was present.
221    Value(Option<Bytes>),
222    /// `AND`, `OR`, `XOR`, `MATCH`, or `USED`: an integer, or `None` when a
223    /// bitwise operation had no usable value.
224    Integer(Option<i64>),
225}
226
227/// Extra statistics returned by `ARINFO ... FULL`.
228#[derive(Debug, Clone, PartialEq)]
229pub struct ArInfoFull {
230    /// Number of dense slices.
231    pub dense_slices: u64,
232    /// Number of sparse slices.
233    pub sparse_slices: u64,
234    /// Average allocated dense-window size.
235    pub average_dense_size: f64,
236    /// Average dense-window fill ratio.
237    pub average_dense_fill: f64,
238    /// Average sparse-slice capacity.
239    pub average_sparse_size: f64,
240}
241
242/// Metadata returned by [`ArInfo`].
243#[derive(Debug, Clone, PartialEq)]
244pub struct ArInfoResponse {
245    /// Number of populated slots.
246    pub count: u64,
247    /// Logical length (`maximum index + 1`).
248    pub len: u64,
249    /// Next index used by `ARINSERT`/`ARRING` as reported by Redis.
250    pub next_insert_index: u64,
251    /// Number of allocated slices.
252    pub slices: u64,
253    /// Allocated top-level directory size.
254    pub directory_size: u64,
255    /// Number of populated super-directory entries.
256    pub super_directory_entries: u64,
257    /// Number of logical positions in each slice.
258    pub slice_size: u64,
259    /// Statistics requested with `FULL`.
260    pub full: Option<ArInfoFull>,
261}
262
263fn info_pairs(frame: Frame) -> Result<Vec<(Frame, Frame)>, RedisError> {
264    match frame {
265        Frame::Map(pairs) | Frame::StreamedMap(pairs) | Frame::Attribute(pairs) => Ok(pairs),
266        Frame::Array(Some(items)) => {
267            if items.len() % 2 != 0 {
268                return Err(RedisError::UnexpectedResponse {
269                    expected: "ARINFO map or even-length flat array",
270                    actual: format!("array of {} elements", items.len()),
271                });
272            }
273            let mut items = items.into_iter();
274            let mut pairs = Vec::with_capacity(items.len() / 2);
275            while let (Some(key), Some(value)) = (items.next(), items.next()) {
276                pairs.push((key, value));
277            }
278            Ok(pairs)
279        }
280        other => Err(RedisError::UnexpectedResponse {
281            expected: "ARINFO map or even-length flat array",
282            actual: format!("{other:?}"),
283        }),
284    }
285}
286
287fn parse_info_map(frame: Frame, require_full: bool) -> Result<ArInfoResponse, RedisError> {
288    let mut fields = HashMap::<Bytes, Frame>::new();
289    for (key, value) in info_pairs(frame)? {
290        fields.insert(Bytes::from_frame(key)?, value);
291    }
292
293    fn take<T: FromFrame>(
294        fields: &mut HashMap<Bytes, Frame>,
295        name: &'static [u8],
296    ) -> Result<T, RedisError> {
297        let value = fields
298            .remove(name)
299            .ok_or_else(|| RedisError::UnexpectedResponse {
300                expected: "complete ARINFO field set",
301                actual: format!("missing field {}", String::from_utf8_lossy(name)),
302            })?;
303        T::from_frame(value)
304    }
305
306    let count = take(&mut fields, b"count")?;
307    let len = take(&mut fields, b"len")?;
308    let next_insert_index = take(&mut fields, b"next-insert-index")?;
309    let slices = take(&mut fields, b"slices")?;
310    let directory_size = take(&mut fields, b"directory-size")?;
311    let super_directory_entries = take(&mut fields, b"super-dir-entries")?;
312    let slice_size = take(&mut fields, b"slice-size")?;
313
314    let has_full = require_full
315        || fields.contains_key(&Bytes::from_static(b"dense-slices"))
316        || fields.contains_key(&Bytes::from_static(b"sparse-slices"));
317    let full = if has_full {
318        Some(ArInfoFull {
319            dense_slices: take(&mut fields, b"dense-slices")?,
320            sparse_slices: take(&mut fields, b"sparse-slices")?,
321            average_dense_size: take(&mut fields, b"avg-dense-size")?,
322            average_dense_fill: take(&mut fields, b"avg-dense-fill")?,
323            average_sparse_size: take(&mut fields, b"avg-sparse-size")?,
324        })
325    } else {
326        None
327    };
328
329    Ok(ArInfoResponse {
330        count,
331        len,
332        next_insert_index,
333        slices,
334        directory_size,
335        super_directory_entries,
336        slice_size,
337        full,
338    })
339}
340
341/// ARCOUNT key
342///
343/// Returns the number of populated slots, or zero when `key` is absent.
344#[derive(Debug, Clone)]
345pub struct ArCount {
346    key: Bytes,
347}
348
349impl ArCount {
350    /// Construct an `ARCOUNT` command.
351    pub fn new(key: impl AsRef<[u8]>) -> Self {
352        Self {
353            key: owned_bytes(key),
354        }
355    }
356}
357
358impl Command for ArCount {
359    type Response = u64;
360
361    fn to_frame(&self) -> Frame {
362        array(vec![bulk("ARCOUNT"), bulk(&self.key)])
363    }
364
365    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
366        parse_u64(frame)
367    }
368
369    fn name(&self) -> &str {
370        "ARCOUNT"
371    }
372
373    fn idempotent(&self) -> bool {
374        true
375    }
376}
377
378/// ARDEL key index \[index ...\]
379///
380/// Deletes one or more indexes and returns the number of populated slots that
381/// were removed. Requiring the first index in [`ArDel::new`] prevents an
382/// invalid empty variadic list.
383#[derive(Debug, Clone)]
384pub struct ArDel {
385    key: Bytes,
386    indices: Vec<u64>,
387}
388
389impl ArDel {
390    /// Construct an `ARDEL` command with its first required index.
391    pub fn new(key: impl AsRef<[u8]>, index: u64) -> Self {
392        Self {
393            key: owned_bytes(key),
394            indices: vec![index],
395        }
396    }
397
398    /// Add another index to delete.
399    pub fn index(mut self, index: u64) -> Self {
400        self.indices.push(index);
401        self
402    }
403}
404
405impl Command for ArDel {
406    type Response = u64;
407
408    fn to_frame(&self) -> Frame {
409        let mut args = Vec::with_capacity(2 + self.indices.len());
410        args.push(bulk("ARDEL"));
411        args.push(bulk(&self.key));
412        args.extend(self.indices.iter().map(|index| bulk(index.to_string())));
413        array(args)
414    }
415
416    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
417        parse_u64(frame)
418    }
419
420    fn name(&self) -> &str {
421        "ARDEL"
422    }
423}
424
425/// ARDELRANGE key start end \[start end ...\]
426///
427/// Deletes all populated elements covered by one or more inclusive ranges and
428/// returns the number deleted. Redis accepts each range in either direction.
429#[derive(Debug, Clone)]
430pub struct ArDelRange {
431    key: Bytes,
432    ranges: Vec<(u64, u64)>,
433}
434
435impl ArDelRange {
436    /// Construct an `ARDELRANGE` command with its first required range.
437    pub fn new(key: impl AsRef<[u8]>, start: u64, end: u64) -> Self {
438        Self {
439            key: owned_bytes(key),
440            ranges: vec![(start, end)],
441        }
442    }
443
444    /// Add another inclusive range.
445    pub fn range(mut self, start: u64, end: u64) -> Self {
446        self.ranges.push((start, end));
447        self
448    }
449}
450
451impl Command for ArDelRange {
452    type Response = u64;
453
454    fn to_frame(&self) -> Frame {
455        let mut args = Vec::with_capacity(2 + self.ranges.len() * 2);
456        args.push(bulk("ARDELRANGE"));
457        args.push(bulk(&self.key));
458        for (start, end) in &self.ranges {
459            args.push(bulk(start.to_string()));
460            args.push(bulk(end.to_string()));
461        }
462        array(args)
463    }
464
465    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
466        parse_u64(frame)
467    }
468
469    fn name(&self) -> &str {
470        "ARDELRANGE"
471    }
472}
473
474/// ARGET key index
475///
476/// Returns the binary-safe value at `index`, or `None` for a hole or absent
477/// key.
478#[derive(Debug, Clone)]
479pub struct ArGet {
480    key: Bytes,
481    index: u64,
482}
483
484impl ArGet {
485    /// Construct an `ARGET` command.
486    pub fn new(key: impl AsRef<[u8]>, index: u64) -> Self {
487        Self {
488            key: owned_bytes(key),
489            index,
490        }
491    }
492}
493
494impl Command for ArGet {
495    type Response = Option<Bytes>;
496
497    fn to_frame(&self) -> Frame {
498        array(vec![
499            bulk("ARGET"),
500            bulk(&self.key),
501            bulk(self.index.to_string()),
502        ])
503    }
504
505    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
506        parse_optional_bytes(frame)
507    }
508
509    fn name(&self) -> &str {
510        "ARGET"
511    }
512
513    fn idempotent(&self) -> bool {
514        true
515    }
516}
517
518/// ARGETRANGE key start end
519///
520/// Returns every position in the inclusive range, preserving holes as
521/// `None`. If `start > end`, values are returned in descending index order.
522#[derive(Debug, Clone)]
523pub struct ArGetRange {
524    key: Bytes,
525    start: u64,
526    end: u64,
527}
528
529impl ArGetRange {
530    /// Construct an `ARGETRANGE` command.
531    pub fn new(key: impl AsRef<[u8]>, start: u64, end: u64) -> Self {
532        Self {
533            key: owned_bytes(key),
534            start,
535            end,
536        }
537    }
538}
539
540impl Command for ArGetRange {
541    type Response = Vec<Option<Bytes>>;
542
543    fn to_frame(&self) -> Frame {
544        array(vec![
545            bulk("ARGETRANGE"),
546            bulk(&self.key),
547            bulk(self.start.to_string()),
548            bulk(self.end.to_string()),
549        ])
550    }
551
552    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
553        parse_optional_values(frame)
554    }
555
556    fn name(&self) -> &str {
557        "ARGETRANGE"
558    }
559
560    fn idempotent(&self) -> bool {
561        true
562    }
563}
564
565/// ARGREP key start end predicate \[predicate ...\] \[options ...\]
566///
567/// Searches populated array elements with one or more textual predicates.
568/// Redis defaults to `OR`, an unlimited result count, and case-sensitive
569/// matching. [`ArGrep::with_values`] changes the response variant from
570/// [`ArGrepResult::Indices`] to [`ArGrepResult::Entries`].
571#[derive(Debug, Clone)]
572pub struct ArGrep {
573    key: Bytes,
574    start: ArGrepBound,
575    end: ArGrepBound,
576    predicates: Vec<ArGrepPredicate>,
577    combinator: Option<ArGrepCombinator>,
578    limit: Option<u64>,
579    with_values: bool,
580    nocase: bool,
581}
582
583impl ArGrep {
584    /// Construct an `ARGREP` command with its first required predicate.
585    pub fn new(
586        key: impl AsRef<[u8]>,
587        start: impl Into<ArGrepBound>,
588        end: impl Into<ArGrepBound>,
589        predicate: ArGrepPredicate,
590    ) -> Self {
591        Self {
592            key: owned_bytes(key),
593            start: start.into(),
594            end: end.into(),
595            predicates: vec![predicate],
596            combinator: None,
597            limit: None,
598            with_values: false,
599            nocase: false,
600        }
601    }
602
603    /// Add another predicate. Redis 8.8 accepts at most 250 predicates.
604    pub fn predicate(mut self, predicate: ArGrepPredicate) -> Self {
605        self.predicates.push(predicate);
606        self
607    }
608
609    /// Combine all predicates with logical AND.
610    pub fn and(mut self) -> Self {
611        self.combinator = Some(ArGrepCombinator::And);
612        self
613    }
614
615    /// Combine all predicates with logical OR.
616    pub fn or(mut self) -> Self {
617        self.combinator = Some(ArGrepCombinator::Or);
618        self
619    }
620
621    /// Stop after `limit` matches. Redis requires a positive value.
622    pub fn limit(mut self, limit: u64) -> Self {
623        self.limit = Some(limit);
624        self
625    }
626
627    /// Return nested index-value entries instead of indexes alone.
628    pub fn with_values(mut self) -> Self {
629        self.with_values = true;
630        self
631    }
632
633    /// Enable ASCII case-insensitive matching for all predicates.
634    pub fn nocase(mut self) -> Self {
635        self.nocase = true;
636        self
637    }
638}
639
640impl Command for ArGrep {
641    type Response = ArGrepResult;
642
643    fn to_frame(&self) -> Frame {
644        let mut args = Vec::with_capacity(4 + self.predicates.len() * 2 + 4);
645        args.push(bulk("ARGREP"));
646        args.push(bulk(&self.key));
647        self.start.append_to(&mut args);
648        self.end.append_to(&mut args);
649        for predicate in &self.predicates {
650            predicate.append_to(&mut args);
651        }
652        match self.combinator {
653            Some(ArGrepCombinator::And) => args.push(bulk("AND")),
654            Some(ArGrepCombinator::Or) => args.push(bulk("OR")),
655            None => {}
656        }
657        if let Some(limit) = self.limit {
658            args.push(bulk("LIMIT"));
659            args.push(bulk(limit.to_string()));
660        }
661        if self.with_values {
662            args.push(bulk("WITHVALUES"));
663        }
664        if self.nocase {
665            args.push(bulk("NOCASE"));
666        }
667        array(args)
668    }
669
670    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
671        if self.with_values {
672            Vec::<ArrayEntry>::from_frame(frame).map(ArGrepResult::Entries)
673        } else {
674            Vec::<u64>::from_frame(frame).map(ArGrepResult::Indices)
675        }
676    }
677
678    fn name(&self) -> &str {
679        "ARGREP"
680    }
681
682    fn idempotent(&self) -> bool {
683        true
684    }
685}
686
687/// ARINFO key \[FULL\]
688///
689/// Returns typed array metadata. RESP2's alternating key-value array and
690/// RESP3's map reply are normalized into [`ArInfoResponse`].
691#[derive(Debug, Clone)]
692pub struct ArInfo {
693    key: Bytes,
694    full: bool,
695}
696
697impl ArInfo {
698    /// Construct a base `ARINFO` command.
699    pub fn new(key: impl AsRef<[u8]>) -> Self {
700        Self {
701            key: owned_bytes(key),
702            full: false,
703        }
704    }
705
706    /// Request the five additional per-encoding slice statistics.
707    pub fn full(mut self) -> Self {
708        self.full = true;
709        self
710    }
711}
712
713impl Command for ArInfo {
714    type Response = ArInfoResponse;
715
716    fn to_frame(&self) -> Frame {
717        let mut args = vec![bulk("ARINFO"), bulk(&self.key)];
718        if self.full {
719            args.push(bulk("FULL"));
720        }
721        array(args)
722    }
723
724    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
725        parse_info_map(frame, self.full)
726    }
727
728    fn name(&self) -> &str {
729        "ARINFO"
730    }
731
732    fn idempotent(&self) -> bool {
733        true
734    }
735}
736
737/// ARINSERT key value \[value ...\]
738///
739/// Inserts values at consecutive cursor positions and returns the last index
740/// written. Requiring the first value in [`ArInsert::new`] prevents an invalid
741/// empty variadic list.
742#[derive(Debug, Clone)]
743pub struct ArInsert {
744    key: Bytes,
745    values: Vec<Bytes>,
746}
747
748impl ArInsert {
749    /// Construct an `ARINSERT` command with its first required value.
750    pub fn new(key: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Self {
751        Self {
752            key: owned_bytes(key),
753            values: vec![owned_bytes(value)],
754        }
755    }
756
757    /// Add another value to the same consecutive insertion batch.
758    pub fn value(mut self, value: impl AsRef<[u8]>) -> Self {
759        self.values.push(owned_bytes(value));
760        self
761    }
762}
763
764impl Command for ArInsert {
765    type Response = u64;
766
767    fn to_frame(&self) -> Frame {
768        let mut args = Vec::with_capacity(2 + self.values.len());
769        args.push(bulk("ARINSERT"));
770        args.push(bulk(&self.key));
771        args.extend(self.values.iter().map(bulk));
772        array(args)
773    }
774
775    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
776        parse_u64(frame)
777    }
778
779    fn name(&self) -> &str {
780        "ARINSERT"
781    }
782}
783
784/// ARLASTITEMS key count \[REV\]
785///
786/// Returns up to `count` cursor-relative positions. The default order is
787/// chronological; [`ArLastItems::rev`] requests newest-first order. Holes are
788/// preserved as `None`.
789#[derive(Debug, Clone)]
790pub struct ArLastItems {
791    key: Bytes,
792    count: u64,
793    rev: bool,
794}
795
796impl ArLastItems {
797    /// Construct an `ARLASTITEMS` command.
798    pub fn new(key: impl AsRef<[u8]>, count: u64) -> Self {
799        Self {
800            key: owned_bytes(key),
801            count,
802            rev: false,
803        }
804    }
805
806    /// Return positions in reverse chronological order (newest first).
807    pub fn rev(mut self) -> Self {
808        self.rev = true;
809        self
810    }
811}
812
813impl Command for ArLastItems {
814    type Response = Vec<Option<Bytes>>;
815
816    fn to_frame(&self) -> Frame {
817        let mut args = vec![
818            bulk("ARLASTITEMS"),
819            bulk(&self.key),
820            bulk(self.count.to_string()),
821        ];
822        if self.rev {
823            args.push(bulk("REV"));
824        }
825        array(args)
826    }
827
828    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
829        parse_optional_values(frame)
830    }
831
832    fn name(&self) -> &str {
833        "ARLASTITEMS"
834    }
835
836    fn idempotent(&self) -> bool {
837        true
838    }
839}
840
841/// ARLEN key
842///
843/// Returns `maximum populated index + 1`, or zero when `key` is absent.
844#[derive(Debug, Clone)]
845pub struct ArLen {
846    key: Bytes,
847}
848
849impl ArLen {
850    /// Construct an `ARLEN` command.
851    pub fn new(key: impl AsRef<[u8]>) -> Self {
852        Self {
853            key: owned_bytes(key),
854        }
855    }
856}
857
858impl Command for ArLen {
859    type Response = u64;
860
861    fn to_frame(&self) -> Frame {
862        array(vec![bulk("ARLEN"), bulk(&self.key)])
863    }
864
865    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
866        parse_u64(frame)
867    }
868
869    fn name(&self) -> &str {
870        "ARLEN"
871    }
872
873    fn idempotent(&self) -> bool {
874        true
875    }
876}
877
878/// ARMGET key index \[index ...\]
879///
880/// Returns one binary-safe optional value for every requested index.
881#[derive(Debug, Clone)]
882pub struct ArMGet {
883    key: Bytes,
884    indices: Vec<u64>,
885}
886
887impl ArMGet {
888    /// Construct an `ARMGET` command with its first required index.
889    pub fn new(key: impl AsRef<[u8]>, index: u64) -> Self {
890        Self {
891            key: owned_bytes(key),
892            indices: vec![index],
893        }
894    }
895
896    /// Add another index to fetch.
897    pub fn index(mut self, index: u64) -> Self {
898        self.indices.push(index);
899        self
900    }
901}
902
903impl Command for ArMGet {
904    type Response = Vec<Option<Bytes>>;
905
906    fn to_frame(&self) -> Frame {
907        let mut args = Vec::with_capacity(2 + self.indices.len());
908        args.push(bulk("ARMGET"));
909        args.push(bulk(&self.key));
910        args.extend(self.indices.iter().map(|index| bulk(index.to_string())));
911        array(args)
912    }
913
914    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
915        parse_optional_values(frame)
916    }
917
918    fn name(&self) -> &str {
919        "ARMGET"
920    }
921
922    fn idempotent(&self) -> bool {
923        true
924    }
925}
926
927/// ARMSET key index value \[index value ...\]
928///
929/// Sets scattered index-value pairs and returns the number of previously empty
930/// slots filled.
931#[derive(Debug, Clone)]
932pub struct ArMSet {
933    key: Bytes,
934    entries: Vec<(u64, Bytes)>,
935}
936
937impl ArMSet {
938    /// Construct an `ARMSET` command with its first required pair.
939    pub fn new(key: impl AsRef<[u8]>, index: u64, value: impl AsRef<[u8]>) -> Self {
940        Self {
941            key: owned_bytes(key),
942            entries: vec![(index, owned_bytes(value))],
943        }
944    }
945
946    /// Add another scattered index-value pair.
947    pub fn pair(mut self, index: u64, value: impl AsRef<[u8]>) -> Self {
948        self.entries.push((index, owned_bytes(value)));
949        self
950    }
951}
952
953impl Command for ArMSet {
954    type Response = u64;
955
956    fn to_frame(&self) -> Frame {
957        let mut args = Vec::with_capacity(2 + self.entries.len() * 2);
958        args.push(bulk("ARMSET"));
959        args.push(bulk(&self.key));
960        for (index, value) in &self.entries {
961            args.push(bulk(index.to_string()));
962            args.push(bulk(value));
963        }
964        array(args)
965    }
966
967    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
968        parse_u64(frame)
969    }
970
971    fn name(&self) -> &str {
972        "ARMSET"
973    }
974}
975
976/// ARNEXT key
977///
978/// Returns the next index `ARINSERT` or `ARRING` would use. A missing key or a
979/// never-used cursor returns `Some(0)`; `None` represents an exhausted cursor.
980#[derive(Debug, Clone)]
981pub struct ArNext {
982    key: Bytes,
983}
984
985impl ArNext {
986    /// Construct an `ARNEXT` command.
987    pub fn new(key: impl AsRef<[u8]>) -> Self {
988        Self {
989            key: owned_bytes(key),
990        }
991    }
992}
993
994impl Command for ArNext {
995    type Response = Option<u64>;
996
997    fn to_frame(&self) -> Frame {
998        array(vec![bulk("ARNEXT"), bulk(&self.key)])
999    }
1000
1001    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1002        Option::<u64>::from_frame(frame)
1003    }
1004
1005    fn name(&self) -> &str {
1006        "ARNEXT"
1007    }
1008
1009    fn idempotent(&self) -> bool {
1010        true
1011    }
1012}
1013
1014/// AROP key start end operation
1015///
1016/// Aggregates populated elements in an inclusive range. The operation enum
1017/// makes the optional `MATCH value` argument structurally valid, while
1018/// [`ArOpResult`] preserves Redis's operation-dependent reply type.
1019#[derive(Debug, Clone)]
1020pub struct ArOp {
1021    key: Bytes,
1022    start: u64,
1023    end: u64,
1024    operation: ArOpOperation,
1025}
1026
1027impl ArOp {
1028    /// Construct an `AROP` command.
1029    pub fn new(key: impl AsRef<[u8]>, start: u64, end: u64, operation: ArOpOperation) -> Self {
1030        Self {
1031            key: owned_bytes(key),
1032            start,
1033            end,
1034            operation,
1035        }
1036    }
1037}
1038
1039impl Command for ArOp {
1040    type Response = ArOpResult;
1041
1042    fn to_frame(&self) -> Frame {
1043        let mut args = vec![
1044            bulk("AROP"),
1045            bulk(&self.key),
1046            bulk(self.start.to_string()),
1047            bulk(self.end.to_string()),
1048        ];
1049        self.operation.append_to(&mut args);
1050        array(args)
1051    }
1052
1053    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1054        match &self.operation {
1055            ArOpOperation::Sum | ArOpOperation::Min | ArOpOperation::Max => {
1056                parse_optional_bytes(frame).map(ArOpResult::Value)
1057            }
1058            ArOpOperation::And | ArOpOperation::Or | ArOpOperation::Xor => {
1059                Option::<i64>::from_frame(frame).map(ArOpResult::Integer)
1060            }
1061            ArOpOperation::Match(_) | ArOpOperation::Used => {
1062                parse_i64(frame).map(|value| ArOpResult::Integer(Some(value)))
1063            }
1064        }
1065    }
1066
1067    fn name(&self) -> &str {
1068        "AROP"
1069    }
1070
1071    fn idempotent(&self) -> bool {
1072        true
1073    }
1074}
1075
1076/// ARRING key size value \[value ...\]
1077///
1078/// Inserts values into a ring window and returns the last index written.
1079/// Redis requires `size` to be positive. Requiring the first value in
1080/// [`ArRing::new`] prevents an invalid empty variadic list.
1081#[derive(Debug, Clone)]
1082pub struct ArRing {
1083    key: Bytes,
1084    size: u64,
1085    values: Vec<Bytes>,
1086}
1087
1088impl ArRing {
1089    /// Construct an `ARRING` command with its first required value.
1090    pub fn new(key: impl AsRef<[u8]>, size: u64, value: impl AsRef<[u8]>) -> Self {
1091        Self {
1092            key: owned_bytes(key),
1093            size,
1094            values: vec![owned_bytes(value)],
1095        }
1096    }
1097
1098    /// Add another value to the same ring insertion batch.
1099    pub fn value(mut self, value: impl AsRef<[u8]>) -> Self {
1100        self.values.push(owned_bytes(value));
1101        self
1102    }
1103}
1104
1105impl Command for ArRing {
1106    type Response = u64;
1107
1108    fn to_frame(&self) -> Frame {
1109        let mut args = Vec::with_capacity(3 + self.values.len());
1110        args.push(bulk("ARRING"));
1111        args.push(bulk(&self.key));
1112        args.push(bulk(self.size.to_string()));
1113        args.extend(self.values.iter().map(bulk));
1114        array(args)
1115    }
1116
1117    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1118        parse_u64(frame)
1119    }
1120
1121    fn name(&self) -> &str {
1122        "ARRING"
1123    }
1124}
1125
1126/// ARSCAN key start end \[LIMIT limit\]
1127///
1128/// Returns populated elements as nested index-value entries, skipping holes.
1129/// If `start > end`, entries are returned in descending index order.
1130#[derive(Debug, Clone)]
1131pub struct ArScan {
1132    key: Bytes,
1133    start: u64,
1134    end: u64,
1135    limit: Option<u64>,
1136}
1137
1138impl ArScan {
1139    /// Construct an `ARSCAN` command.
1140    pub fn new(key: impl AsRef<[u8]>, start: u64, end: u64) -> Self {
1141        Self {
1142            key: owned_bytes(key),
1143            start,
1144            end,
1145            limit: None,
1146        }
1147    }
1148
1149    /// Limit the number of returned entries. Redis requires a positive value.
1150    pub fn limit(mut self, limit: u64) -> Self {
1151        self.limit = Some(limit);
1152        self
1153    }
1154}
1155
1156impl Command for ArScan {
1157    type Response = Vec<ArrayEntry>;
1158
1159    fn to_frame(&self) -> Frame {
1160        let mut args = vec![
1161            bulk("ARSCAN"),
1162            bulk(&self.key),
1163            bulk(self.start.to_string()),
1164            bulk(self.end.to_string()),
1165        ];
1166        if let Some(limit) = self.limit {
1167            args.push(bulk("LIMIT"));
1168            args.push(bulk(limit.to_string()));
1169        }
1170        array(args)
1171    }
1172
1173    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1174        Vec::<ArrayEntry>::from_frame(frame)
1175    }
1176
1177    fn name(&self) -> &str {
1178        "ARSCAN"
1179    }
1180
1181    fn idempotent(&self) -> bool {
1182        true
1183    }
1184}
1185
1186/// ARSEEK key index
1187///
1188/// Sets the next index used by `ARINSERT` and `ARRING`. Returns `true` when the
1189/// cursor was updated and `false` when `key` does not exist. Unlike other array
1190/// commands, Redis permits `u64::MAX` here to create a terminal cursor.
1191#[derive(Debug, Clone)]
1192pub struct ArSeek {
1193    key: Bytes,
1194    index: u64,
1195}
1196
1197impl ArSeek {
1198    /// Construct an `ARSEEK` command.
1199    pub fn new(key: impl AsRef<[u8]>, index: u64) -> Self {
1200        Self {
1201            key: owned_bytes(key),
1202            index,
1203        }
1204    }
1205}
1206
1207impl Command for ArSeek {
1208    type Response = bool;
1209
1210    fn to_frame(&self) -> Frame {
1211        array(vec![
1212            bulk("ARSEEK"),
1213            bulk(&self.key),
1214            bulk(self.index.to_string()),
1215        ])
1216    }
1217
1218    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1219        parse_bool(frame)
1220    }
1221
1222    fn name(&self) -> &str {
1223        "ARSEEK"
1224    }
1225}
1226
1227/// ARSET key index value \[value ...\]
1228///
1229/// Sets contiguous values beginning at `index` and returns the number of
1230/// previously empty slots filled.
1231#[derive(Debug, Clone)]
1232pub struct ArSet {
1233    key: Bytes,
1234    index: u64,
1235    values: Vec<Bytes>,
1236}
1237
1238impl ArSet {
1239    /// Construct an `ARSET` command with its first required value.
1240    pub fn new(key: impl AsRef<[u8]>, index: u64, value: impl AsRef<[u8]>) -> Self {
1241        Self {
1242            key: owned_bytes(key),
1243            index,
1244            values: vec![owned_bytes(value)],
1245        }
1246    }
1247
1248    /// Add another contiguous value.
1249    pub fn value(mut self, value: impl AsRef<[u8]>) -> Self {
1250        self.values.push(owned_bytes(value));
1251        self
1252    }
1253}
1254
1255impl Command for ArSet {
1256    type Response = u64;
1257
1258    fn to_frame(&self) -> Frame {
1259        let mut args = Vec::with_capacity(3 + self.values.len());
1260        args.push(bulk("ARSET"));
1261        args.push(bulk(&self.key));
1262        args.push(bulk(self.index.to_string()));
1263        args.extend(self.values.iter().map(bulk));
1264        array(args)
1265    }
1266
1267    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1268        parse_u64(frame)
1269    }
1270
1271    fn name(&self) -> &str {
1272        "ARSET"
1273    }
1274}
1275
1276#[cfg(test)]
1277mod tests {
1278    use super::*;
1279
1280    const MAX_ARRAY_INDEX: u64 = u64::MAX - 1;
1281    const MAX_ARRAY_INDEX_TEXT: &[u8] = b"18446744073709551614";
1282
1283    fn command_args<C: Command>(command: &C) -> Vec<Bytes> {
1284        match command.to_frame() {
1285            Frame::Array(Some(items)) => items
1286                .into_iter()
1287                .map(Bytes::from_frame)
1288                .collect::<Result<_, _>>()
1289                .expect("command arguments should be bulk strings"),
1290            other => panic!("expected command array, got {other:?}"),
1291        }
1292    }
1293
1294    fn assert_args<C: Command>(command: &C, expected: &[&[u8]]) {
1295        assert_eq!(
1296            command_args(command),
1297            expected
1298                .iter()
1299                .map(|value| Bytes::copy_from_slice(value))
1300                .collect::<Vec<_>>()
1301        );
1302    }
1303
1304    fn base_info_pairs() -> Vec<(Frame, Frame)> {
1305        vec![
1306            (bulk("count"), Frame::Integer(3)),
1307            (bulk("len"), Frame::Integer(11)),
1308            (bulk("next-insert-index"), Frame::Integer(4)),
1309            (bulk("slices"), Frame::Integer(2)),
1310            (bulk("directory-size"), Frame::Integer(8)),
1311            (bulk("super-dir-entries"), Frame::Integer(0)),
1312            (bulk("slice-size"), Frame::Integer(64)),
1313        ]
1314    }
1315
1316    fn flatten_pairs(pairs: Vec<(Frame, Frame)>) -> Frame {
1317        array(
1318            pairs
1319                .into_iter()
1320                .flat_map(|(key, value)| [key, value])
1321                .collect(),
1322        )
1323    }
1324
1325    #[test]
1326    fn arcount_and_arlen_frames_and_unsigned_responses() {
1327        let count = ArCount::new("array");
1328        let len = ArLen::new("array");
1329        assert_args(&count, &[b"ARCOUNT", b"array"]);
1330        assert_args(&len, &[b"ARLEN", b"array"]);
1331        assert_eq!(count.name(), "ARCOUNT");
1332        assert_eq!(len.name(), "ARLEN");
1333
1334        assert_eq!(count.parse_response(Frame::Integer(7)).unwrap(), 7);
1335        assert_eq!(
1336            count
1337                .parse_response(Frame::BulkString(Some(Bytes::from_static(
1338                    MAX_ARRAY_INDEX_TEXT,
1339                ))))
1340                .unwrap(),
1341            MAX_ARRAY_INDEX
1342        );
1343        assert_eq!(
1344            len.parse_response(Frame::BigNumber(Bytes::from_static(MAX_ARRAY_INDEX_TEXT,)))
1345                .unwrap(),
1346            MAX_ARRAY_INDEX
1347        );
1348        assert!(count.parse_response(Frame::Integer(-1)).is_err());
1349    }
1350
1351    #[test]
1352    fn ardel_builds_nonempty_index_list() {
1353        let command = ArDel::new("array", 1).index(MAX_ARRAY_INDEX);
1354        assert_args(&command, &[b"ARDEL", b"array", b"1", MAX_ARRAY_INDEX_TEXT]);
1355        assert_eq!(command.name(), "ARDEL");
1356        assert_eq!(command.parse_response(Frame::Integer(2)).unwrap(), 2);
1357        assert!(!command.idempotent());
1358    }
1359
1360    #[test]
1361    fn ardelrange_builds_complete_range_pairs() {
1362        let command = ArDelRange::new("array", 9, 3).range(20, 25);
1363        assert_args(
1364            &command,
1365            &[b"ARDELRANGE", b"array", b"9", b"3", b"20", b"25"],
1366        );
1367        assert_eq!(command.name(), "ARDELRANGE");
1368        assert_eq!(
1369            command
1370                .parse_response(Frame::BulkString(Some(Bytes::from_static(b"4"))))
1371                .unwrap(),
1372            4
1373        );
1374    }
1375
1376    #[test]
1377    fn arget_is_binary_safe_and_normalizes_resp2_and_resp3_nulls() {
1378        let key = String::from("array");
1379        let command = ArGet::new(&key, 4);
1380        assert_args(&command, &[b"ARGET", b"array", b"4"]);
1381        let value = Bytes::from_static(b"\0binary\xff");
1382        assert_eq!(
1383            command
1384                .parse_response(Frame::BulkString(Some(value.clone())))
1385                .unwrap(),
1386            Some(value)
1387        );
1388        assert_eq!(
1389            command.parse_response(Frame::BulkString(None)).unwrap(),
1390            None
1391        );
1392        assert_eq!(command.parse_response(Frame::Null).unwrap(), None);
1393        assert!(command.idempotent());
1394    }
1395
1396    #[test]
1397    fn argetrange_preserves_holes() {
1398        let command = ArGetRange::new("array", 5, 2);
1399        assert_args(&command, &[b"ARGETRANGE", b"array", b"5", b"2"]);
1400        let response = array(vec![
1401            bulk("five"),
1402            Frame::BulkString(None),
1403            Frame::Null,
1404            bulk("two"),
1405        ]);
1406        assert_eq!(
1407            command.parse_response(response).unwrap(),
1408            vec![
1409                Some(Bytes::from_static(b"five")),
1410                None,
1411                None,
1412                Some(Bytes::from_static(b"two")),
1413            ]
1414        );
1415        assert!(command.idempotent());
1416    }
1417
1418    #[test]
1419    fn argrep_builds_all_predicates_bounds_and_options() {
1420        let command = ArGrep::new(
1421            "array",
1422            ArGrepBound::Start,
1423            ArGrepBound::End,
1424            ArGrepPredicate::exact("one"),
1425        )
1426        .predicate(ArGrepPredicate::matches("on"))
1427        .predicate(ArGrepPredicate::glob("o*"))
1428        .predicate(ArGrepPredicate::regex("^o"))
1429        .and()
1430        .limit(2)
1431        .nocase();
1432        assert_args(
1433            &command,
1434            &[
1435                b"ARGREP", b"array", b"-", b"+", b"EXACT", b"one", b"MATCH", b"on", b"GLOB", b"o*",
1436                b"RE", b"^o", b"AND", b"LIMIT", b"2", b"NOCASE",
1437            ],
1438        );
1439        assert_eq!(command.name(), "ARGREP");
1440        assert_eq!(
1441            command
1442                .parse_response(array(vec![
1443                    Frame::Integer(1),
1444                    Frame::BigNumber(Bytes::from_static(MAX_ARRAY_INDEX_TEXT)),
1445                ]))
1446                .unwrap(),
1447            ArGrepResult::Indices(vec![1, MAX_ARRAY_INDEX])
1448        );
1449        assert!(command.idempotent());
1450    }
1451
1452    #[test]
1453    fn argrep_with_values_parses_nested_binary_entries() {
1454        let binary = Bytes::from_static(b"\0value\xff");
1455        let command = ArGrep::new(
1456            "array",
1457            0,
1458            MAX_ARRAY_INDEX,
1459            ArGrepPredicate::matches(binary.clone()),
1460        )
1461        .or()
1462        .with_values();
1463        assert_args(
1464            &command,
1465            &[
1466                b"ARGREP",
1467                b"array",
1468                b"0",
1469                MAX_ARRAY_INDEX_TEXT,
1470                b"MATCH",
1471                b"\0value\xff",
1472                b"OR",
1473                b"WITHVALUES",
1474            ],
1475        );
1476        let response = array(vec![array(vec![
1477            Frame::BulkString(Some(Bytes::from_static(MAX_ARRAY_INDEX_TEXT))),
1478            Frame::BulkString(Some(binary.clone())),
1479        ])]);
1480        assert_eq!(
1481            command.parse_response(response).unwrap(),
1482            ArGrepResult::Entries(vec![ArrayEntry {
1483                index: MAX_ARRAY_INDEX,
1484                value: binary,
1485            }])
1486        );
1487        assert!(
1488            command
1489                .parse_response(array(vec![Frame::Integer(1), bulk("value")]))
1490                .is_err()
1491        );
1492    }
1493
1494    #[test]
1495    fn arinfo_parses_resp2_base_fields() {
1496        let command = ArInfo::new("array");
1497        assert_args(&command, &[b"ARINFO", b"array"]);
1498        let info = command
1499            .parse_response(flatten_pairs(base_info_pairs()))
1500            .unwrap();
1501        assert_eq!(
1502            info,
1503            ArInfoResponse {
1504                count: 3,
1505                len: 11,
1506                next_insert_index: 4,
1507                slices: 2,
1508                directory_size: 8,
1509                super_directory_entries: 0,
1510                slice_size: 64,
1511                full: None,
1512            }
1513        );
1514        assert!(command.idempotent());
1515    }
1516
1517    #[test]
1518    fn arinfo_parses_resp3_full_fields_and_resp2_doubles() {
1519        let command = ArInfo::new("array").full();
1520        assert_args(&command, &[b"ARINFO", b"array", b"FULL"]);
1521        let mut pairs = base_info_pairs();
1522        pairs.extend([
1523            (bulk("dense-slices"), Frame::Integer(1)),
1524            (bulk("sparse-slices"), Frame::Integer(1)),
1525            (bulk("avg-dense-size"), Frame::Double(32.0)),
1526            (
1527                bulk("avg-dense-fill"),
1528                Frame::BulkString(Some(Bytes::from_static(b"0.75"))),
1529            ),
1530            (bulk("avg-sparse-size"), Frame::Double(8.5)),
1531        ]);
1532        let info = command.parse_response(Frame::Map(pairs)).unwrap();
1533        assert_eq!(
1534            info.full,
1535            Some(ArInfoFull {
1536                dense_slices: 1,
1537                sparse_slices: 1,
1538                average_dense_size: 32.0,
1539                average_dense_fill: 0.75,
1540                average_sparse_size: 8.5,
1541            })
1542        );
1543
1544        let mut resp2_pairs = base_info_pairs();
1545        resp2_pairs.extend([
1546            (bulk("dense-slices"), Frame::Integer(0)),
1547            (bulk("sparse-slices"), Frame::Integer(2)),
1548            (bulk("avg-dense-size"), bulk("0")),
1549            (bulk("avg-dense-fill"), bulk("0")),
1550            (bulk("avg-sparse-size"), bulk("4.25")),
1551        ]);
1552        let resp2 = command.parse_response(flatten_pairs(resp2_pairs)).unwrap();
1553        assert_eq!(resp2.full.unwrap().average_sparse_size, 4.25);
1554    }
1555
1556    #[test]
1557    fn arinfo_rejects_malformed_or_incomplete_maps() {
1558        let command = ArInfo::new("array");
1559        assert!(command.parse_response(array(vec![bulk("count")])).is_err());
1560        assert!(
1561            command
1562                .parse_response(Frame::Map(vec![(bulk("count"), Frame::Integer(1))]))
1563                .is_err()
1564        );
1565        assert!(
1566            ArInfo::new("array")
1567                .full()
1568                .parse_response(Frame::Map(base_info_pairs()))
1569                .is_err()
1570        );
1571    }
1572
1573    #[test]
1574    fn arinsert_builds_binary_batch_and_parses_high_index() {
1575        let command = ArInsert::new("array", b"first".as_slice()).value([0, 255]);
1576        assert_args(&command, &[b"ARINSERT", b"array", b"first", b"\0\xff"]);
1577        assert_eq!(command.name(), "ARINSERT");
1578        assert_eq!(
1579            command
1580                .parse_response(Frame::BigNumber(Bytes::from_static(MAX_ARRAY_INDEX_TEXT,)))
1581                .unwrap(),
1582            MAX_ARRAY_INDEX
1583        );
1584    }
1585
1586    #[test]
1587    fn arlastitems_builds_rev_and_preserves_holes() {
1588        let command = ArLastItems::new("array", 3).rev();
1589        assert_args(&command, &[b"ARLASTITEMS", b"array", b"3", b"REV"]);
1590        assert_eq!(
1591            command
1592                .parse_response(array(vec![bulk("new"), Frame::Null, bulk("old")]))
1593                .unwrap(),
1594            vec![
1595                Some(Bytes::from_static(b"new")),
1596                None,
1597                Some(Bytes::from_static(b"old")),
1598            ]
1599        );
1600        assert!(command.idempotent());
1601    }
1602
1603    #[test]
1604    fn armget_builds_indices_and_preserves_nulls() {
1605        let command = ArMGet::new("array", 0).index(8);
1606        assert_args(&command, &[b"ARMGET", b"array", b"0", b"8"]);
1607        assert_eq!(
1608            command
1609                .parse_response(array(vec![bulk("zero"), Frame::BulkString(None)]))
1610                .unwrap(),
1611            vec![Some(Bytes::from_static(b"zero")), None]
1612        );
1613        assert!(command.idempotent());
1614    }
1615
1616    #[test]
1617    fn armset_builds_binary_pairs() {
1618        let dynamic_key = String::from("array");
1619        let command = ArMSet::new(&dynamic_key, 0, "zero").pair(8, [0, 255]);
1620        assert_args(
1621            &command,
1622            &[b"ARMSET", b"array", b"0", b"zero", b"8", b"\0\xff"],
1623        );
1624        assert_eq!(command.name(), "ARMSET");
1625        assert_eq!(command.parse_response(Frame::Integer(2)).unwrap(), 2);
1626    }
1627
1628    #[test]
1629    fn arnext_distinguishes_zero_terminal_null_and_high_index() {
1630        let command = ArNext::new("array");
1631        assert_args(&command, &[b"ARNEXT", b"array"]);
1632        assert_eq!(command.parse_response(Frame::Integer(0)).unwrap(), Some(0));
1633        assert_eq!(
1634            command.parse_response(Frame::BulkString(None)).unwrap(),
1635            None
1636        );
1637        assert_eq!(command.parse_response(Frame::Null).unwrap(), None);
1638        assert_eq!(
1639            command
1640                .parse_response(Frame::BigNumber(Bytes::from_static(MAX_ARRAY_INDEX_TEXT,)))
1641                .unwrap(),
1642            Some(MAX_ARRAY_INDEX)
1643        );
1644        assert!(command.idempotent());
1645    }
1646
1647    #[test]
1648    fn arop_builds_every_operation_variant() {
1649        let operations = [
1650            (ArOpOperation::Sum, b"SUM".as_slice()),
1651            (ArOpOperation::Min, b"MIN".as_slice()),
1652            (ArOpOperation::Max, b"MAX".as_slice()),
1653            (ArOpOperation::And, b"AND".as_slice()),
1654            (ArOpOperation::Or, b"OR".as_slice()),
1655            (ArOpOperation::Xor, b"XOR".as_slice()),
1656            (ArOpOperation::Used, b"USED".as_slice()),
1657        ];
1658        for (operation, token) in operations {
1659            let command = ArOp::new("array", 1, 9, operation);
1660            assert_args(&command, &[b"AROP", b"array", b"1", b"9", token]);
1661            assert_eq!(command.name(), "AROP");
1662        }
1663        let match_command = ArOp::new(
1664            "array",
1665            1,
1666            9,
1667            ArOpOperation::matches(Bytes::from_static(b"\0\xff")),
1668        );
1669        assert_args(
1670            &match_command,
1671            &[b"AROP", b"array", b"1", b"9", b"MATCH", b"\0\xff"],
1672        );
1673    }
1674
1675    #[test]
1676    fn arop_parses_value_integer_and_null_branches() {
1677        let sum = ArOp::new("array", 0, 9, ArOpOperation::Sum);
1678        assert_eq!(
1679            sum.parse_response(bulk("12.5")).unwrap(),
1680            ArOpResult::Value(Some(Bytes::from_static(b"12.5")))
1681        );
1682        assert_eq!(
1683            sum.parse_response(Frame::Null).unwrap(),
1684            ArOpResult::Value(None)
1685        );
1686
1687        let and = ArOp::new("array", 0, 9, ArOpOperation::And);
1688        assert_eq!(
1689            and.parse_response(Frame::Integer(-4)).unwrap(),
1690            ArOpResult::Integer(Some(-4))
1691        );
1692        assert_eq!(
1693            and.parse_response(Frame::BulkString(None)).unwrap(),
1694            ArOpResult::Integer(None)
1695        );
1696
1697        let used = ArOp::new("array", 0, 9, ArOpOperation::Used);
1698        assert_eq!(
1699            used.parse_response(Frame::Integer(3)).unwrap(),
1700            ArOpResult::Integer(Some(3))
1701        );
1702        assert!(used.parse_response(Frame::Null).is_err());
1703        assert!(used.idempotent());
1704    }
1705
1706    #[test]
1707    fn arring_builds_nonempty_batch() {
1708        let command = ArRing::new("ring", 3, "one").value("two");
1709        assert_args(&command, &[b"ARRING", b"ring", b"3", b"one", b"two"]);
1710        assert_eq!(command.name(), "ARRING");
1711        assert_eq!(command.parse_response(Frame::Integer(1)).unwrap(), 1);
1712        assert!(!command.idempotent());
1713    }
1714
1715    #[test]
1716    fn arscan_builds_limit_and_parses_nested_entries() {
1717        let command = ArScan::new("array", 9, 0).limit(2);
1718        assert_args(&command, &[b"ARSCAN", b"array", b"9", b"0", b"LIMIT", b"2"]);
1719        let binary = Bytes::from_static(b"\0\xff");
1720        let response = array(vec![
1721            array(vec![Frame::Integer(9), bulk("nine")]),
1722            array(vec![
1723                Frame::BigNumber(Bytes::from_static(MAX_ARRAY_INDEX_TEXT)),
1724                Frame::BulkString(Some(binary.clone())),
1725            ]),
1726        ]);
1727        assert_eq!(
1728            command.parse_response(response).unwrap(),
1729            vec![
1730                ArrayEntry {
1731                    index: 9,
1732                    value: Bytes::from_static(b"nine"),
1733                },
1734                ArrayEntry {
1735                    index: MAX_ARRAY_INDEX,
1736                    value: binary,
1737                },
1738            ]
1739        );
1740        assert!(
1741            command
1742                .parse_response(array(vec![Frame::Integer(1), bulk("flat")]))
1743                .is_err()
1744        );
1745        assert!(command.idempotent());
1746    }
1747
1748    #[test]
1749    fn arseek_accepts_terminal_index_and_boolean_protocol_forms() {
1750        let command = ArSeek::new("array", u64::MAX);
1751        assert_args(&command, &[b"ARSEEK", b"array", b"18446744073709551615"]);
1752        assert_eq!(command.name(), "ARSEEK");
1753        assert!(command.parse_response(Frame::Integer(1)).unwrap());
1754        assert!(!command.parse_response(Frame::Boolean(false)).unwrap());
1755        assert!(command.parse_response(Frame::Integer(2)).is_err());
1756    }
1757
1758    #[test]
1759    fn arset_builds_contiguous_binary_values() {
1760        let command = ArSet::new("array", 4, "four").value([0, 255]);
1761        assert_args(&command, &[b"ARSET", b"array", b"4", b"four", b"\0\xff"]);
1762        assert_eq!(command.name(), "ARSET");
1763        assert_eq!(command.parse_response(Frame::Integer(2)).unwrap(), 2);
1764        assert!(!command.idempotent());
1765    }
1766
1767    #[test]
1768    fn exactly_the_read_commands_are_idempotent() {
1769        assert!(ArCount::new("k").idempotent());
1770        assert!(ArGet::new("k", 0).idempotent());
1771        assert!(ArGetRange::new("k", 0, 1).idempotent());
1772        assert!(ArGrep::new("k", 0, 1, ArGrepPredicate::exact("v")).idempotent());
1773        assert!(ArInfo::new("k").idempotent());
1774        assert!(ArLastItems::new("k", 1).idempotent());
1775        assert!(ArLen::new("k").idempotent());
1776        assert!(ArMGet::new("k", 0).idempotent());
1777        assert!(ArNext::new("k").idempotent());
1778        assert!(ArOp::new("k", 0, 1, ArOpOperation::Used).idempotent());
1779        assert!(ArScan::new("k", 0, 1).idempotent());
1780
1781        assert!(!ArDel::new("k", 0).idempotent());
1782        assert!(!ArDelRange::new("k", 0, 1).idempotent());
1783        assert!(!ArInsert::new("k", "v").idempotent());
1784        assert!(!ArMSet::new("k", 0, "v").idempotent());
1785        assert!(!ArRing::new("k", 1, "v").idempotent());
1786        assert!(!ArSeek::new("k", 0).idempotent());
1787        assert!(!ArSet::new("k", 0, "v").idempotent());
1788    }
1789}