1use crate::CommandArg;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25#[derive(Clone)]
30pub struct SetBit {
31 key: CommandArg,
32 offset: u64,
33 value: u8,
34}
35
36impl SetBit {
37 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#[derive(Clone)]
78pub struct GetBit {
79 key: CommandArg,
80 offset: u64,
81}
82
83impl GetBit {
84 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#[derive(Clone)]
125pub struct BitCount {
126 key: CommandArg,
127 range: Option<(i64, i64)>,
128 bit_mode: bool,
129}
130
131impl BitCount {
132 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 pub fn range(mut self, start: i64, end: i64) -> Self {
143 self.range = Some((start, end));
144 self
145 }
146
147 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#[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 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 pub fn range(mut self, start: i64, end: i64) -> Self {
210 self.range = Some((start, end));
211 self
212 }
213
214 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#[derive(Clone)]
253pub enum BitOperation {
254 And,
256 Or,
258 Xor,
260 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#[derive(Clone)]
281pub struct BitOp {
282 operation: BitOperation,
283 destkey: CommandArg,
284 keys: Vec<CommandArg>,
285}
286
287impl BitOp {
288 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
339pub enum BitfieldOverflow {
340 Wrap,
342 Sat,
344 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#[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#[derive(Clone)]
412pub struct Bitfield {
413 key: CommandArg,
414 ops: Vec<BitfieldOp>,
415}
416
417impl Bitfield {
418 pub fn new(key: impl Into<CommandArg>) -> Self {
420 Self {
421 key: key.into(),
422 ops: Vec::new(),
423 }
424 }
425
426 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 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 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 pub fn overflow(mut self, overflow: BitfieldOverflow) -> Self {
470 self.ops.push(BitfieldOp::Overflow(overflow));
471 self
472 }
473}
474
475fn 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#[derive(Clone)]
570pub struct BitfieldRo {
571 key: CommandArg,
572 gets: Vec<(String, String)>,
573}
574
575impl BitfieldRo {
576 pub fn new(key: impl Into<CommandArg>) -> Self {
578 Self {
579 key: key.into(),
580 gets: Vec::new(),
581 }
582 }
583
584 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}