redis/
cmd.rs

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/// An argument to a redis command
18#[derive(Clone)]
19pub enum Arg<D> {
20    /// A normal argument
21    Simple(D),
22    /// A cursor argument created from `cursor_arg()`
23    Cursor,
24}
25
26/// CommandCacheConfig is used to define caching behaviour of individual commands.
27/// # Example
28/// ```rust
29/// use std::time::Duration;
30/// use redis::{CommandCacheConfig, Cmd};
31///
32/// let ttl = Duration::from_secs(120); // 2 minutes TTL
33/// let config = CommandCacheConfig::new()
34///     .set_enable_cache(true)
35///     .set_client_side_ttl(ttl);
36/// let command = Cmd::new().arg("GET").arg("key").set_cache_config(config);
37/// ```
38#[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    /// Creates new CommandCacheConfig with enable_cache as true and without client_side_ttl.
49    pub fn new() -> Self {
50        Self {
51            enable_cache: true,
52            client_side_ttl: None,
53        }
54    }
55
56    /// Sets whether the cache should be enabled or not.
57    /// Disabling cache for specific command when using [crate::caching::CacheMode::All] will not work.
58    pub fn set_enable_cache(mut self, enable_cache: bool) -> Self {
59        self.enable_cache = enable_cache;
60        self
61    }
62
63    /// Sets custom client side time to live (TTL).
64    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/// Represents redis commands.
77#[derive(Clone)]
78pub struct Cmd {
79    pub(crate) data: Vec<u8>,
80    // Arg::Simple contains the offset that marks the end of the argument
81    args: Vec<Arg<usize>>,
82    cursor: Option<u64>,
83    // If it's true command's response won't be read from socket. Useful for Pub/Sub.
84    no_response: bool,
85    #[cfg(feature = "cache-aio")]
86    cache: Option<CommandCacheConfig>,
87}
88
89/// Represents a redis iterator.
90pub 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        // we need to do this in a loop until we produce at least one item
103        // or we find the actual end of the iteration.  This is necessary
104        // because with filtering an iterator it is possible that a whole
105        // chunk is not matching the pattern and thus yielding empty results.
106        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/// The inner future of AsyncIter
128#[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/// Represents the state of AsyncIter
136#[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/// Represents a redis iterator that can be used with async connections.
144#[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        // we need to do this in a loop until we produce at least one item
154        // or we find the actual end of the iteration.  This is necessary
155        // because with filtering an iterator it is possible that a whole
156        // chunk is not matching the pattern and thus yielding empty results.
157        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    /// ```rust,no_run
181    /// # use redis::AsyncCommands;
182    /// # async fn scan_set() -> redis::RedisResult<()> {
183    /// # let client = redis::Client::open("redis://127.0.0.1/")?;
184    /// # let mut con = client.get_multiplexed_async_connection().await?;
185    /// let _: () = con.sadd("my_set", 42i32).await?;
186    /// let _: () = con.sadd("my_set", 43i32).await?;
187    /// let mut iter: redis::AsyncIter<i32> = con.sscan("my_set").await?;
188    /// while let Some(element) = iter.next_item().await {
189    ///     assert!(element == 42 || element == 43);
190    /// }
191    /// # Ok(())
192    /// # }
193    /// ```
194    #[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
364/// A command acts as a builder interface to creating encoded redis
365/// requests.  This allows you to easily assemble a packed command
366/// by chaining arguments together.
367///
368/// Basic example:
369///
370/// ```rust
371/// redis::Cmd::new().arg("SET").arg("my_key").arg(42);
372/// ```
373///
374/// There is also a helper function called `cmd` which makes it a
375/// tiny bit shorter:
376///
377/// ```rust
378/// redis::cmd("SET").arg("my_key").arg(42);
379/// ```
380///
381/// Because Rust currently does not have an ideal system
382/// for lifetimes of temporaries, sometimes you need to hold on to
383/// the initially generated command:
384///
385/// ```rust,no_run
386/// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
387/// # let mut con = client.get_connection().unwrap();
388/// let mut cmd = redis::cmd("SMEMBERS");
389/// let mut iter : redis::Iter<i32> = cmd.arg("my_set").clone().iter(&mut con).unwrap();
390/// ```
391impl Cmd {
392    /// Creates a new empty command.
393    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    /// Creates a new empty command, with at least the requested capacity.
405    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    /// Get the capacities for the internal buffers.
417    #[cfg(test)]
418    #[allow(dead_code)]
419    pub(crate) fn capacity(&self) -> (usize, usize) {
420        (self.args.capacity(), self.data.capacity())
421    }
422
423    /// Appends an argument to the command.  The argument passed must
424    /// be a type that implements `ToRedisArgs`.  Most primitive types as
425    /// well as vectors of primitive types implement it.
426    ///
427    /// For instance all of the following are valid:
428    ///
429    /// ```rust,no_run
430    /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
431    /// # let mut con = client.get_connection().unwrap();
432    /// redis::cmd("SET").arg(&["my_key", "my_value"]);
433    /// redis::cmd("SET").arg("my_key").arg(42);
434    /// redis::cmd("SET").arg("my_key").arg(b"my_value");
435    /// ```
436    #[inline]
437    pub fn arg<T: ToRedisArgs>(&mut self, arg: T) -> &mut Cmd {
438        arg.write_redis_args(self);
439        self
440    }
441
442    /// Works similar to `arg` but adds a cursor argument.  This is always
443    /// an integer and also flips the command implementation to support a
444    /// different mode for the iterators where the iterator will ask for
445    /// another batch of items when the local data is exhausted.
446    ///
447    /// ```rust,no_run
448    /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
449    /// # let mut con = client.get_connection().unwrap();
450    /// let mut cmd = redis::cmd("SSCAN");
451    /// let mut iter : redis::Iter<isize> =
452    ///     cmd.arg("my_set").cursor_arg(0).clone().iter(&mut con).unwrap();
453    /// for x in iter {
454    ///     // do something with the item
455    /// }
456    /// ```
457    #[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    /// Returns the packed command as a byte vector.
466    #[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    /// Like `get_packed_command` but replaces the cursor with the
482    /// provided value.  If the command is not in scan mode, `None`
483    /// is returned.
484    #[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    /// Returns true if the command is in scan mode.
494    #[inline]
495    pub fn in_scan_mode(&self) -> bool {
496        self.cursor.is_some()
497    }
498
499    /// Sends the command as query to the connection and converts the
500    /// result to the target redis value.  This is the general way how
501    /// you can retrieve data.
502    #[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    /// Async version of `query`.
511    #[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    /// Similar to `query()` but returns an iterator over the items of the
522    /// bulk result or iterator.  In normal mode this is not in any way more
523    /// efficient than just querying into a `Vec<T>` as it's internally
524    /// implemented as buffering into a vector.  This however is useful when
525    /// `cursor_arg` was used in which case the iterator will query for more
526    /// items until the server side cursor is exhausted.
527    ///
528    /// This is useful for commands such as `SSCAN`, `SCAN` and others.
529    ///
530    /// One speciality of this function is that it will check if the response
531    /// looks like a cursor or not and always just looks at the payload.
532    /// This way you can use the function the same for responses in the
533    /// format of `KEYS` (just a list) as well as `SSCAN` (which returns a
534    /// tuple of cursor and list).
535    #[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    /// Similar to `iter()` but returns an AsyncIter over the items of the
554    /// bulk result or iterator.  A [futures::Stream](https://docs.rs/futures/0.3.3/futures/stream/trait.Stream.html)
555    /// is implemented on AsyncIter. In normal mode this is not in any way more
556    /// efficient than just querying into a `Vec<T>` as it's internally
557    /// implemented as buffering into a vector.  This however is useful when
558    /// `cursor_arg` was used in which case the stream will query for more
559    /// items until the server side cursor is exhausted.
560    ///
561    /// This is useful for commands such as `SSCAN`, `SCAN` and others in async contexts.
562    ///
563    /// One speciality of this function is that it will check if the response
564    /// looks like a cursor or not and always just looks at the payload.
565    /// This way you can use the function the same for responses in the
566    /// format of `KEYS` (just a list) as well as `SSCAN` (which returns a
567    /// tuple of cursor and list).
568    #[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    /// This is a shortcut to `query()` that does not return a value and
597    /// will fail the task if the query fails because of an error.  This is
598    /// mainly useful in examples and for simple commands like setting
599    /// keys.
600    ///
601    /// This is equivalent to a call of query like this:
602    ///
603    /// ```rust,no_run
604    /// # let client = redis::Client::open("redis://127.0.0.1/").unwrap();
605    /// # let mut con = client.get_connection().unwrap();
606    /// redis::cmd("PING").query::<()>(&mut con).unwrap();
607    /// ```
608    #[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    /// This is an alternative to `query`` that can be used if you want to be able to handle a
615    /// command's success or failure but don't care about the command's response. For example,
616    /// this is useful for "SET" commands for which the response's content is not important.
617    /// It avoids the need to define generic bounds for ().
618    #[inline]
619    pub fn exec(&self, con: &mut dyn ConnectionLike) -> RedisResult<()> {
620        self.query::<()>(con)
621    }
622
623    /// This is an alternative to `query_async` that can be used if you want to be able to handle a
624    /// command's success or failure but don't care about the command's response. For example,
625    /// this is useful for "SET" commands for which the response's content is not important.
626    /// It avoids the need to define generic bounds for ().
627    #[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    /// Returns an iterator over the arguments in this command (including the command name itself)
633    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    // Get a reference to the argument at `idx`
647    #[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    /// Client won't read and wait for results. Currently only used for Pub/Sub commands in RESP3.
672    #[inline]
673    pub fn set_no_response(&mut self, nr: bool) -> &mut Cmd {
674        self.no_response = nr;
675        self
676    }
677
678    /// Check whether command's result will be waited for.
679    #[inline]
680    pub fn is_no_response(&self) -> bool {
681        self.no_response
682    }
683
684    /// Changes caching behaviour for this specific command.
685    #[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
699/// Shortcut function to creating a command with a single argument.
700///
701/// The first argument of a redis command is always the name of the command
702/// which needs to be a string.  This is the recommended way to start a
703/// command pipe.
704///
705/// ```rust
706/// redis::cmd("PING");
707/// ```
708pub fn cmd(name: &str) -> Cmd {
709    let mut rv = Cmd::new();
710    rv.arg(name);
711    rv
712}
713
714/// Packs a bunch of commands into a request.
715///
716/// This is generally a quite useless function as this functionality is
717/// nicely wrapped through the `Cmd` object, but in some cases it can be
718/// useful.  The return value of this can then be send to the low level
719/// `ConnectionLike` methods.
720///
721/// Example:
722///
723/// ```rust
724/// # use redis::ToRedisArgs;
725/// let mut args = vec![];
726/// args.extend("SET".to_redis_args());
727/// args.extend("my_key".to_redis_args());
728/// args.extend(42.to_redis_args());
729/// let cmd = redis::pack_command(&args);
730/// 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());
731/// ```
732pub fn pack_command(args: &[Vec<u8>]) -> Vec<u8> {
733    encode_command(args.iter().map(|x| Arg::Simple(&x[..])), 0)
734}
735
736/// Shortcut for creating a new pipeline.
737pub 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        // Test that a write split across multiple calls to `write` produces the
751        // same result as a single call to `write_arg`
752        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 that multiple writers to the same command produce the same
769    // result as the same multiple calls to `write_arg`
770    #[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 that an "empty" write produces the equivalent to `write_arg(b"")`
796    #[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}