Skip to main content

redis_tower_commands/
bitmap.rs

1//! Bit-level operations over Redis string values.
2//!
3//! Use [`SetBit`] and [`GetBit`] for individual flags, [`BitCount`] for
4//! population counts, and [`BitOp`] / [`Bitfield`] for bulk operations. Offset
5//! and count replies are integers; bit reads are normalized to their typed
6//! command response.
7//!
8//! ```
9//! use redis_tower_commands::{GetBit, SetBit};
10//! use redis_tower_core::Command;
11//!
12//! let set = SetBit::new("daily:active", 42, 1);
13//! let get = GetBit::new("daily:active", 42);
14//! assert_eq!((set.name(), get.name()), ("SETBIT", "GETBIT"));
15//! ```
16//!
17//! See the [command cookbook] for binary key handling and response shapes.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#binary-keys-and-values
20
21use crate::CommandArg;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25/// SETBIT key offset value
26///
27/// Sets or clears the bit at `offset` in the string value stored at `key`.
28/// Returns the original bit value stored at `offset`.
29#[derive(Clone)]
30pub struct SetBit {
31    key: CommandArg,
32    offset: u64,
33    value: u8,
34}
35
36impl SetBit {
37    /// Create a new [`SetBit`] command.
38    pub fn new(key: impl Into<CommandArg>, offset: u64, value: u8) -> Self {
39        Self {
40            key: key.into(),
41            offset,
42            value,
43        }
44    }
45}
46
47impl Command for SetBit {
48    type Response = i64;
49
50    fn to_frame(&self) -> Frame {
51        array(vec![
52            bulk("SETBIT"),
53            bulk(&self.key),
54            bulk(self.offset.to_string()),
55            bulk(self.value.to_string()),
56        ])
57    }
58
59    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
60        match frame {
61            Frame::Integer(n) => Ok(n),
62            other => Err(RedisError::UnexpectedResponse {
63                expected: "integer",
64                actual: format!("{other:?}"),
65            }),
66        }
67    }
68
69    fn name(&self) -> &str {
70        "SETBIT"
71    }
72}
73
74/// GETBIT key offset
75///
76/// Returns the bit value at `offset` in the string value stored at `key`.
77#[derive(Clone)]
78pub struct GetBit {
79    key: CommandArg,
80    offset: u64,
81}
82
83impl GetBit {
84    /// Create a new [`GetBit`] command.
85    pub fn new(key: impl Into<CommandArg>, offset: u64) -> Self {
86        Self {
87            key: key.into(),
88            offset,
89        }
90    }
91}
92
93impl Command for GetBit {
94    type Response = i64;
95
96    fn to_frame(&self) -> Frame {
97        array(vec![
98            bulk("GETBIT"),
99            bulk(&self.key),
100            bulk(self.offset.to_string()),
101        ])
102    }
103
104    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
105        match frame {
106            Frame::Integer(n) => Ok(n),
107            other => Err(RedisError::UnexpectedResponse {
108                expected: "integer",
109                actual: format!("{other:?}"),
110            }),
111        }
112    }
113
114    fn name(&self) -> &str {
115        "GETBIT"
116    }
117}
118
119/// BITCOUNT key \[start end \[BYTE|BIT\]\]
120///
121/// Counts the number of set bits (population counting) in a string.
122/// By default counts all bytes; use `.range()` to limit and `.bit_mode()`
123/// to interpret the range as bit offsets instead of byte offsets.
124#[derive(Clone)]
125pub struct BitCount {
126    key: CommandArg,
127    range: Option<(i64, i64)>,
128    bit_mode: bool,
129}
130
131impl BitCount {
132    /// Create a new [`BitCount`] command.
133    pub fn new(key: impl Into<CommandArg>) -> Self {
134        Self {
135            key: key.into(),
136            range: None,
137            bit_mode: false,
138        }
139    }
140
141    /// Limit the count to the byte range `[start, end]`.
142    pub fn range(mut self, start: i64, end: i64) -> Self {
143        self.range = Some((start, end));
144        self
145    }
146
147    /// Interpret the range as bit offsets instead of byte offsets.
148    pub fn bit_mode(mut self) -> Self {
149        self.bit_mode = true;
150        self
151    }
152}
153
154impl Command for BitCount {
155    type Response = i64;
156
157    fn to_frame(&self) -> Frame {
158        let mut args = vec![bulk("BITCOUNT"), bulk(&self.key)];
159        if let Some((start, end)) = self.range {
160            args.push(bulk(start.to_string()));
161            args.push(bulk(end.to_string()));
162            if self.bit_mode {
163                args.push(bulk("BIT"));
164            }
165        }
166        array(args)
167    }
168
169    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
170        match frame {
171            Frame::Integer(n) => Ok(n),
172            other => Err(RedisError::UnexpectedResponse {
173                expected: "integer",
174                actual: format!("{other:?}"),
175            }),
176        }
177    }
178
179    fn name(&self) -> &str {
180        "BITCOUNT"
181    }
182}
183
184/// BITPOS key bit \[start \[end \[BYTE|BIT\]\]\]
185///
186/// Returns the position of the first bit set to `bit` (0 or 1) in the string
187/// stored at `key`. Use `.range()` to limit the search and `.bit_mode()` to
188/// interpret the range as bit offsets instead of byte offsets.
189#[derive(Clone)]
190pub struct BitPos {
191    key: CommandArg,
192    bit: u8,
193    range: Option<(i64, i64)>,
194    bit_mode: bool,
195}
196
197impl BitPos {
198    /// Create a new [`BitPos`] command.
199    pub fn new(key: impl Into<CommandArg>, bit: u8) -> Self {
200        Self {
201            key: key.into(),
202            bit,
203            range: None,
204            bit_mode: false,
205        }
206    }
207
208    /// Limit the search to the byte range `[start, end]`.
209    pub fn range(mut self, start: i64, end: i64) -> Self {
210        self.range = Some((start, end));
211        self
212    }
213
214    /// Interpret the range as bit offsets instead of byte offsets.
215    pub fn bit_mode(mut self) -> Self {
216        self.bit_mode = true;
217        self
218    }
219}
220
221impl Command for BitPos {
222    type Response = i64;
223
224    fn to_frame(&self) -> Frame {
225        let mut args = vec![bulk("BITPOS"), bulk(&self.key), bulk(self.bit.to_string())];
226        if let Some((start, end)) = self.range {
227            args.push(bulk(start.to_string()));
228            args.push(bulk(end.to_string()));
229            if self.bit_mode {
230                args.push(bulk("BIT"));
231            }
232        }
233        array(args)
234    }
235
236    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
237        match frame {
238            Frame::Integer(n) => Ok(n),
239            other => Err(RedisError::UnexpectedResponse {
240                expected: "integer",
241                actual: format!("{other:?}"),
242            }),
243        }
244    }
245
246    fn name(&self) -> &str {
247        "BITPOS"
248    }
249}
250
251/// Bitwise operation for BITOP.
252#[derive(Clone)]
253pub enum BitOperation {
254    /// Bitwise AND.
255    And,
256    /// Bitwise OR.
257    Or,
258    /// Bitwise XOR.
259    Xor,
260    /// Bitwise NOT (single source key only).
261    Not,
262}
263
264impl BitOperation {
265    fn as_str(&self) -> &str {
266        match self {
267            BitOperation::And => "AND",
268            BitOperation::Or => "OR",
269            BitOperation::Xor => "XOR",
270            BitOperation::Not => "NOT",
271        }
272    }
273}
274
275/// BITOP AND|OR|XOR|NOT destkey key \[key ...\]
276///
277/// Performs a bitwise operation between strings and stores the result in `destkey`.
278/// Returns the size of the string stored in the destination key (the longest
279/// input string length).
280#[derive(Clone)]
281pub struct BitOp {
282    operation: BitOperation,
283    destkey: CommandArg,
284    keys: Vec<CommandArg>,
285}
286
287impl BitOp {
288    /// Create a new [`BitOp`] command.
289    pub fn new(
290        operation: BitOperation,
291        destkey: impl Into<CommandArg>,
292        keys: impl IntoIterator<Item = impl Into<CommandArg>>,
293    ) -> Self {
294        Self {
295            operation,
296            destkey: destkey.into(),
297            keys: keys.into_iter().map(Into::into).collect(),
298        }
299    }
300}
301
302impl Command for BitOp {
303    type Response = i64;
304
305    fn to_frame(&self) -> Frame {
306        let mut args = vec![
307            bulk("BITOP"),
308            bulk(self.operation.as_str()),
309            bulk(&self.destkey),
310        ];
311        for key in &self.keys {
312            args.push(bulk(key));
313        }
314        array(args)
315    }
316
317    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
318        match frame {
319            Frame::Integer(n) => Ok(n),
320            other => Err(RedisError::UnexpectedResponse {
321                expected: "integer",
322                actual: format!("{other:?}"),
323            }),
324        }
325    }
326
327    fn name(&self) -> &str {
328        "BITOP"
329    }
330}
331
332/// OVERFLOW behavior for `BITFIELD` `INCRBY`/`SET` operations.
333///
334/// Controls how the server handles overflow on signed/unsigned integers:
335/// - `Wrap` -- wrap around (the default for both signed and unsigned).
336/// - `Sat` -- saturate at the min/max value of the field type.
337/// - `Fail` -- do not perform the operation and return nil for that sub-command.
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum BitfieldOverflow {
340    /// Wrap around on overflow.
341    Wrap,
342    /// Saturate at the type's min/max on overflow.
343    Sat,
344    /// Fail (return nil) on overflow.
345    Fail,
346}
347
348impl BitfieldOverflow {
349    fn as_str(&self) -> &str {
350        match self {
351            BitfieldOverflow::Wrap => "WRAP",
352            BitfieldOverflow::Sat => "SAT",
353            BitfieldOverflow::Fail => "FAIL",
354        }
355    }
356}
357
358/// A single sub-operation within a `BITFIELD` command.
359#[derive(Clone)]
360enum BitfieldOp {
361    Get {
362        encoding: String,
363        offset: String,
364    },
365    Set {
366        encoding: String,
367        offset: String,
368        value: i64,
369    },
370    IncrBy {
371        encoding: String,
372        offset: String,
373        increment: i64,
374    },
375    Overflow(BitfieldOverflow),
376}
377
378/// BITFIELD key \[GET enc offset\] \[SET enc offset value\]
379/// \[INCRBY enc offset increment\] \[OVERFLOW WRAP|SAT|FAIL\] ...
380///
381/// Performs a series of arbitrary-width integer operations on the string stored
382/// at `key`, treating it as an array of packed bit fields. Sub-operations are
383/// applied in the order they are added. Each `GET`, `SET`, and `INCRBY` produces
384/// one entry in the response array; `OVERFLOW` produces no entry and instead
385/// controls the behavior of subsequent `INCRBY`/`SET` ops.
386///
387/// Returns one `Option<i64>` per `GET`/`SET`/`INCRBY`. The value is `None` only
388/// when a preceding `OVERFLOW FAIL` caused that operation to be skipped.
389///
390/// # Example
391///
392/// ```no_run
393/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
394/// use redis_tower_commands::{Bitfield, BitfieldOverflow};
395/// use redis_tower_core::RedisConnection;
396///
397/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
398///
399/// let results = conn
400///     .execute(
401///         Bitfield::new("mykey")
402///             .set("u8", "0", 255)
403///             .overflow(BitfieldOverflow::Sat)
404///             .incr_by("u8", "0", 10),
405///     )
406///     .await?;
407/// # let _ = results;
408/// # Ok(())
409/// # }
410/// ```
411#[derive(Clone)]
412pub struct Bitfield {
413    key: CommandArg,
414    ops: Vec<BitfieldOp>,
415}
416
417impl Bitfield {
418    /// Create a new `BITFIELD` command targeting `key`.
419    pub fn new(key: impl Into<CommandArg>) -> Self {
420        Self {
421            key: key.into(),
422            ops: Vec::new(),
423        }
424    }
425
426    /// Add a `GET` sub-operation.
427    ///
428    /// `encoding` is a type like `"u8"` or `"i16"`; `offset` is either an
429    /// absolute bit offset like `"0"` or a type-relative offset like `"#2"`.
430    pub fn get(mut self, encoding: impl Into<String>, offset: impl Into<String>) -> Self {
431        self.ops.push(BitfieldOp::Get {
432            encoding: encoding.into(),
433            offset: offset.into(),
434        });
435        self
436    }
437
438    /// Add a `SET` sub-operation that writes `value` and returns the old value.
439    pub fn set(
440        mut self,
441        encoding: impl Into<String>,
442        offset: impl Into<String>,
443        value: i64,
444    ) -> Self {
445        self.ops.push(BitfieldOp::Set {
446            encoding: encoding.into(),
447            offset: offset.into(),
448            value,
449        });
450        self
451    }
452
453    /// Add an `INCRBY` sub-operation and return the new value.
454    pub fn incr_by(
455        mut self,
456        encoding: impl Into<String>,
457        offset: impl Into<String>,
458        increment: i64,
459    ) -> Self {
460        self.ops.push(BitfieldOp::IncrBy {
461            encoding: encoding.into(),
462            offset: offset.into(),
463            increment,
464        });
465        self
466    }
467
468    /// Set the overflow behavior for subsequent `INCRBY`/`SET` operations.
469    pub fn overflow(mut self, overflow: BitfieldOverflow) -> Self {
470        self.ops.push(BitfieldOp::Overflow(overflow));
471        self
472    }
473}
474
475/// Parse a `BITFIELD`/`BITFIELD_RO` response array into one entry per op.
476fn parse_bitfield_response(frame: Frame) -> Result<Vec<Option<i64>>, RedisError> {
477    match frame {
478        Frame::Array(Some(frames)) => frames
479            .into_iter()
480            .map(|f| match f {
481                Frame::Integer(n) => Ok(Some(n)),
482                Frame::Null => Ok(None),
483                Frame::BulkString(None) => Ok(None),
484                Frame::Array(None) => Ok(None),
485                other => Err(RedisError::UnexpectedResponse {
486                    expected: "integer or nil",
487                    actual: format!("{other:?}"),
488                }),
489            })
490            .collect(),
491        other => Err(RedisError::UnexpectedResponse {
492            expected: "array",
493            actual: format!("{other:?}"),
494        }),
495    }
496}
497
498impl Command for Bitfield {
499    type Response = Vec<Option<i64>>;
500
501    fn to_frame(&self) -> Frame {
502        let mut args = vec![bulk("BITFIELD"), bulk(&self.key)];
503        for op in &self.ops {
504            match op {
505                BitfieldOp::Get { encoding, offset } => {
506                    args.push(bulk("GET"));
507                    args.push(bulk(encoding.as_str()));
508                    args.push(bulk(offset.as_str()));
509                }
510                BitfieldOp::Set {
511                    encoding,
512                    offset,
513                    value,
514                } => {
515                    args.push(bulk("SET"));
516                    args.push(bulk(encoding.as_str()));
517                    args.push(bulk(offset.as_str()));
518                    args.push(bulk(value.to_string()));
519                }
520                BitfieldOp::IncrBy {
521                    encoding,
522                    offset,
523                    increment,
524                } => {
525                    args.push(bulk("INCRBY"));
526                    args.push(bulk(encoding.as_str()));
527                    args.push(bulk(offset.as_str()));
528                    args.push(bulk(increment.to_string()));
529                }
530                BitfieldOp::Overflow(overflow) => {
531                    args.push(bulk("OVERFLOW"));
532                    args.push(bulk(overflow.as_str()));
533                }
534            }
535        }
536        array(args)
537    }
538
539    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
540        parse_bitfield_response(frame)
541    }
542
543    fn name(&self) -> &str {
544        "BITFIELD"
545    }
546}
547
548/// BITFIELD_RO key GET enc offset \[GET enc offset ...\]
549///
550/// The read-only variant of `BITFIELD`. Supports only `GET` sub-operations,
551/// which makes it safe to run on replicas. Returns one `Option<i64>` per `GET`.
552///
553/// # Example
554///
555/// ```no_run
556/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
557/// use redis_tower_commands::BitfieldRo;
558/// use redis_tower_core::RedisConnection;
559///
560/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
561///
562/// let values = conn
563///     .execute(BitfieldRo::new("mykey").get("u8", "0").get("u8", "8"))
564///     .await?;
565/// # let _ = values;
566/// # Ok(())
567/// # }
568/// ```
569#[derive(Clone)]
570pub struct BitfieldRo {
571    key: CommandArg,
572    gets: Vec<(String, String)>,
573}
574
575impl BitfieldRo {
576    /// Create a new `BITFIELD_RO` command targeting `key`.
577    pub fn new(key: impl Into<CommandArg>) -> Self {
578        Self {
579            key: key.into(),
580            gets: Vec::new(),
581        }
582    }
583
584    /// Add a `GET` sub-operation.
585    ///
586    /// `encoding` is a type like `"u8"` or `"i16"`; `offset` is either an
587    /// absolute bit offset like `"0"` or a type-relative offset like `"#2"`.
588    pub fn get(mut self, encoding: impl Into<String>, offset: impl Into<String>) -> Self {
589        self.gets.push((encoding.into(), offset.into()));
590        self
591    }
592}
593
594impl Command for BitfieldRo {
595    type Response = Vec<Option<i64>>;
596
597    fn to_frame(&self) -> Frame {
598        let mut args = vec![bulk("BITFIELD_RO"), bulk(&self.key)];
599        for (encoding, offset) in &self.gets {
600            args.push(bulk("GET"));
601            args.push(bulk(encoding.as_str()));
602            args.push(bulk(offset.as_str()));
603        }
604        array(args)
605    }
606
607    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
608        parse_bitfield_response(frame)
609    }
610
611    fn name(&self) -> &str {
612        "BITFIELD_RO"
613    }
614
615    fn idempotent(&self) -> bool {
616        true
617    }
618}
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use redis_tower_core::Command;
624    use redis_tower_protocol::Frame;
625    use redis_tower_protocol::helpers::{array, bulk};
626
627    #[test]
628    fn bitfield_get_set_incrby_overflow_to_frame() {
629        let cmd = Bitfield::new("mykey")
630            .get("u8", "0")
631            .set("u8", "0", 255)
632            .overflow(BitfieldOverflow::Sat)
633            .incr_by("u8", "0", 10);
634        assert_eq!(
635            cmd.to_frame(),
636            array(vec![
637                bulk("BITFIELD"),
638                bulk("mykey"),
639                bulk("GET"),
640                bulk("u8"),
641                bulk("0"),
642                bulk("SET"),
643                bulk("u8"),
644                bulk("0"),
645                bulk("255"),
646                bulk("OVERFLOW"),
647                bulk("SAT"),
648                bulk("INCRBY"),
649                bulk("u8"),
650                bulk("0"),
651                bulk("10"),
652            ])
653        );
654    }
655
656    #[test]
657    fn bitfield_overflow_fail_to_frame() {
658        let cmd = Bitfield::new("k")
659            .overflow(BitfieldOverflow::Fail)
660            .incr_by("u8", "#0", 1);
661        assert_eq!(
662            cmd.to_frame(),
663            array(vec![
664                bulk("BITFIELD"),
665                bulk("k"),
666                bulk("OVERFLOW"),
667                bulk("FAIL"),
668                bulk("INCRBY"),
669                bulk("u8"),
670                bulk("#0"),
671                bulk("1"),
672            ])
673        );
674    }
675
676    #[test]
677    fn bitfield_parses_integer_and_nil() {
678        let cmd = Bitfield::new("k");
679        let frame = Frame::Array(Some(vec![Frame::Integer(7), Frame::Null]));
680        assert_eq!(cmd.parse_response(frame).unwrap(), vec![Some(7), None]);
681    }
682
683    #[test]
684    fn bitfield_not_idempotent() {
685        assert!(!Bitfield::new("k").idempotent());
686    }
687
688    #[test]
689    fn bitfield_ro_two_gets_to_frame() {
690        let cmd = BitfieldRo::new("mykey").get("u8", "0").get("i16", "#1");
691        assert_eq!(
692            cmd.to_frame(),
693            array(vec![
694                bulk("BITFIELD_RO"),
695                bulk("mykey"),
696                bulk("GET"),
697                bulk("u8"),
698                bulk("0"),
699                bulk("GET"),
700                bulk("i16"),
701                bulk("#1"),
702            ])
703        );
704    }
705
706    #[test]
707    fn bitfield_ro_is_idempotent() {
708        assert!(BitfieldRo::new("k").get("u8", "0").idempotent());
709    }
710}