Skip to main content

redis/
cmd.rs

1#[cfg(feature = "aio")]
2use futures_util::{
3    Stream, StreamExt,
4    future::BoxFuture,
5    task::{Context, Poll},
6};
7#[cfg(feature = "aio")]
8use std::pin::Pin;
9#[cfg(feature = "cache-aio")]
10use std::time::Duration;
11use std::{fmt, io::Write};
12
13use crate::pipeline::Pipeline;
14use crate::types::{FromRedisValue, RedisResult, RedisWrite, ToRedisArgs, from_redis_value};
15use crate::{ParsingError, connection::ConnectionLike};
16
17/// An argument to a redis command
18#[derive(Clone, PartialEq, Debug)]
19#[non_exhaustive]
20pub enum Arg<D> {
21    /// A normal argument
22    Simple(D),
23    /// A cursor argument created from `cursor_arg()`
24    Cursor,
25}
26
27/// CommandCacheConfig is used to define caching behaviour of individual commands.
28/// # Example
29/// ```rust
30/// use std::time::Duration;
31/// use redis::{CommandCacheConfig, Cmd};
32///
33/// let ttl = Duration::from_secs(120); // 2 minutes TTL
34/// let config = CommandCacheConfig::new()
35///     .set_enable_cache(true)
36///     .set_client_side_ttl(ttl);
37/// let command = Cmd::new().arg("GET").arg("key").set_cache_config(config);
38/// ```
39#[cfg(feature = "cache-aio")]
40#[cfg_attr(docsrs, doc(cfg(feature = "cache-aio")))]
41#[derive(Clone, Debug)]
42pub struct CommandCacheConfig {
43    pub(crate) enable_cache: bool,
44    pub(crate) client_side_ttl: Option<Duration>,
45}
46
47#[cfg(feature = "cache-aio")]
48impl CommandCacheConfig {
49    /// Creates new CommandCacheConfig with enable_cache as true and without client_side_ttl.
50    pub fn new() -> Self {
51        Self {
52            enable_cache: true,
53            client_side_ttl: None,
54        }
55    }
56
57    /// Sets whether the cache should be enabled or not.
58    /// Disabling cache for specific command when using [crate::caching::CacheMode::All] will not work.
59    pub fn set_enable_cache(mut self, enable_cache: bool) -> Self {
60        self.enable_cache = enable_cache;
61        self
62    }
63
64    /// Sets custom client side time to live (TTL).
65    pub fn set_client_side_ttl(mut self, client_side_ttl: Duration) -> Self {
66        self.client_side_ttl = Some(client_side_ttl);
67        self
68    }
69}
70#[cfg(feature = "cache-aio")]
71impl Default for CommandCacheConfig {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77/// Represents redis commands.
78#[derive(Clone)]
79pub struct Cmd {
80    pub(crate) data: Vec<u8>,
81    // Arg::Simple contains the offset that marks the end of the argument
82    args: Vec<Arg<usize>>,
83    cursor: Option<u64>,
84    // If it's true command's response won't be read from socket. Useful for Pub/Sub.
85    no_response: bool,
86    pub(crate) skip_concurrency_limit: bool,
87    #[cfg(feature = "cache-aio")]
88    cache: Option<CommandCacheConfig>,
89}
90
91impl std::fmt::Debug for Cmd {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        let mut debug_struct = f.debug_struct("Cmd");
94        debug_struct
95            .field("data", &String::from_utf8_lossy(&self.data).as_ref())
96            .field("args", &self.args)
97            .field("cursor", &self.cursor)
98            .field("no_response", &self.no_response);
99
100        #[cfg(feature = "cache-aio")]
101        debug_struct.field("cache", &self.cache);
102
103        debug_struct.finish()
104    }
105}
106
107/// Represents a redis iterator.
108pub struct Iter<'a, T: FromRedisValue> {
109    iter: CheckedIter<'a, T>,
110}
111impl<T: FromRedisValue> Iterator for Iter<'_, T> {
112    type Item = RedisResult<T>;
113
114    #[inline]
115    fn next(&mut self) -> Option<RedisResult<T>> {
116        self.iter.next()
117    }
118}
119
120/// Represents a safe(r) redis iterator.
121struct CheckedIter<'a, T: FromRedisValue> {
122    batch: std::vec::IntoIter<Result<T, ParsingError>>,
123    con: &'a mut (dyn ConnectionLike + 'a),
124    cmd: Cmd,
125}
126
127impl<T: FromRedisValue> Iterator for CheckedIter<'_, T> {
128    type Item = RedisResult<T>;
129
130    #[inline]
131    fn next(&mut self) -> Option<RedisResult<T>> {
132        // we need to do this in a loop until we produce at least one item
133        // or we find the actual end of the iteration.  This is necessary
134        // because with filtering an iterator it is possible that a whole
135        // chunk is not matching the pattern and thus yielding empty results.
136        loop {
137            if let Some(value) = self.batch.next() {
138                return Some(value.map_err(|err| err.into()));
139            }
140
141            if self.cmd.cursor? == 0 {
142                return None;
143            }
144
145            let (cursor, batch) = match self
146                .con
147                .req_packed_command(&self.cmd.get_packed_command())
148                .and_then(|val| Ok(from_redis_value::<(u64, _)>(val)?))
149            {
150                Ok((cursor, values)) => (cursor, T::from_each_redis_values(values)),
151                Err(e) => return Some(Err(e)),
152            };
153
154            self.cmd.cursor = Some(cursor);
155            self.batch = batch.into_iter();
156        }
157    }
158}
159
160#[cfg(feature = "aio")]
161use crate::aio::ConnectionLike as AsyncConnection;
162
163/// The inner future of AsyncIter
164#[cfg(feature = "aio")]
165struct AsyncIterInner<'a, T: FromRedisValue + 'a> {
166    batch: std::vec::IntoIter<Result<T, ParsingError>>,
167    con: &'a mut (dyn AsyncConnection + Send + 'a),
168    cmd: Cmd,
169}
170
171/// Represents the state of AsyncIter
172#[cfg(feature = "aio")]
173enum IterOrFuture<'a, T: FromRedisValue + 'a> {
174    Iter(AsyncIterInner<'a, T>),
175    Future(BoxFuture<'a, (AsyncIterInner<'a, T>, Option<RedisResult<T>>)>),
176    Empty,
177}
178
179/// Represents a redis iterator that can be used with async connections.
180#[cfg(feature = "aio")]
181pub struct AsyncIter<'a, T: FromRedisValue + 'a> {
182    inner: IterOrFuture<'a, T>,
183}
184
185#[cfg(feature = "aio")]
186impl<'a, T: FromRedisValue + 'a> AsyncIterInner<'a, T> {
187    async fn next_item(&mut self) -> Option<RedisResult<T>> {
188        // we need to do this in a loop until we produce at least one item
189        // or we find the actual end of the iteration.  This is necessary
190        // because with filtering an iterator it is possible that a whole
191        // chunk is not matching the pattern and thus yielding empty results.
192        loop {
193            if let Some(v) = self.batch.next() {
194                return Some(v.map_err(|err| err.into()));
195            }
196
197            if self.cmd.cursor? == 0 {
198                return None;
199            }
200
201            let (cursor, batch) = match self
202                .con
203                .req_packed_command(&self.cmd)
204                .await
205                .and_then(|val| Ok(from_redis_value::<(u64, _)>(val)?))
206            {
207                Ok((cursor, items)) => (cursor, T::from_each_redis_values(items)),
208                Err(e) => return Some(Err(e)),
209            };
210
211            self.cmd.cursor = Some(cursor);
212            self.batch = batch.into_iter();
213        }
214    }
215}
216
217#[cfg(feature = "aio")]
218impl<'a, T: FromRedisValue + 'a + Unpin + Send> AsyncIter<'a, T> {
219    /// ```rust,no_run
220    /// # use redis::AsyncCommands;
221    /// # async fn scan_set() -> redis::RedisResult<()> {
222    /// # let client = redis::Client::open("redis://127.0.0.1/")?;
223    /// # let mut con = client.get_multiplexed_async_connection().await?;
224    /// let _: () = con.sadd("my_set", 42i32).await?;
225    /// let _: () = con.sadd("my_set", 43i32).await?;
226    /// let mut iter: redis::AsyncIter<i32> = con.sscan("my_set").await?;
227    /// while let Some(element) = iter.next_item().await {
228    ///     let element = element?;
229    ///     assert!(element == 42 || element == 43);
230    /// }
231    /// # Ok(())
232    /// # }
233    /// ```
234    #[inline]
235    pub async fn next_item(&mut self) -> Option<RedisResult<T>> {
236        StreamExt::next(self).await
237    }
238}
239
240#[cfg(feature = "aio")]
241impl<'a, T: FromRedisValue + Unpin + Send + 'a> Stream for AsyncIter<'a, T> {
242    type Item = RedisResult<T>;
243
244    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
245        let this = self.get_mut();
246        let inner = std::mem::replace(&mut this.inner, IterOrFuture::Empty);
247        match inner {
248            IterOrFuture::Iter(mut iter) => {
249                let fut = async move {
250                    let next_item = iter.next_item().await;
251                    (iter, next_item)
252                };
253                this.inner = IterOrFuture::Future(Box::pin(fut));
254                Pin::new(this).poll_next(cx)
255            }
256            IterOrFuture::Future(mut fut) => match fut.as_mut().poll(cx) {
257                Poll::Pending => {
258                    this.inner = IterOrFuture::Future(fut);
259                    Poll::Pending
260                }
261                Poll::Ready((iter, value)) => {
262                    this.inner = IterOrFuture::Iter(iter);
263
264                    Poll::Ready(value)
265                }
266            },
267            IterOrFuture::Empty => unreachable!(),
268        }
269    }
270}
271
272fn countdigits(mut v: usize) -> usize {
273    let mut result = 1;
274    loop {
275        if v < 10 {
276            return result;
277        }
278        if v < 100 {
279            return result + 1;
280        }
281        if v < 1000 {
282            return result + 2;
283        }
284        if v < 10000 {
285            return result + 3;
286        }
287
288        v /= 10000;
289        result += 4;
290    }
291}
292
293#[inline]
294fn bulklen(len: usize) -> usize {
295    1 + countdigits(len) + 2 + len + 2
296}
297
298fn args_len<'a, I>(args: I, cursor: u64) -> usize
299where
300    I: IntoIterator<Item = Arg<&'a [u8]>> + ExactSizeIterator,
301{
302    let mut totlen = 1 + countdigits(args.len()) + 2;
303    for item in args {
304        totlen += bulklen(match item {
305            Arg::Cursor => countdigits(cursor as usize),
306            Arg::Simple(val) => val.len(),
307        });
308    }
309    totlen
310}
311
312pub(crate) fn cmd_len(cmd: &Cmd) -> usize {
313    args_len(cmd.args_iter(), cmd.cursor.unwrap_or(0))
314}
315
316fn encode_command<'a, I>(args: I, cursor: u64) -> Vec<u8>
317where
318    I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
319{
320    let mut cmd = Vec::new();
321    write_command_to_vec(&mut cmd, args, cursor);
322    cmd
323}
324
325fn write_command_to_vec<'a, I>(cmd: &mut Vec<u8>, args: I, cursor: u64)
326where
327    I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
328{
329    let totlen = args_len(args.clone(), cursor);
330
331    cmd.reserve(totlen);
332
333    write_command(cmd, args, cursor);
334}
335
336fn write_command<'a, I>(cmd: &mut Vec<u8>, args: I, cursor: u64)
337where
338    I: IntoIterator<Item = Arg<&'a [u8]>> + Clone + ExactSizeIterator,
339{
340    let mut buf = ::itoa::Buffer::new();
341
342    cmd.extend_from_slice(b"*");
343    cmd.extend_from_slice(buf.format(args.len()).as_bytes());
344    cmd.extend_from_slice(b"\r\n");
345
346    let mut cursor_bytes = itoa::Buffer::new();
347    for item in args {
348        let bytes = match item {
349            Arg::Cursor => cursor_bytes.format(cursor).as_bytes(),
350            Arg::Simple(val) => val,
351        };
352
353        cmd.extend_from_slice(b"$");
354        cmd.extend_from_slice(buf.format(bytes.len()).as_bytes());
355        cmd.extend_from_slice(b"\r\n");
356
357        cmd.extend_from_slice(bytes);
358        cmd.extend_from_slice(b"\r\n");
359    }
360}
361
362impl RedisWrite for Cmd {
363    fn write_arg(&mut self, arg: &[u8]) {
364        self.data.extend_from_slice(arg);
365        self.args.push(Arg::Simple(self.data.len()));
366    }
367
368    fn write_arg_fmt(&mut self, arg: impl fmt::Display) {
369        write!(self.data, "{arg}").unwrap();
370        self.args.push(Arg::Simple(self.data.len()));
371    }
372
373    fn writer_for_next_arg(&mut self) -> impl Write + '_ {
374        struct CmdBufferedArgGuard<'a>(&'a mut Cmd);
375        impl Drop for CmdBufferedArgGuard<'_> {
376            fn drop(&mut self) {
377                self.0.args.push(Arg::Simple(self.0.data.len()));
378            }
379        }
380        impl Write for CmdBufferedArgGuard<'_> {
381            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
382                self.0.data.extend_from_slice(buf);
383                Ok(buf.len())
384            }
385
386            fn flush(&mut self) -> std::io::Result<()> {
387                Ok(())
388            }
389        }
390
391        CmdBufferedArgGuard(self)
392    }
393
394    fn reserve_space_for_args(&mut self, additional: impl IntoIterator<Item = usize>) {
395        let mut capacity = 0;
396        let mut args = 0;
397        for add in additional {
398            capacity += add;
399            args += 1;
400        }
401        self.data.reserve(capacity);
402        self.args.reserve(args);
403    }
404
405    #[cfg(feature = "bytes")]
406    fn bufmut_for_next_arg(&mut self, capacity: usize) -> impl bytes::BufMut + '_ {
407        self.data.reserve(capacity);
408        struct CmdBufferedArgGuard<'a>(&'a mut Cmd);
409        impl Drop for CmdBufferedArgGuard<'_> {
410            fn drop(&mut self) {
411                self.0.args.push(Arg::Simple(self.0.data.len()));
412            }
413        }
414        unsafe impl bytes::BufMut for CmdBufferedArgGuard<'_> {
415            fn remaining_mut(&self) -> usize {
416                self.0.data.remaining_mut()
417            }
418
419            unsafe fn advance_mut(&mut self, cnt: usize) {
420                unsafe {
421                    self.0.data.advance_mut(cnt);
422                }
423            }
424
425            fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
426                self.0.data.chunk_mut()
427            }
428
429            // Vec specializes these methods, so we do too
430            fn put<T: bytes::buf::Buf>(&mut self, src: T)
431            where
432                Self: Sized,
433            {
434                self.0.data.put(src);
435            }
436
437            fn put_slice(&mut self, src: &[u8]) {
438                self.0.data.put_slice(src);
439            }
440
441            fn put_bytes(&mut self, val: u8, cnt: usize) {
442                self.0.data.put_bytes(val, cnt);
443            }
444        }
445
446        CmdBufferedArgGuard(self)
447    }
448}
449
450impl Default for Cmd {
451    fn default() -> Self {
452        Self::new()
453    }
454}
455
456/// A command acts as a builder interface to creating encoded redis
457/// requests.  This allows you to easily assemble a packed command
458/// by chaining arguments together.
459///
460/// Basic example:
461///
462/// ```rust
463/// redis::Cmd::new().arg("SET").arg("my_key").arg(42);
464/// ```
465///
466/// There is also a helper function called `cmd` which makes it a
467/// tiny bit shorter:
468///
469/// ```rust
470/// redis::cmd("SET").arg("my_key").arg(42);
471/// ```
472///
473/// Because Rust currently does not have an ideal system
474/// for lifetimes of temporaries, sometimes you need to hold on to
475/// the initially generated command:
476///
477/// ```rust,no_run
478/// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
479/// # let mut con = client.get_connection().unwrap();
480/// let mut cmd = redis::cmd("SMEMBERS");
481/// let mut iter : redis::Iter<i32> = cmd.arg("my_set").clone().iter(&mut con).unwrap();
482/// ```
483impl Cmd {
484    /// Creates a new empty command.
485    pub fn new() -> Self {
486        Self {
487            data: vec![],
488            args: vec![],
489            cursor: None,
490            no_response: false,
491            skip_concurrency_limit: false,
492            #[cfg(feature = "cache-aio")]
493            cache: None,
494        }
495    }
496
497    /// Creates a new empty command, with at least the requested capacity.
498    pub fn with_capacity(arg_count: usize, size_of_data: usize) -> Self {
499        Self {
500            data: Vec::with_capacity(size_of_data),
501            args: Vec::with_capacity(arg_count),
502            cursor: None,
503            no_response: false,
504            skip_concurrency_limit: false,
505            #[cfg(feature = "cache-aio")]
506            cache: None,
507        }
508    }
509
510    /// Get the capacities for the internal buffers.
511    #[cfg(test)]
512    #[allow(dead_code)]
513    pub(crate) fn capacity(&self) -> (usize, usize) {
514        (self.args.capacity(), self.data.capacity())
515    }
516
517    /// Clears the command, resetting it completely.
518    ///
519    /// This is equivalent to [`Cmd::new`], except the buffer capacity is kept.
520    ///
521    /// # Examples
522    ///
523    /// ```rust,no_run
524    /// # use redis::{Client, Cmd};
525    /// # let client = Client::open("redis://127.0.0.1/").unwrap();
526    /// # let mut con = client.get_connection().expect("Failed to connect to Redis");
527    /// let mut cmd = Cmd::new();
528    /// cmd.arg("SET").arg("foo").arg("42");
529    /// cmd.query::<()>(&mut con).expect("Query failed");
530    /// cmd.clear();
531    /// // This reuses the allocations of the previous command
532    /// cmd.arg("SET").arg("bar").arg("42");
533    /// cmd.query::<()>(&mut con).expect("Query failed");
534    /// ```
535    pub fn clear(&mut self) {
536        self.data.clear();
537        self.args.clear();
538        self.cursor = None;
539        self.no_response = false;
540        self.skip_concurrency_limit = false;
541        #[cfg(feature = "cache-aio")]
542        {
543            self.cache = None;
544        }
545    }
546
547    /// Appends an argument to the command.  The argument passed must
548    /// be a type that implements `ToRedisArgs`.  Most primitive types as
549    /// well as vectors of primitive types implement it.
550    ///
551    /// For instance all of the following are valid:
552    ///
553    /// ```rust,no_run
554    /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
555    /// # let mut con = client.get_connection().unwrap();
556    /// redis::cmd("SET").arg(&["my_key", "my_value"]);
557    /// redis::cmd("SET").arg("my_key").arg(42);
558    /// redis::cmd("SET").arg("my_key").arg(b"my_value");
559    /// ```
560    #[inline]
561    pub fn arg<T: ToRedisArgs>(&mut self, arg: T) -> &mut Self {
562        arg.write_redis_args(self);
563        self
564    }
565
566    /// Takes the command out of the mutable reference and returns it as a value
567    ///
568    /// The referenced command is left empty.
569    pub fn take(&mut self) -> Self {
570        std::mem::take(self)
571    }
572
573    /// Works similar to `arg` but adds a cursor argument.
574    ///
575    /// This is always an integer and also flips the command implementation to support a
576    /// different mode for the iterators where the iterator will ask for
577    /// another batch of items when the local data is exhausted.
578    /// Calling this function more than once will overwrite the previous cursor with the latest set value.
579    ///
580    /// ```rust,no_run
581    /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
582    /// # let mut con = client.get_connection().unwrap();
583    /// let mut cmd = redis::cmd("SSCAN");
584    /// let mut iter : redis::Iter<isize> =
585    ///     cmd.arg("my_set").cursor_arg(0).clone().iter(&mut con).unwrap();
586    /// for x in iter {
587    ///     // do something with the item
588    /// }
589    /// ```
590    #[inline]
591    pub fn cursor_arg(&mut self, cursor: u64) -> &mut Self {
592        self.cursor = Some(cursor);
593        self.args.push(Arg::Cursor);
594        self
595    }
596
597    /// Returns the packed command as a byte vector.
598    ///
599    /// This is a wrapper around [`write_packed_command`] that creates a [`Vec`] to write to.
600    ///
601    /// [`write_packed_command`]: Self::write_packed_command
602    #[inline]
603    pub fn get_packed_command(&self) -> Vec<u8> {
604        let mut cmd = Vec::new();
605        if self.is_empty() {
606            return cmd;
607        }
608        self.write_packed_command(&mut cmd);
609        cmd
610    }
611
612    /// Writes the packed command to `dst`.
613    ///
614    /// This will *append* the packed command.
615    ///
616    /// See also [`get_packed_command`].
617    ///
618    /// [`get_packed_command`]: Self::get_packed_command.
619    #[inline]
620    pub fn write_packed_command(&self, dst: &mut Vec<u8>) {
621        write_command_to_vec(dst, self.args_iter(), self.cursor.unwrap_or(0));
622    }
623
624    pub(crate) fn write_packed_command_preallocated(&self, cmd: &mut Vec<u8>) {
625        write_command(cmd, self.args_iter(), self.cursor.unwrap_or(0));
626    }
627
628    /// Returns true if the command is in scan mode.
629    #[inline]
630    pub fn in_scan_mode(&self) -> bool {
631        self.cursor.is_some()
632    }
633
634    /// Sends the command as query to the connection and converts the
635    /// result to the target redis value.  This is the general way how
636    /// you can retrieve data.
637    #[inline]
638    pub fn query<T: FromRedisValue>(&self, con: &mut dyn ConnectionLike) -> RedisResult<T> {
639        match con.req_command(self) {
640            Ok(val) => Ok(from_redis_value(val.extract_error()?)?),
641            Err(e) => Err(e),
642        }
643    }
644
645    /// Async version of `query`.
646    #[inline]
647    #[cfg(feature = "aio")]
648    pub async fn query_async<T: FromRedisValue>(
649        &self,
650        con: &mut impl crate::aio::ConnectionLike,
651    ) -> RedisResult<T> {
652        let val = con.req_packed_command(self).await?;
653        Ok(from_redis_value(val.extract_error()?)?)
654    }
655
656    /// Sets the cursor and converts the passed value to a batch used by the
657    /// iterators.
658    fn set_cursor_and_get_batch<T: FromRedisValue>(
659        &mut self,
660        value: crate::Value,
661    ) -> RedisResult<Vec<Result<T, ParsingError>>> {
662        let (cursor, values) = if value.looks_like_cursor() {
663            let (cursor, values) = from_redis_value::<(u64, _)>(value)?;
664            (cursor, values)
665        } else {
666            (0, from_redis_value(value)?)
667        };
668
669        self.cursor = Some(cursor);
670
671        Ok(T::from_each_redis_values(values))
672    }
673
674    /// Similar to `query()` but returns an iterator over the items of the
675    /// bulk result or iterator.  In normal mode this is not in any way more
676    /// efficient than just querying into a `Vec<T>` as it's internally
677    /// implemented as buffering into a vector.  This however is useful when
678    /// `cursor_arg` was used in which case the iterator will query for more
679    /// items until the server side cursor is exhausted.
680    ///
681    /// This is useful for commands such as `SSCAN`, `SCAN` and others.
682    ///
683    /// One speciality of this function is that it will check if the response
684    /// looks like a cursor or not and always just looks at the payload.
685    /// This way you can use the function the same for responses in the
686    /// format of `KEYS` (just a list) as well as `SSCAN` (which returns a
687    /// tuple of cursor and list).
688    #[inline]
689    pub fn iter<T: FromRedisValue>(
690        mut self,
691        con: &mut dyn ConnectionLike,
692    ) -> RedisResult<Iter<'_, T>> {
693        let rv = con.req_command(&self)?;
694
695        let batch = self.set_cursor_and_get_batch(rv)?;
696
697        Ok(Iter {
698            iter: CheckedIter {
699                batch: batch.into_iter(),
700                con,
701                cmd: self,
702            },
703        })
704    }
705
706    /// Similar to `iter()` but returns an AsyncIter over the items of the
707    /// bulk result or iterator.  A [futures::Stream](https://docs.rs/futures/0.3.3/futures/stream/trait.Stream.html)
708    /// is implemented on AsyncIter. In normal mode this is not in any way more
709    /// efficient than just querying into a `Vec<T>` as it's internally
710    /// implemented as buffering into a vector.  This however is useful when
711    /// `cursor_arg` was used in which case the stream will query for more
712    /// items until the server side cursor is exhausted.
713    ///
714    /// This is useful for commands such as `SSCAN`, `SCAN` and others in async contexts.
715    ///
716    /// One speciality of this function is that it will check if the response
717    /// looks like a cursor or not and always just looks at the payload.
718    /// This way you can use the function the same for responses in the
719    /// format of `KEYS` (just a list) as well as `SSCAN` (which returns a
720    /// tuple of cursor and list).
721    #[cfg(feature = "aio")]
722    #[inline]
723    pub async fn iter_async<'a, T: FromRedisValue + 'a>(
724        mut self,
725        con: &'a mut (dyn AsyncConnection + Send),
726    ) -> RedisResult<AsyncIter<'a, T>> {
727        let rv = con.req_packed_command(&self).await?;
728
729        let batch = self.set_cursor_and_get_batch(rv)?;
730
731        Ok(AsyncIter {
732            inner: IterOrFuture::Iter(AsyncIterInner {
733                batch: batch.into_iter(),
734                con,
735                cmd: self,
736            }),
737        })
738    }
739
740    /// This is an alternative to `query`` that can be used if you want to be able to handle a
741    /// command's success or failure but don't care about the command's response. For example,
742    /// this is useful for "SET" commands for which the response's content is not important.
743    /// It avoids the need to define generic bounds for ().
744    #[inline]
745    pub fn exec(&self, con: &mut dyn ConnectionLike) -> RedisResult<()> {
746        self.query::<()>(con)
747    }
748
749    /// This is an alternative to `query_async` that can be used if you want to be able to handle a
750    /// command's success or failure but don't care about the command's response. For example,
751    /// this is useful for "SET" commands for which the response's content is not important.
752    /// It avoids the need to define generic bounds for ().
753    #[cfg(feature = "aio")]
754    pub async fn exec_async(&self, con: &mut impl crate::aio::ConnectionLike) -> RedisResult<()> {
755        self.query_async::<()>(con).await
756    }
757
758    /// Returns an iterator over the arguments in this command (including the command name itself)
759    pub fn args_iter(&self) -> impl Clone + ExactSizeIterator<Item = Arg<&[u8]>> {
760        let mut prev = 0;
761        self.args.iter().map(move |arg| match *arg {
762            Arg::Simple(i) => {
763                let arg = Arg::Simple(&self.data[prev..i]);
764                prev = i;
765                arg
766            }
767
768            Arg::Cursor => Arg::Cursor,
769        })
770    }
771
772    // Get a reference to the argument at `idx`
773    #[cfg(any(feature = "cluster", feature = "cache-aio"))]
774    pub(crate) fn arg_idx(&self, idx: usize) -> Option<&[u8]> {
775        if idx >= self.args.len() {
776            return None;
777        }
778
779        let start = if idx == 0 {
780            0
781        } else {
782            match self.args[idx - 1] {
783                Arg::Simple(n) => n,
784                _ => 0,
785            }
786        };
787        let end = match self.args[idx] {
788            Arg::Simple(n) => n,
789            _ => 0,
790        };
791        if start == 0 && end == 0 {
792            return None;
793        }
794        Some(&self.data[start..end])
795    }
796
797    /// Client won't read and wait for results. Currently only used for Pub/Sub commands in RESP3.
798    ///
799    /// This is mostly set internally. The user can set it if they know that a certain command doesn't return a response, or if they use an async connection and don't want to wait for the server response.
800    /// For sync connections, setting this wrongly can affect the connection's correctness, and should be avoided.
801    #[inline]
802    pub fn set_no_response(&mut self, nr: bool) -> &mut Self {
803        self.no_response = nr;
804        self
805    }
806
807    /// Check whether command's result will be waited for.
808    #[inline]
809    pub fn is_no_response(&self) -> bool {
810        self.no_response
811    }
812
813    /// Changes caching behaviour for this specific command.
814    #[cfg(feature = "cache-aio")]
815    #[cfg_attr(docsrs, doc(cfg(feature = "cache-aio")))]
816    pub fn set_cache_config(&mut self, command_cache_config: CommandCacheConfig) -> &mut Self {
817        self.cache = Some(command_cache_config);
818        self
819    }
820
821    #[cfg(feature = "cache-aio")]
822    #[inline]
823    pub(crate) fn get_cache_config(&self) -> &Option<CommandCacheConfig> {
824        &self.cache
825    }
826
827    pub(crate) fn is_empty(&self) -> bool {
828        self.args.is_empty()
829    }
830}
831
832/// Shortcut function to creating a command with a single argument.
833///
834/// The first argument of a redis command is always the name of the command
835/// which needs to be a string.  This is the recommended way to start a
836/// command pipe.
837///
838/// ```rust
839/// redis::cmd("PING");
840/// ```
841pub fn cmd(name: &str) -> Cmd {
842    let mut rv = Cmd::new();
843    rv.arg(name);
844    rv
845}
846
847/// Packs a bunch of commands into a request.
848///
849/// This is generally a quite useless function as this functionality is
850/// nicely wrapped through the `Cmd` object, but in some cases it can be
851/// useful.  The return value of this can then be send to the low level
852/// `ConnectionLike` methods.
853///
854/// Example:
855///
856/// ```rust
857/// # use redis::ToRedisArgs;
858/// let mut args = vec![];
859/// args.extend("SET".to_redis_args());
860/// args.extend("my_key".to_redis_args());
861/// args.extend(42.to_redis_args());
862/// let cmd = redis::pack_command(&args);
863/// assert_eq!(cmd, b"*3\r\n$3\r\nSET\r\n$6\r\nmy_key\r\n$2\r\n42\r\n".to_vec());
864/// ```
865pub fn pack_command(args: &[Vec<u8>]) -> Vec<u8> {
866    encode_command(args.iter().map(|x| Arg::Simple(&x[..])), 0)
867}
868
869/// Shortcut for creating a new pipeline.
870pub fn pipe() -> Pipeline {
871    Pipeline::new()
872}
873
874#[cfg(test)]
875mod tests {
876    use super::*;
877    #[cfg(feature = "bytes")]
878    use bytes::BufMut;
879
880    fn args_iter_to_str(cmd: &Cmd) -> Vec<String> {
881        cmd.args_iter()
882            .map(|arg| match arg {
883                Arg::Simple(bytes) => String::from_utf8(bytes.to_vec()).unwrap(),
884                Arg::Cursor => "CURSOR".to_string(),
885            })
886            .collect()
887    }
888
889    fn assert_arg_equality(c1: &Cmd, c2: &Cmd) {
890        let v1: Vec<_> = c1.args_iter().collect::<Vec<_>>();
891        let v2: Vec<_> = c2.args_iter().collect::<Vec<_>>();
892        assert_eq!(
893            v1,
894            v2,
895            "{:?} - {:?}",
896            args_iter_to_str(c1),
897            args_iter_to_str(c2)
898        );
899    }
900
901    fn assert_practical_equivalent(c1: Cmd, c2: Cmd) {
902        assert_eq!(c1.get_packed_command(), c2.get_packed_command());
903        assert_arg_equality(&c1, &c2);
904    }
905
906    #[test]
907    fn test_cmd_packed_command_simple_args() {
908        let args: &[&[u8]] = &[b"phone", b"barz"];
909        let mut cmd = cmd("key");
910        cmd.write_arg_fmt("value");
911        cmd.arg(42).arg(args);
912
913        let packed_command = cmd.get_packed_command();
914        assert_eq!(cmd_len(&cmd), packed_command.len());
915        assert_eq!(
916            packed_command,
917            b"*5\r\n$3\r\nkey\r\n$5\r\nvalue\r\n$2\r\n42\r\n$5\r\nphone\r\n$4\r\nbarz\r\n",
918            "{}",
919            String::from_utf8(packed_command.clone()).unwrap()
920        );
921        let args_vec: Vec<&[u8]> = vec![b"key", b"value", b"42", b"phone", b"barz"];
922        let args_vec: Vec<_> = args_vec.into_iter().map(Arg::Simple).collect();
923        assert_eq!(cmd.args_iter().collect::<Vec<_>>(), args_vec);
924    }
925
926    #[test]
927    fn test_cmd_packed_command_with_cursor() {
928        let args: &[&[u8]] = &[b"phone", b"barz"];
929        let mut cmd = cmd("key");
930        cmd.arg("value").arg(42).arg(args).cursor_arg(512);
931
932        let packed_command = cmd.get_packed_command();
933        assert_eq!(cmd_len(&cmd), packed_command.len());
934        assert_eq!(
935            packed_command,
936            b"*6\r\n$3\r\nkey\r\n$5\r\nvalue\r\n$2\r\n42\r\n$5\r\nphone\r\n$4\r\nbarz\r\n$3\r\n512\r\n",
937            "{}",
938            String::from_utf8(packed_command.clone()).unwrap()
939        );
940        let args_vec: Vec<&[u8]> = vec![b"key", b"value", b"42", b"phone", b"barz"];
941        let args_vec: Vec<_> = args_vec
942            .into_iter()
943            .map(Arg::Simple)
944            .chain(std::iter::once(Arg::Cursor))
945            .collect();
946        assert_eq!(cmd.args_iter().collect::<Vec<_>>(), args_vec);
947    }
948
949    #[test]
950    fn test_cmd_clean() {
951        let mut cmd = cmd("key");
952        cmd.arg("value")
953            .cursor_arg(24)
954            .set_no_response(true)
955            .clear();
956
957        // Everything should be reset, but the capacity should still be there
958        assert!(cmd.data.is_empty());
959        assert!(cmd.data.capacity() > 0);
960        assert!(cmd.is_empty());
961        assert!(cmd.args.capacity() > 0);
962        assert_eq!(cmd.cursor, None);
963        assert!(!cmd.no_response);
964        assert_practical_equivalent(cmd, Cmd::new());
965    }
966
967    #[test]
968    #[cfg(feature = "cache-aio")]
969    fn test_cmd_clean_cache_aio() {
970        let mut cmd = cmd("key");
971        cmd.arg("value")
972            .cursor_arg(24)
973            .set_cache_config(crate::CommandCacheConfig::default())
974            .set_no_response(true)
975            .clear();
976
977        // Everything should be reset, but the capacity should still be there
978        assert!(cmd.data.is_empty());
979        assert!(cmd.data.capacity() > 0);
980        assert!(cmd.is_empty());
981        assert!(cmd.args.capacity() > 0);
982        assert_eq!(cmd.cursor, None);
983        assert!(!cmd.no_response);
984        assert!(cmd.cache.is_none());
985    }
986
987    #[test]
988    fn test_cmd_writer_for_next_arg() {
989        // Test that a write split across multiple calls to `write` produces the
990        // same result as a single call to `write_arg`
991        let mut c1 = Cmd::new();
992        {
993            let mut c1_writer = c1.writer_for_next_arg();
994            c1_writer.write_all(b"foo").unwrap();
995            c1_writer.write_all(b"bar").unwrap();
996            c1_writer.flush().unwrap();
997        }
998
999        let mut c2 = Cmd::new();
1000        c2.write_arg(b"foobar");
1001
1002        assert_practical_equivalent(c1, c2);
1003    }
1004
1005    // Test that multiple writers to the same command produce the same
1006    // result as the same multiple calls to `write_arg`
1007    #[test]
1008    fn test_cmd_writer_for_next_arg_multiple() {
1009        let mut c1 = Cmd::new();
1010        {
1011            let mut c1_writer = c1.writer_for_next_arg();
1012            c1_writer.write_all(b"foo").unwrap();
1013            c1_writer.write_all(b"bar").unwrap();
1014            c1_writer.flush().unwrap();
1015        }
1016        {
1017            let mut c1_writer = c1.writer_for_next_arg();
1018            c1_writer.write_all(b"baz").unwrap();
1019            c1_writer.write_all(b"qux").unwrap();
1020            c1_writer.flush().unwrap();
1021        }
1022
1023        let mut c2 = Cmd::new();
1024        c2.write_arg(b"foobar");
1025        c2.write_arg(b"bazqux");
1026
1027        assert_practical_equivalent(c1, c2);
1028    }
1029
1030    // Test that an "empty" write produces the equivalent to `write_arg(b"")`
1031    #[test]
1032    fn test_cmd_writer_for_next_arg_empty() {
1033        let mut c1 = Cmd::new();
1034        {
1035            let mut c1_writer = c1.writer_for_next_arg();
1036            c1_writer.flush().unwrap();
1037        }
1038
1039        let mut c2 = Cmd::new();
1040        c2.write_arg(b"");
1041
1042        assert_practical_equivalent(c1, c2);
1043    }
1044
1045    #[cfg(feature = "bytes")]
1046    /// Test that a write split across multiple calls to `write` produces the
1047    /// same result as a single call to `write_arg`
1048    #[test]
1049    fn test_cmd_bufmut_for_next_arg() {
1050        let mut c1 = Cmd::new();
1051        {
1052            let mut c1_writer = c1.bufmut_for_next_arg(6);
1053            c1_writer.put_slice(b"foo");
1054            c1_writer.put_slice(b"bar");
1055        }
1056
1057        let mut c2 = Cmd::new();
1058        c2.write_arg(b"foobar");
1059
1060        assert_practical_equivalent(c1, c2);
1061    }
1062
1063    #[cfg(feature = "bytes")]
1064    /// Test that multiple writers to the same command produce the same
1065    /// result as the same multiple calls to `write_arg`
1066    #[test]
1067    fn test_cmd_bufmut_for_next_arg_multiple() {
1068        let mut c1 = Cmd::new();
1069        {
1070            let mut c1_writer = c1.bufmut_for_next_arg(6);
1071            c1_writer.put_slice(b"foo");
1072            c1_writer.put_slice(b"bar");
1073        }
1074        {
1075            let mut c1_writer = c1.bufmut_for_next_arg(6);
1076            c1_writer.put_slice(b"baz");
1077            c1_writer.put_slice(b"qux");
1078        }
1079
1080        let mut c2 = Cmd::new();
1081        c2.write_arg(b"foobar");
1082        c2.write_arg(b"bazqux");
1083
1084        assert_practical_equivalent(c1, c2);
1085    }
1086
1087    #[cfg(feature = "bytes")]
1088    /// Test that an "empty" write produces the equivalent to `write_arg(b"")`
1089    #[test]
1090    fn test_cmd_bufmut_for_next_arg_empty() {
1091        let mut c1 = Cmd::new();
1092        {
1093            let _c1_writer = c1.bufmut_for_next_arg(0);
1094        }
1095
1096        let mut c2 = Cmd::new();
1097        c2.write_arg(b"");
1098
1099        assert_practical_equivalent(c1, c2);
1100    }
1101
1102    #[test]
1103    #[cfg(feature = "cluster")]
1104    fn test_cmd_arg_idx() {
1105        let mut c = Cmd::new();
1106        assert_eq!(c.arg_idx(0), None);
1107
1108        c.arg("SET");
1109        assert_eq!(c.arg_idx(0), Some(&b"SET"[..]));
1110        assert_eq!(c.arg_idx(1), None);
1111
1112        c.arg("foo").arg("42");
1113        assert_eq!(c.arg_idx(1), Some(&b"foo"[..]));
1114        assert_eq!(c.arg_idx(2), Some(&b"42"[..]));
1115        assert_eq!(c.arg_idx(3), None);
1116        assert_eq!(c.arg_idx(4), None);
1117    }
1118}