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#[derive(Clone, PartialEq, Debug)]
19#[non_exhaustive]
20pub enum Arg<D> {
21 Simple(D),
23 Cursor,
25}
26
27#[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 pub fn new() -> Self {
51 Self {
52 enable_cache: true,
53 client_side_ttl: None,
54 }
55 }
56
57 pub fn set_enable_cache(mut self, enable_cache: bool) -> Self {
60 self.enable_cache = enable_cache;
61 self
62 }
63
64 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#[derive(Clone)]
79pub struct Cmd {
80 pub(crate) data: Vec<u8>,
81 args: Vec<Arg<usize>>,
83 cursor: Option<u64>,
84 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
107pub 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
120struct 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 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#[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#[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#[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 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 #[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 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
456impl Cmd {
484 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 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 #[cfg(test)]
512 #[allow(dead_code)]
513 pub(crate) fn capacity(&self) -> (usize, usize) {
514 (self.args.capacity(), self.data.capacity())
515 }
516
517 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 #[inline]
561 pub fn arg<T: ToRedisArgs>(&mut self, arg: T) -> &mut Self {
562 arg.write_redis_args(self);
563 self
564 }
565
566 pub fn take(&mut self) -> Self {
570 std::mem::take(self)
571 }
572
573 #[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 #[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 #[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 #[inline]
630 pub fn in_scan_mode(&self) -> bool {
631 self.cursor.is_some()
632 }
633
634 #[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 #[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 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 #[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 #[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 #[inline]
745 pub fn exec(&self, con: &mut dyn ConnectionLike) -> RedisResult<()> {
746 self.query::<()>(con)
747 }
748
749 #[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 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 #[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 #[inline]
802 pub fn set_no_response(&mut self, nr: bool) -> &mut Self {
803 self.no_response = nr;
804 self
805 }
806
807 #[inline]
809 pub fn is_no_response(&self) -> bool {
810 self.no_response
811 }
812
813 #[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
832pub fn cmd(name: &str) -> Cmd {
842 let mut rv = Cmd::new();
843 rv.arg(name);
844 rv
845}
846
847pub fn pack_command(args: &[Vec<u8>]) -> Vec<u8> {
866 encode_command(args.iter().map(|x| Arg::Simple(&x[..])), 0)
867}
868
869pub 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 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 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 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]
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]
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]
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]
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]
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}