1#[cfg(feature = "aio")]
2use futures_util::{
3 future::BoxFuture,
4 task::{Context, Poll},
5 Stream, StreamExt,
6};
7#[cfg(feature = "aio")]
8use std::pin::Pin;
9#[cfg(feature = "cache-aio")]
10use std::time::Duration;
11use std::{fmt, io};
12
13use crate::connection::ConnectionLike;
14use crate::pipeline::Pipeline;
15use crate::types::{from_owned_redis_value, FromRedisValue, RedisResult, RedisWrite, ToRedisArgs};
16
17#[derive(Clone)]
19pub enum Arg<D> {
20 Simple(D),
22 Cursor,
24}
25
26#[cfg(feature = "cache-aio")]
39#[cfg_attr(docsrs, doc(cfg(feature = "cache-aio")))]
40#[derive(Clone)]
41pub struct CommandCacheConfig {
42 pub(crate) enable_cache: bool,
43 pub(crate) client_side_ttl: Option<Duration>,
44}
45
46#[cfg(feature = "cache-aio")]
47impl CommandCacheConfig {
48 pub fn new() -> Self {
50 Self {
51 enable_cache: true,
52 client_side_ttl: None,
53 }
54 }
55
56 pub fn set_enable_cache(mut self, enable_cache: bool) -> Self {
59 self.enable_cache = enable_cache;
60 self
61 }
62
63 pub fn set_client_side_ttl(mut self, client_side_ttl: Duration) -> Self {
65 self.client_side_ttl = Some(client_side_ttl);
66 self
67 }
68}
69#[cfg(feature = "cache-aio")]
70impl Default for CommandCacheConfig {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76#[derive(Clone)]
78pub struct Cmd {
79 pub(crate) data: Vec<u8>,
80 args: Vec<Arg<usize>>,
82 cursor: Option<u64>,
83 no_response: bool,
85 #[cfg(feature = "cache-aio")]
86 cache: Option<CommandCacheConfig>,
87}
88
89pub struct Iter<'a, T: FromRedisValue> {
91 batch: std::vec::IntoIter<T>,
92 cursor: u64,
93 con: &'a mut (dyn ConnectionLike + 'a),
94 cmd: Cmd,
95}
96
97impl<T: FromRedisValue> Iterator for Iter<'_, T> {
98 type Item = T;
99
100 #[inline]
101 fn next(&mut self) -> Option<T> {
102 loop {
107 if let Some(v) = self.batch.next() {
108 return Some(v);
109 };
110 if self.cursor == 0 {
111 return None;
112 }
113
114 let pcmd = self.cmd.get_packed_command_with_cursor(self.cursor)?;
115 let rv = self.con.req_packed_command(&pcmd).ok()?;
116 let (cur, batch): (u64, Vec<T>) = from_owned_redis_value(rv).ok()?;
117
118 self.cursor = cur;
119 self.batch = batch.into_iter();
120 }
121 }
122}
123
124#[cfg(feature = "aio")]
125use crate::aio::ConnectionLike as AsyncConnection;
126
127#[cfg(feature = "aio")]
129struct AsyncIterInner<'a, T: FromRedisValue + 'a> {
130 batch: std::vec::IntoIter<T>,
131 con: &'a mut (dyn AsyncConnection + Send + 'a),
132 cmd: Cmd,
133}
134
135#[cfg(feature = "aio")]
137enum IterOrFuture<'a, T: FromRedisValue + 'a> {
138 Iter(AsyncIterInner<'a, T>),
139 Future(BoxFuture<'a, (AsyncIterInner<'a, T>, Option<T>)>),
140 Empty,
141}
142
143#[cfg(feature = "aio")]
145pub struct AsyncIter<'a, T: FromRedisValue + 'a> {
146 inner: IterOrFuture<'a, T>,
147}
148
149#[cfg(feature = "aio")]
150impl<'a, T: FromRedisValue + 'a> AsyncIterInner<'a, T> {
151 #[inline]
152 pub async fn next_item(&mut self) -> Option<T> {
153 loop {
158 if let Some(v) = self.batch.next() {
159 return Some(v);
160 };
161 if let Some(cursor) = self.cmd.cursor {
162 if cursor == 0 {
163 return None;
164 }
165 } else {
166 return None;
167 }
168
169 let rv = self.con.req_packed_command(&self.cmd).await.ok()?;
170 let (cur, batch): (u64, Vec<T>) = from_owned_redis_value(rv).ok()?;
171
172 self.cmd.cursor = Some(cur);
173 self.batch = batch.into_iter();
174 }
175 }
176}
177
178#[cfg(feature = "aio")]
179impl<'a, T: FromRedisValue + 'a + Unpin + Send> AsyncIter<'a, T> {
180 #[inline]
195 pub async fn next_item(&mut self) -> Option<T> {
196 StreamExt::next(self).await
197 }
198}
199
200#[cfg(feature = "aio")]
201impl<'a, T: FromRedisValue + Unpin + Send + 'a> Stream for AsyncIter<'a, T> {
202 type Item = T;
203
204 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
205 let this = self.get_mut();
206 let inner = std::mem::replace(&mut this.inner, IterOrFuture::Empty);
207 match inner {
208 IterOrFuture::Iter(mut iter) => {
209 let fut = async move {
210 let next_item = iter.next_item().await;
211 (iter, next_item)
212 };
213 this.inner = IterOrFuture::Future(Box::pin(fut));
214 Pin::new(this).poll_next(cx)
215 }
216 IterOrFuture::Future(mut fut) => match fut.as_mut().poll(cx) {
217 Poll::Pending => {
218 this.inner = IterOrFuture::Future(fut);
219 Poll::Pending
220 }
221 Poll::Ready((iter, value)) => {
222 this.inner = IterOrFuture::Iter(iter);
223 Poll::Ready(value)
224 }
225 },
226 IterOrFuture::Empty => unreachable!(),
227 }
228 }
229}
230
231fn countdigits(mut v: usize) -> usize {
232 let mut result = 1;
233 loop {
234 if v < 10 {
235 return result;
236 }
237 if v < 100 {
238 return result + 1;
239 }
240 if v < 1000 {
241 return result + 2;
242 }
243 if v < 10000 {
244 return result + 3;
245 }
246
247 v /= 10000;
248 result += 4;
249 }
250}
251
252#[inline]
253fn bulklen(len: usize) -> usize {
254 1 + countdigits(len) + 2 + len + 2
255}
256
257fn args_len<'a, I>(args: I, cursor: u64) -> usize
258where
259 I: IntoIterator<Item = Arg<&'a [u8]>> + ExactSizeIterator,
260{
261 let mut totlen = 1 + countdigits(args.len()) + 2;
262 for item in args {
263 totlen += bulklen(match item {
264 Arg::Cursor => countdigits(cursor as usize),
265 Arg::Simple(val) => val.len(),
266 });
267 }
268 totlen
269}
270
271pub(crate) fn cmd_len(cmd: &Cmd) -> usize {
272 args_len(cmd.args_iter(), cmd.cursor.unwrap_or(0))
273}
274
275fn encode_command<'a, I>(args: I, cursor: u64) -> Vec<u8>
276where
277 I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
278{
279 let mut cmd = Vec::new();
280 write_command_to_vec(&mut cmd, args, cursor);
281 cmd
282}
283
284fn write_command_to_vec<'a, I>(cmd: &mut Vec<u8>, args: I, cursor: u64)
285where
286 I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
287{
288 let totlen = args_len(args.clone(), cursor);
289
290 cmd.reserve(totlen);
291
292 write_command(cmd, args, cursor).unwrap()
293}
294
295fn write_command<'a, I>(cmd: &mut (impl ?Sized + io::Write), args: I, cursor: u64) -> io::Result<()>
296where
297 I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
298{
299 let mut buf = ::itoa::Buffer::new();
300
301 cmd.write_all(b"*")?;
302 let s = buf.format(args.len());
303 cmd.write_all(s.as_bytes())?;
304 cmd.write_all(b"\r\n")?;
305
306 let mut cursor_bytes = itoa::Buffer::new();
307 for item in args {
308 let bytes = match item {
309 Arg::Cursor => cursor_bytes.format(cursor).as_bytes(),
310 Arg::Simple(val) => val,
311 };
312
313 cmd.write_all(b"$")?;
314 let s = buf.format(bytes.len());
315 cmd.write_all(s.as_bytes())?;
316 cmd.write_all(b"\r\n")?;
317
318 cmd.write_all(bytes)?;
319 cmd.write_all(b"\r\n")?;
320 }
321 Ok(())
322}
323
324impl RedisWrite for Cmd {
325 fn write_arg(&mut self, arg: &[u8]) {
326 self.data.extend_from_slice(arg);
327 self.args.push(Arg::Simple(self.data.len()));
328 }
329
330 fn write_arg_fmt(&mut self, arg: impl fmt::Display) {
331 use std::io::Write;
332 write!(self.data, "{arg}").unwrap();
333 self.args.push(Arg::Simple(self.data.len()));
334 }
335
336 fn writer_for_next_arg(&mut self) -> impl std::io::Write + '_ {
337 struct CmdBufferedArgGuard<'a>(&'a mut Cmd);
338 impl Drop for CmdBufferedArgGuard<'_> {
339 fn drop(&mut self) {
340 self.0.args.push(Arg::Simple(self.0.data.len()));
341 }
342 }
343 impl std::io::Write for CmdBufferedArgGuard<'_> {
344 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
345 self.0.data.extend_from_slice(buf);
346 Ok(buf.len())
347 }
348
349 fn flush(&mut self) -> std::io::Result<()> {
350 Ok(())
351 }
352 }
353
354 CmdBufferedArgGuard(self)
355 }
356}
357
358impl Default for Cmd {
359 fn default() -> Cmd {
360 Cmd::new()
361 }
362}
363
364impl Cmd {
392 pub fn new() -> Cmd {
394 Cmd {
395 data: vec![],
396 args: vec![],
397 cursor: None,
398 no_response: false,
399 #[cfg(feature = "cache-aio")]
400 cache: None,
401 }
402 }
403
404 pub fn with_capacity(arg_count: usize, size_of_data: usize) -> Cmd {
406 Cmd {
407 data: Vec::with_capacity(size_of_data),
408 args: Vec::with_capacity(arg_count),
409 cursor: None,
410 no_response: false,
411 #[cfg(feature = "cache-aio")]
412 cache: None,
413 }
414 }
415
416 #[cfg(test)]
418 #[allow(dead_code)]
419 pub(crate) fn capacity(&self) -> (usize, usize) {
420 (self.args.capacity(), self.data.capacity())
421 }
422
423 #[inline]
437 pub fn arg<T: ToRedisArgs>(&mut self, arg: T) -> &mut Cmd {
438 arg.write_redis_args(self);
439 self
440 }
441
442 #[inline]
458 pub fn cursor_arg(&mut self, cursor: u64) -> &mut Cmd {
459 assert!(!self.in_scan_mode());
460 self.cursor = Some(cursor);
461 self.args.push(Arg::Cursor);
462 self
463 }
464
465 #[inline]
467 pub fn get_packed_command(&self) -> Vec<u8> {
468 let mut cmd = Vec::new();
469 self.write_packed_command(&mut cmd);
470 cmd
471 }
472
473 pub(crate) fn write_packed_command(&self, cmd: &mut Vec<u8>) {
474 write_command_to_vec(cmd, self.args_iter(), self.cursor.unwrap_or(0))
475 }
476
477 pub(crate) fn write_packed_command_preallocated(&self, cmd: &mut Vec<u8>) {
478 write_command(cmd, self.args_iter(), self.cursor.unwrap_or(0)).unwrap()
479 }
480
481 #[inline]
485 fn get_packed_command_with_cursor(&self, cursor: u64) -> Option<Vec<u8>> {
486 if !self.in_scan_mode() {
487 None
488 } else {
489 Some(encode_command(self.args_iter(), cursor))
490 }
491 }
492
493 #[inline]
495 pub fn in_scan_mode(&self) -> bool {
496 self.cursor.is_some()
497 }
498
499 #[inline]
503 pub fn query<T: FromRedisValue>(&self, con: &mut dyn ConnectionLike) -> RedisResult<T> {
504 match con.req_command(self) {
505 Ok(val) => from_owned_redis_value(val.extract_error()?),
506 Err(e) => Err(e),
507 }
508 }
509
510 #[inline]
512 #[cfg(feature = "aio")]
513 pub async fn query_async<T: FromRedisValue>(
514 &self,
515 con: &mut impl crate::aio::ConnectionLike,
516 ) -> RedisResult<T> {
517 let val = con.req_packed_command(self).await?;
518 from_owned_redis_value(val.extract_error()?)
519 }
520
521 #[inline]
536 pub fn iter<T: FromRedisValue>(self, con: &mut dyn ConnectionLike) -> RedisResult<Iter<'_, T>> {
537 let rv = con.req_command(&self)?;
538
539 let (cursor, batch) = if rv.looks_like_cursor() {
540 from_owned_redis_value::<(u64, Vec<T>)>(rv)?
541 } else {
542 (0, from_owned_redis_value(rv)?)
543 };
544
545 Ok(Iter {
546 batch: batch.into_iter(),
547 cursor,
548 con,
549 cmd: self,
550 })
551 }
552
553 #[cfg(feature = "aio")]
569 #[inline]
570 pub async fn iter_async<'a, T: FromRedisValue + 'a>(
571 mut self,
572 con: &'a mut (dyn AsyncConnection + Send),
573 ) -> RedisResult<AsyncIter<'a, T>> {
574 let rv = con.req_packed_command(&self).await?;
575
576 let (cursor, batch) = if rv.looks_like_cursor() {
577 from_owned_redis_value::<(u64, Vec<T>)>(rv)?
578 } else {
579 (0, from_owned_redis_value(rv)?)
580 };
581 if cursor == 0 {
582 self.cursor = None;
583 } else {
584 self.cursor = Some(cursor);
585 }
586
587 Ok(AsyncIter {
588 inner: IterOrFuture::Iter(AsyncIterInner {
589 batch: batch.into_iter(),
590 con,
591 cmd: self,
592 }),
593 })
594 }
595
596 #[inline]
609 #[deprecated(note = "Use Cmd::exec + unwrap, instead")]
610 pub fn execute(&self, con: &mut dyn ConnectionLike) {
611 self.exec(con).unwrap();
612 }
613
614 #[inline]
619 pub fn exec(&self, con: &mut dyn ConnectionLike) -> RedisResult<()> {
620 self.query::<()>(con)
621 }
622
623 #[cfg(feature = "aio")]
628 pub async fn exec_async(&self, con: &mut impl crate::aio::ConnectionLike) -> RedisResult<()> {
629 self.query_async::<()>(con).await
630 }
631
632 pub fn args_iter(&self) -> impl Clone + ExactSizeIterator<Item = Arg<&[u8]>> {
634 let mut prev = 0;
635 self.args.iter().map(move |arg| match *arg {
636 Arg::Simple(i) => {
637 let arg = Arg::Simple(&self.data[prev..i]);
638 prev = i;
639 arg
640 }
641
642 Arg::Cursor => Arg::Cursor,
643 })
644 }
645
646 #[cfg(any(feature = "cluster", feature = "cache-aio"))]
648 pub(crate) fn arg_idx(&self, idx: usize) -> Option<&[u8]> {
649 if idx >= self.args.len() {
650 return None;
651 }
652
653 let start = if idx == 0 {
654 0
655 } else {
656 match self.args[idx - 1] {
657 Arg::Simple(n) => n,
658 _ => 0,
659 }
660 };
661 let end = match self.args[idx] {
662 Arg::Simple(n) => n,
663 _ => 0,
664 };
665 if start == 0 && end == 0 {
666 return None;
667 }
668 Some(&self.data[start..end])
669 }
670
671 #[inline]
673 pub fn set_no_response(&mut self, nr: bool) -> &mut Cmd {
674 self.no_response = nr;
675 self
676 }
677
678 #[inline]
680 pub fn is_no_response(&self) -> bool {
681 self.no_response
682 }
683
684 #[cfg(feature = "cache-aio")]
686 #[cfg_attr(docsrs, doc(cfg(feature = "cache-aio")))]
687 pub fn set_cache_config(&mut self, command_cache_config: CommandCacheConfig) -> &mut Cmd {
688 self.cache = Some(command_cache_config);
689 self
690 }
691
692 #[cfg(feature = "cache-aio")]
693 #[inline]
694 pub(crate) fn get_cache_config(&self) -> &Option<CommandCacheConfig> {
695 &self.cache
696 }
697}
698
699pub fn cmd(name: &str) -> Cmd {
709 let mut rv = Cmd::new();
710 rv.arg(name);
711 rv
712}
713
714pub fn pack_command(args: &[Vec<u8>]) -> Vec<u8> {
733 encode_command(args.iter().map(|x| Arg::Simple(&x[..])), 0)
734}
735
736pub fn pipe() -> Pipeline {
738 Pipeline::new()
739}
740
741#[cfg(test)]
742mod tests {
743 use super::Cmd;
744
745 use crate::RedisWrite;
746 use std::io::Write;
747
748 #[test]
749 fn test_cmd_writer_for_next_arg() {
750 let mut c1 = Cmd::new();
753 {
754 let mut c1_writer = c1.writer_for_next_arg();
755 c1_writer.write_all(b"foo").unwrap();
756 c1_writer.write_all(b"bar").unwrap();
757 c1_writer.flush().unwrap();
758 }
759 let v1 = c1.get_packed_command();
760
761 let mut c2 = Cmd::new();
762 c2.write_arg(b"foobar");
763 let v2 = c2.get_packed_command();
764
765 assert_eq!(v1, v2);
766 }
767
768 #[test]
771 fn test_cmd_writer_for_next_arg_multiple() {
772 let mut c1 = Cmd::new();
773 {
774 let mut c1_writer = c1.writer_for_next_arg();
775 c1_writer.write_all(b"foo").unwrap();
776 c1_writer.write_all(b"bar").unwrap();
777 c1_writer.flush().unwrap();
778 }
779 {
780 let mut c1_writer = c1.writer_for_next_arg();
781 c1_writer.write_all(b"baz").unwrap();
782 c1_writer.write_all(b"qux").unwrap();
783 c1_writer.flush().unwrap();
784 }
785 let v1 = c1.get_packed_command();
786
787 let mut c2 = Cmd::new();
788 c2.write_arg(b"foobar");
789 c2.write_arg(b"bazqux");
790 let v2 = c2.get_packed_command();
791
792 assert_eq!(v1, v2);
793 }
794
795 #[test]
797 fn test_cmd_writer_for_next_arg_empty() {
798 let mut c1 = Cmd::new();
799 {
800 let mut c1_writer = c1.writer_for_next_arg();
801 c1_writer.flush().unwrap();
802 }
803 let v1 = c1.get_packed_command();
804
805 let mut c2 = Cmd::new();
806 c2.write_arg(b"");
807 let v2 = c2.get_packed_command();
808
809 assert_eq!(v1, v2);
810 }
811
812 #[test]
813 #[cfg(feature = "cluster")]
814 fn test_cmd_arg_idx() {
815 let mut c = Cmd::new();
816 assert_eq!(c.arg_idx(0), None);
817
818 c.arg("SET");
819 assert_eq!(c.arg_idx(0), Some(&b"SET"[..]));
820 assert_eq!(c.arg_idx(1), None);
821
822 c.arg("foo").arg("42");
823 assert_eq!(c.arg_idx(1), Some(&b"foo"[..]));
824 assert_eq!(c.arg_idx(2), Some(&b"42"[..]));
825 assert_eq!(c.arg_idx(3), None);
826 assert_eq!(c.arg_idx(4), None);
827 }
828}