redis_protocol/resp3/
utils.rs

1use crate::resp3::types::*;
2use crate::types::{RedisProtocolError, RedisProtocolErrorKind};
3use crate::utils::{digits_in_number, PATTERN_PUBSUB_PREFIX, PUBSUB_PREFIX, PUBSUB_PUSH_PREFIX};
4use alloc::borrow::Cow;
5use alloc::collections::VecDeque;
6use alloc::format;
7use alloc::string::ToString;
8use alloc::vec::Vec;
9use bytes::BytesMut;
10use cookie_factory::GenError;
11
12#[cfg(feature = "std")]
13use std::collections::{HashMap, HashSet};
14
15#[cfg(feature = "hashbrown")]
16use hashbrown::{HashMap, HashSet};
17
18#[cfg(feature = "index-map")]
19use indexmap::{IndexMap, IndexSet};
20
21pub const BOOLEAN_ENCODE_LEN: usize = 4;
22
23#[cfg(not(feature = "index-map"))]
24pub fn new_set<K>(capacity: Option<usize>) -> HashSet<K> {
25  if let Some(capacity) = capacity {
26    HashSet::with_capacity(capacity)
27  } else {
28    HashSet::new()
29  }
30}
31
32#[cfg(feature = "index-map")]
33pub fn new_set<K>(capacity: Option<usize>) -> IndexSet<K> {
34  if let Some(capacity) = capacity {
35    IndexSet::with_capacity(capacity)
36  } else {
37    IndexSet::new()
38  }
39}
40
41#[cfg(not(feature = "index-map"))]
42pub fn new_map<K, V>(capacity: Option<usize>) -> HashMap<K, V> {
43  if let Some(capacity) = capacity {
44    HashMap::with_capacity(capacity)
45  } else {
46    HashMap::new()
47  }
48}
49
50#[cfg(feature = "index-map")]
51pub fn new_map<K, V>(capacity: Option<usize>) -> IndexMap<K, V> {
52  if let Some(capacity) = capacity {
53    IndexMap::with_capacity(capacity)
54  } else {
55    IndexMap::new()
56  }
57}
58
59#[cfg(feature = "index-map")]
60pub fn hashmap_to_frame_map(data: HashMap<Frame, Frame>) -> FrameMap {
61  let mut out = IndexMap::with_capacity(data.len());
62  for (key, value) in data.into_iter() {
63    let _ = out.insert(key, value);
64  }
65
66  out
67}
68
69#[cfg(not(feature = "index-map"))]
70pub fn hashmap_to_frame_map(data: HashMap<Frame, Frame>) -> FrameMap {
71  data
72}
73
74#[cfg(feature = "index-map")]
75pub fn hashset_to_frame_set(data: HashSet<Frame>) -> FrameSet {
76  let mut out = IndexSet::with_capacity(data.len());
77  for key in data.into_iter() {
78    let _ = out.insert(key);
79  }
80
81  out
82}
83
84#[cfg(not(feature = "index-map"))]
85pub fn hashset_to_frame_set(data: HashSet<Frame>) -> FrameSet {
86  data
87}
88
89pub fn blobstring_encode_len(b: &[u8]) -> usize {
90  1 + digits_in_number(b.len()) + 2 + b.len() + 2
91}
92
93pub fn array_or_push_encode_len(frames: &Vec<Frame>) -> Result<usize, GenError> {
94  let mut total_len = 1 + digits_in_number(frames.len()) + 2;
95
96  for frame in frames.iter() {
97    total_len += encode_len(frame)?;
98  }
99  Ok(total_len)
100}
101
102pub fn bignumber_encode_len(b: &[u8]) -> usize {
103  1 + b.len() + 2
104}
105
106pub fn simplestring_encode_len(s: &[u8]) -> usize {
107  1 + s.len() + 2
108}
109
110pub fn verbatimstring_encode_len(format: &VerbatimStringFormat, data: &[u8]) -> usize {
111  // prefix, data len + format len, crlf, format, colon, data, crlf
112  1 + digits_in_number(data.len() + format.encode_len()) + 2 + format.encode_len() + data.len() + 2
113}
114
115pub fn number_encode_len(i: &i64) -> usize {
116  let prefix = if *i < 0 { 1 } else { 0 };
117  let as_usize = if *i < 0 { (*i * -1) as usize } else { *i as usize };
118
119  1 + digits_in_number(as_usize) + 2 + prefix
120}
121
122pub fn double_encode_len(f: &f64) -> Result<usize, GenError> {
123  if f.is_nan() {
124    Err(GenError::CustomError(2))
125  } else if f.is_infinite() {
126    let inf_len = if f.is_sign_negative() {
127      NEG_INFINITY.as_bytes().len()
128    } else {
129      INFINITY.as_bytes().len()
130    };
131
132    // comma, inf|-inf, CRLF
133    Ok(1 + inf_len + 2)
134  } else {
135    // TODO there's probably a more clever way to do this
136    Ok(1 + f.to_string().as_bytes().len() + 2)
137  }
138}
139
140pub fn map_encode_len(map: &FrameMap) -> Result<usize, GenError> {
141  let mut total_len = 1 + digits_in_number(map.len()) + 2;
142
143  for (key, value) in map.iter() {
144    total_len += encode_len(key)? + encode_len(value)?;
145  }
146  Ok(total_len)
147}
148
149pub fn set_encode_len(set: &FrameSet) -> Result<usize, GenError> {
150  let mut total_len = 1 + digits_in_number(set.len()) + 2;
151
152  for frame in set.iter() {
153    total_len += encode_len(frame)?;
154  }
155  Ok(total_len)
156}
157
158pub fn hello_encode_len(_version: &RespVersion, auth: &Option<Auth>) -> usize {
159  let mut total_len = HELLO.as_bytes().len() + 3;
160
161  if let Some(ref auth) = *auth {
162    total_len += AUTH.as_bytes().len() + 1 + auth.username.as_bytes().len() + 1 + auth.password.as_bytes().len() + 1;
163  }
164  total_len
165}
166
167pub fn attribute_encode_len(attributes: &Option<Attributes>) -> Result<usize, GenError> {
168  let attribute_len = match attributes {
169    Some(attributes) => map_encode_len(attributes)?,
170    None => 0,
171  };
172
173  Ok(attribute_len)
174}
175
176pub fn is_normal_pubsub(frames: &Vec<Frame>) -> bool {
177  (frames.len() == 4 || frames.len() == 5)
178    && frames[0].as_str().map(|s| s == PUBSUB_PUSH_PREFIX).unwrap_or(false)
179    && frames[1].as_str().map(|s| s == PUBSUB_PREFIX).unwrap_or(false)
180}
181
182pub fn is_pattern_pubsub(frames: &Vec<Frame>) -> bool {
183  (frames.len() == 4 || frames.len() == 5)
184    && frames[0].as_str().map(|s| s == PUBSUB_PUSH_PREFIX).unwrap_or(false)
185    && frames[1].as_str().map(|s| s == PATTERN_PUBSUB_PREFIX).unwrap_or(false)
186}
187
188/// Returns the number of bytes necessary to represent the frame and any associated attributes.
189pub fn encode_len(data: &Frame) -> Result<usize, GenError> {
190  use crate::resp3::types::Frame::*;
191
192  let total_len = match *data {
193    Array {
194      ref data,
195      ref attributes,
196    } => array_or_push_encode_len(data)? + attribute_encode_len(attributes)?,
197    Push {
198      ref data,
199      ref attributes,
200    } => array_or_push_encode_len(data)? + attribute_encode_len(attributes)?,
201    BlobString {
202      ref data,
203      ref attributes,
204    } => blobstring_encode_len(data) + attribute_encode_len(attributes)?,
205    BlobError {
206      ref data,
207      ref attributes,
208    } => blobstring_encode_len(data) + attribute_encode_len(attributes)?,
209    SimpleString {
210      ref data,
211      ref attributes,
212    } => simplestring_encode_len(data) + attribute_encode_len(attributes)?,
213    SimpleError {
214      ref data,
215      ref attributes,
216    } => simplestring_encode_len(data.as_bytes()) + attribute_encode_len(attributes)?,
217    Number {
218      ref data,
219      ref attributes,
220    } => number_encode_len(data) + attribute_encode_len(attributes)?,
221    Double {
222      ref data,
223      ref attributes,
224    } => double_encode_len(data)? + attribute_encode_len(attributes)?,
225    Boolean {
226      data: _,
227      ref attributes,
228    } => BOOLEAN_ENCODE_LEN + attribute_encode_len(attributes)?,
229    VerbatimString {
230      ref data,
231      ref attributes,
232      ref format,
233      ..
234    } => verbatimstring_encode_len(format, data) + attribute_encode_len(attributes)?,
235    Map {
236      ref data,
237      ref attributes,
238    } => map_encode_len(data)? + attribute_encode_len(attributes)?,
239    Set {
240      ref data,
241      ref attributes,
242    } => set_encode_len(data)? + attribute_encode_len(attributes)?,
243    BigNumber {
244      ref data,
245      ref attributes,
246    } => bignumber_encode_len(data) + attribute_encode_len(attributes)?,
247    Hello { ref version, ref auth } => hello_encode_len(version, auth),
248    ChunkedString(ref data) => {
249      if data.is_empty() {
250        END_STREAM_STRING_BYTES.as_bytes().len()
251      } else {
252        blobstring_encode_len(data)
253      }
254    }
255    Null => NULL.as_bytes().len(),
256  };
257
258  Ok(total_len)
259}
260
261/// Return the string representation of a double, accounting for `inf` and `-inf`.
262///
263/// NaN is not checked here.
264pub fn f64_to_redis_string(data: &f64) -> Cow<'static, str> {
265  if data.is_infinite() {
266    if data.is_sign_negative() {
267      Cow::Borrowed(NEG_INFINITY)
268    } else {
269      Cow::Borrowed(INFINITY)
270    }
271  } else {
272    Cow::Owned(data.to_string())
273  }
274}
275
276pub fn reconstruct_blobstring(
277  frames: VecDeque<Frame>,
278  attributes: Option<Attributes>,
279) -> Result<Frame, RedisProtocolError> {
280  let total_len = frames.iter().fold(0, |m, f| m + f.len());
281  let mut data = BytesMut::with_capacity(total_len);
282
283  for frame in frames.into_iter() {
284    data.extend_from_slice(match frame {
285      Frame::ChunkedString(ref inner) => inner,
286      Frame::BlobString { ref data, .. } => &data,
287      _ => {
288        return Err(RedisProtocolError::new(
289          RedisProtocolErrorKind::DecodeError,
290          format!("Cannot create blob string from {:?}", frame.kind()),
291        ))
292      }
293    });
294  }
295
296  Ok(Frame::BlobString {
297    data: data.freeze(),
298    attributes,
299  })
300}
301
302pub fn reconstruct_array(frames: VecDeque<Frame>, attributes: Option<Attributes>) -> Result<Frame, RedisProtocolError> {
303  let mut data = Vec::with_capacity(frames.len());
304
305  for frame in frames.into_iter() {
306    data.push(frame);
307  }
308  Ok(Frame::Array { data, attributes })
309}
310
311pub fn reconstruct_map(
312  mut frames: VecDeque<Frame>,
313  attributes: Option<Attributes>,
314) -> Result<Frame, RedisProtocolError> {
315  if frames.is_empty() {
316    return Ok(Frame::Map {
317      data: new_map(None),
318      attributes,
319    });
320  }
321
322  if frames.len() % 2 != 0 {
323    return Err(RedisProtocolError::new(
324      RedisProtocolErrorKind::DecodeError,
325      "Map must have an even number of inner frames.",
326    ));
327  }
328
329  let mut data = new_map(Some(frames.len() / 2));
330  while frames.len() > 0 {
331    let value = frames.pop_back().unwrap();
332    let key = match frames.pop_back() {
333      Some(f) => f,
334      None => {
335        return Err(RedisProtocolError::new(
336          RedisProtocolErrorKind::DecodeError,
337          "Missing map key.",
338        ))
339      }
340    };
341
342    if !key.can_hash() {
343      return Err(RedisProtocolError::new(
344        RedisProtocolErrorKind::DecodeError,
345        format!("{:?} cannot be used as hash key.", key.kind()),
346      ));
347    }
348
349    data.insert(key, value);
350  }
351
352  Ok(Frame::Map { data, attributes })
353}
354
355pub fn reconstruct_set(frames: VecDeque<Frame>, attributes: Option<Attributes>) -> Result<Frame, RedisProtocolError> {
356  let mut data = new_set(Some(frames.len()));
357
358  for frame in frames.into_iter() {
359    if !frame.can_hash() {
360      return Err(RedisProtocolError::new(
361        RedisProtocolErrorKind::DecodeError,
362        format!("{:?} cannot be used as hash key.", frame.kind()),
363      ));
364    }
365
366    data.insert(frame);
367  }
368  Ok(Frame::Set { data, attributes })
369}
370
371#[cfg(test)]
372mod tests {
373  use alloc::vec;
374  use crate::resp3::types::*;
375  use crate::resp3::utils::{encode_len, new_map, new_set};
376
377  fn create_attributes() -> (FrameMap, usize) {
378    let mut out = new_map(None);
379    let key = Frame::SimpleString {
380      data: "foo".into(),
381      attributes: None,
382    };
383    let value = Frame::Number {
384      data: 42,
385      attributes: None,
386    };
387    out.insert(key, value);
388
389    (out, 1 + 1 + 2 + 6 + 5)
390  }
391
392  #[test]
393  fn should_reconstruct_blobstring() {
394    let mut streamed_frame = StreamedFrame::new(FrameKind::BlobString);
395    streamed_frame.add_frame(Frame::ChunkedString("foo".as_bytes().into()));
396    streamed_frame.add_frame(Frame::ChunkedString("bar".as_bytes().into()));
397    streamed_frame.add_frame(Frame::ChunkedString("baz".as_bytes().into()));
398
399    let expected = Frame::BlobString {
400      data: "foobarbaz".as_bytes().into(),
401      attributes: None,
402    };
403    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
404
405    let mut streamed_frame = StreamedFrame::new(FrameKind::BlobString);
406    streamed_frame.add_frame(Frame::ChunkedString("foo".as_bytes().into()));
407    streamed_frame.add_frame(Frame::ChunkedString("bar".as_bytes().into()));
408    streamed_frame.add_frame(Frame::ChunkedString("baz".as_bytes().into()));
409    let (attributes, _) = create_attributes();
410    streamed_frame.attributes = Some(attributes.clone());
411
412    let expected = Frame::BlobString {
413      data: "foobarbaz".as_bytes().into(),
414      attributes: Some(attributes),
415    };
416    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
417  }
418
419  #[test]
420  fn should_reconstruct_array() {
421    let mut streamed_frame = StreamedFrame::new(FrameKind::Array);
422    streamed_frame.add_frame(Frame::SimpleString {
423      data: "foo".into(),
424      attributes: None,
425    });
426    streamed_frame.add_frame(Frame::Number {
427      data: 42,
428      attributes: None,
429    });
430    streamed_frame.add_frame(Frame::Boolean {
431      data: true,
432      attributes: None,
433    });
434
435    let expected = Frame::Array {
436      data: vec![
437        Frame::SimpleString {
438          data: "foo".into(),
439          attributes: None,
440        },
441        Frame::Number {
442          data: 42,
443          attributes: None,
444        },
445        Frame::Boolean {
446          data: true,
447          attributes: None,
448        },
449      ],
450      attributes: None,
451    };
452    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
453
454    let (attributes, _) = create_attributes();
455    let mut streamed_frame = StreamedFrame::new(FrameKind::Array);
456    streamed_frame.add_frame(Frame::SimpleString {
457      data: "foo".into(),
458      attributes: None,
459    });
460    streamed_frame.add_frame(Frame::Number {
461      data: 42,
462      attributes: Some(attributes.clone()),
463    });
464    streamed_frame.add_frame(Frame::Boolean {
465      data: true,
466      attributes: None,
467    });
468    streamed_frame.attributes = Some(attributes.clone());
469
470    let expected = Frame::Array {
471      data: vec![
472        Frame::SimpleString {
473          data: "foo".into(),
474          attributes: None,
475        },
476        Frame::Number {
477          data: 42,
478          attributes: Some(attributes.clone()),
479        },
480        Frame::Boolean {
481          data: true,
482          attributes: None,
483        },
484      ],
485      attributes: Some(attributes),
486    };
487    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
488  }
489
490  #[test]
491  fn should_reconstruct_map() {
492    let mut k1 = Frame::SimpleString {
493      data: "a".into(),
494      attributes: None,
495    };
496    let v1 = Frame::Number {
497      data: 42,
498      attributes: None,
499    };
500    let k2 = Frame::BlobString {
501      data: "b".as_bytes().into(),
502      attributes: None,
503    };
504    let v2 = Frame::Boolean {
505      data: true,
506      attributes: None,
507    };
508
509    let mut streamed_frame = StreamedFrame::new(FrameKind::Map);
510    streamed_frame.add_frame(k1.clone());
511    streamed_frame.add_frame(v1.clone());
512    streamed_frame.add_frame(k2.clone());
513    streamed_frame.add_frame(v2.clone());
514
515    let mut expected = new_map(None);
516    expected.insert(k1.clone(), v1.clone());
517    expected.insert(k2.clone(), v2.clone());
518    let expected = Frame::Map {
519      data: expected,
520      attributes: None,
521    };
522    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
523
524    let (attributes, _) = create_attributes();
525    let _ = k1.add_attributes(attributes.clone()).unwrap();
526
527    let mut streamed_frame = StreamedFrame::new(FrameKind::Map);
528    streamed_frame.add_frame(k1.clone());
529    streamed_frame.add_frame(v1.clone());
530    streamed_frame.add_frame(k2.clone());
531    streamed_frame.add_frame(v2.clone());
532    streamed_frame.attributes = Some(attributes.clone());
533
534    let mut expected = new_map(None);
535    expected.insert(k1.clone(), v1.clone());
536    expected.insert(k2.clone(), v2.clone());
537    let expected = Frame::Map {
538      data: expected,
539      attributes: Some(attributes),
540    };
541    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
542  }
543
544  #[test]
545  #[should_panic]
546  fn should_reconstruct_map_odd_elements() {
547    let k1 = Frame::SimpleString {
548      data: "a".into(),
549      attributes: None,
550    };
551    let v1 = Frame::Number {
552      data: 42,
553      attributes: None,
554    };
555    let k2 = Frame::BlobString {
556      data: "b".as_bytes().into(),
557      attributes: None,
558    };
559
560    let mut streamed_frame = StreamedFrame::new(FrameKind::Map);
561    streamed_frame.add_frame(k1.clone());
562    streamed_frame.add_frame(v1.clone());
563    streamed_frame.add_frame(k2.clone());
564
565    let _ = streamed_frame.into_frame().unwrap();
566  }
567
568  #[test]
569  fn should_reconstruct_set() {
570    let mut v1 = Frame::SimpleString {
571      data: "a".into(),
572      attributes: None,
573    };
574    let v2 = Frame::Number {
575      data: 42,
576      attributes: None,
577    };
578    let v3 = Frame::BlobString {
579      data: "b".as_bytes().into(),
580      attributes: None,
581    };
582    let v4 = Frame::Boolean {
583      data: true,
584      attributes: None,
585    };
586
587    let mut streamed_frame = StreamedFrame::new(FrameKind::Set);
588    streamed_frame.add_frame(v1.clone());
589    streamed_frame.add_frame(v2.clone());
590    streamed_frame.add_frame(v3.clone());
591    streamed_frame.add_frame(v4.clone());
592
593    let mut expected = new_set(None);
594    expected.insert(v1.clone());
595    expected.insert(v2.clone());
596    expected.insert(v3.clone());
597    expected.insert(v4.clone());
598    let expected = Frame::Set {
599      data: expected,
600      attributes: None,
601    };
602    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
603
604    let (attributes, _) = create_attributes();
605    let _ = v1.add_attributes(attributes.clone()).unwrap();
606
607    let mut streamed_frame = StreamedFrame::new(FrameKind::Set);
608    streamed_frame.add_frame(v1.clone());
609    streamed_frame.add_frame(v2.clone());
610    streamed_frame.add_frame(v3.clone());
611    streamed_frame.add_frame(v4.clone());
612    streamed_frame.attributes = Some(attributes.clone());
613
614    let mut expected = new_set(None);
615    expected.insert(v1);
616    expected.insert(v2);
617    expected.insert(v3);
618    expected.insert(v4);
619    let expected = Frame::Set {
620      data: expected,
621      attributes: Some(attributes),
622    };
623    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
624  }
625
626  #[test]
627  fn should_reconstruct_nested_array() {
628    let mut streamed_frame = StreamedFrame::new(FrameKind::Array);
629    streamed_frame.add_frame(Frame::SimpleString {
630      data: "foo".into(),
631      attributes: None,
632    });
633    streamed_frame.add_frame(Frame::Array {
634      data: vec![
635        Frame::SimpleString {
636          data: "foo".into(),
637          attributes: None,
638        },
639        Frame::Null,
640        Frame::BigNumber {
641          data: "123456789".as_bytes().into(),
642          attributes: None,
643        },
644      ],
645      attributes: None,
646    });
647    streamed_frame.add_frame(Frame::Boolean {
648      data: true,
649      attributes: None,
650    });
651
652    let expected = Frame::Array {
653      data: vec![
654        Frame::SimpleString {
655          data: "foo".into(),
656          attributes: None,
657        },
658        Frame::Array {
659          data: vec![
660            Frame::SimpleString {
661              data: "foo".into(),
662              attributes: None,
663            },
664            Frame::Null,
665            Frame::BigNumber {
666              data: "123456789".as_bytes().into(),
667              attributes: None,
668            },
669          ],
670          attributes: None,
671        },
672        Frame::Boolean {
673          data: true,
674          attributes: None,
675        },
676      ],
677      attributes: None,
678    };
679    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
680
681    let (attributes, _) = create_attributes();
682    let mut streamed_frame = StreamedFrame::new(FrameKind::Array);
683    streamed_frame.add_frame(Frame::SimpleString {
684      data: "foo".into(),
685      attributes: None,
686    });
687    streamed_frame.add_frame(Frame::Array {
688      data: vec![
689        Frame::SimpleString {
690          data: "foo".into(),
691          attributes: None,
692        },
693        Frame::Null,
694        Frame::BigNumber {
695          data: "123456789".as_bytes().into(),
696          attributes: Some(attributes.clone()),
697        },
698      ],
699      attributes: None,
700    });
701    streamed_frame.add_frame(Frame::Boolean {
702      data: true,
703      attributes: Some(attributes.clone()),
704    });
705    streamed_frame.attributes = Some(attributes.clone());
706
707    let expected = Frame::Array {
708      data: vec![
709        Frame::SimpleString {
710          data: "foo".into(),
711          attributes: None,
712        },
713        Frame::Array {
714          data: vec![
715            Frame::SimpleString {
716              data: "foo".into(),
717              attributes: None,
718            },
719            Frame::Null,
720            Frame::BigNumber {
721              data: "123456789".as_bytes().into(),
722              attributes: Some(attributes.clone()),
723            },
724          ],
725          attributes: None,
726        },
727        Frame::Boolean {
728          data: true,
729          attributes: Some(attributes.clone()),
730        },
731      ],
732      attributes: Some(attributes),
733    };
734    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
735  }
736
737  #[test]
738  fn should_reconstruct_nested_map() {
739    let k1 = Frame::SimpleString {
740      data: "a".into(),
741      attributes: None,
742    };
743    let mut v1 = Frame::Number {
744      data: 42,
745      attributes: None,
746    };
747    let k2 = Frame::BlobString {
748      data: "b".as_bytes().into(),
749      attributes: None,
750    };
751    let inner_k1 = Frame::SimpleString {
752      data: "b".into(),
753      attributes: None,
754    };
755    let mut inner_v1 = Frame::BlobString {
756      data: "foobarbaz".as_bytes().into(),
757      attributes: None,
758    };
759    let mut inner_map = new_map(None);
760    inner_map.insert(inner_k1.clone(), inner_v1.clone());
761    let v2 = Frame::Map {
762      data: inner_map,
763      attributes: None,
764    };
765
766    let mut streamed_frame = StreamedFrame::new(FrameKind::Map);
767    streamed_frame.add_frame(k1.clone());
768    streamed_frame.add_frame(v1.clone());
769    streamed_frame.add_frame(k2.clone());
770    streamed_frame.add_frame(v2.clone());
771
772    let mut expected = new_map(None);
773    expected.insert(k1.clone(), v1.clone());
774    expected.insert(k2.clone(), v2.clone());
775    let expected = Frame::Map {
776      data: expected,
777      attributes: None,
778    };
779    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
780
781    let (attributes, _) = create_attributes();
782    let _ = v1.add_attributes(attributes.clone()).unwrap();
783    let _ = inner_v1.add_attributes(attributes.clone()).unwrap();
784    let mut inner_map = new_map(None);
785    inner_map.insert(inner_k1, inner_v1);
786    let v2 = Frame::Map {
787      data: inner_map,
788      attributes: None,
789    };
790
791    let mut streamed_frame = StreamedFrame::new(FrameKind::Map);
792    streamed_frame.add_frame(k1.clone());
793    streamed_frame.add_frame(v1.clone());
794    streamed_frame.add_frame(k2.clone());
795    streamed_frame.add_frame(v2.clone());
796    streamed_frame.attributes = Some(attributes.clone());
797
798    let mut expected = new_map(None);
799    expected.insert(k1.clone(), v1.clone());
800    expected.insert(k2.clone(), v2.clone());
801    let expected = Frame::Map {
802      data: expected,
803      attributes: Some(attributes),
804    };
805    assert_eq!(streamed_frame.into_frame().unwrap(), expected);
806  }
807
808  #[test]
809  fn should_get_encode_len_blobstring() {
810    let mut frame = Frame::BlobString {
811      data: "foobarbaz".as_bytes().into(),
812      attributes: None,
813    };
814    let expected_len = 1 + 1 + 2 + 9 + 2;
815    assert_eq!(encode_len(&frame).unwrap(), expected_len);
816
817    let (attributes, attributes_len) = create_attributes();
818    let _ = frame.add_attributes(attributes).unwrap();
819    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
820  }
821
822  #[test]
823  fn should_get_encode_len_bloberror() {
824    let mut frame = Frame::BlobError {
825      data: "foobarbaz".as_bytes().into(),
826      attributes: None,
827    };
828    let expected_len = 1 + 1 + 2 + 9 + 2;
829    assert_eq!(encode_len(&frame).unwrap(), expected_len);
830
831    let (attributes, attributes_len) = create_attributes();
832    let _ = frame.add_attributes(attributes).unwrap();
833    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
834  }
835
836  #[test]
837  fn should_get_encode_len_bignumber() {
838    let mut frame = Frame::BigNumber {
839      data: "123456789".as_bytes().into(),
840      attributes: None,
841    };
842    let expected_len = 1 + 9 + 2;
843    assert_eq!(encode_len(&frame).unwrap(), expected_len);
844
845    let (attributes, attributes_len) = create_attributes();
846    let _ = frame.add_attributes(attributes).unwrap();
847    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
848  }
849
850  #[test]
851  fn should_get_encode_len_bool() {
852    let mut frame = Frame::Boolean {
853      data: true,
854      attributes: None,
855    };
856    let expected_len = 1 + 1 + 2;
857    assert_eq!(encode_len(&frame).unwrap(), expected_len);
858
859    let (attributes, attributes_len) = create_attributes();
860    let _ = frame.add_attributes(attributes).unwrap();
861    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
862
863    let mut frame = Frame::Boolean {
864      data: false,
865      attributes: None,
866    };
867    let expected_len = 1 + 1 + 2;
868    assert_eq!(encode_len(&frame).unwrap(), expected_len);
869
870    let (attributes, attributes_len) = create_attributes();
871    let _ = frame.add_attributes(attributes).unwrap();
872    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
873  }
874
875  #[test]
876  fn should_get_encode_len_number() {
877    let mut frame = Frame::Number {
878      data: 500,
879      attributes: None,
880    };
881    let expected_len = 1 + 3 + 2;
882    assert_eq!(encode_len(&frame).unwrap(), expected_len);
883
884    let (attributes, attributes_len) = create_attributes();
885    let _ = frame.add_attributes(attributes).unwrap();
886    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
887  }
888
889  #[test]
890  fn should_get_encode_len_negative_number() {
891    let mut frame = Frame::Number {
892      data: -500,
893      attributes: None,
894    };
895    let expected_len = 1 + 4 + 2;
896    assert_eq!(encode_len(&frame).unwrap(), expected_len);
897
898    let (attributes, attributes_len) = create_attributes();
899    let _ = frame.add_attributes(attributes).unwrap();
900    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
901  }
902
903  #[test]
904  fn should_get_encode_len_double() {
905    let mut frame = Frame::Double {
906      data: 500.123,
907      attributes: None,
908    };
909    let expected_len = 1 + 7 + 2;
910    assert_eq!(encode_len(&frame).unwrap(), expected_len);
911
912    let (attributes, attributes_len) = create_attributes();
913    let _ = frame.add_attributes(attributes).unwrap();
914    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
915  }
916
917  #[test]
918  fn should_get_encode_len_negative_double() {
919    let mut frame = Frame::Double {
920      data: -500.123,
921      attributes: None,
922    };
923    let expected_len = 1 + 8 + 2;
924    assert_eq!(encode_len(&frame).unwrap(), expected_len);
925
926    let (attributes, attributes_len) = create_attributes();
927    let _ = frame.add_attributes(attributes).unwrap();
928    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
929  }
930
931  #[test]
932  fn should_get_encode_len_inf_double() {
933    let mut frame = Frame::Double {
934      data: f64::INFINITY,
935      attributes: None,
936    };
937    let expected_len = 1 + 3 + 2;
938    assert_eq!(encode_len(&frame).unwrap(), expected_len);
939
940    let (attributes, attributes_len) = create_attributes();
941    let _ = frame.add_attributes(attributes).unwrap();
942    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
943
944    let mut frame = Frame::Double {
945      data: f64::NEG_INFINITY,
946      attributes: None,
947    };
948    let expected_len = 1 + 4 + 2;
949    assert_eq!(encode_len(&frame).unwrap(), expected_len);
950
951    let (attributes, attributes_len) = create_attributes();
952    let _ = frame.add_attributes(attributes).unwrap();
953    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
954  }
955
956  #[test]
957  fn should_get_encode_len_null() {
958    let frame = Frame::Null;
959    let expected_len = 3;
960    assert_eq!(encode_len(&frame).unwrap(), expected_len);
961  }
962
963  #[test]
964  fn should_get_encode_len_hello() {
965    let frame = Frame::Hello {
966      version: RespVersion::RESP3,
967      auth: None,
968    };
969    let expected_len = 5 + 1 + 1 + 1;
970    assert_eq!(encode_len(&frame).unwrap(), expected_len);
971
972    let frame = Frame::Hello {
973      version: RespVersion::RESP2,
974      auth: None,
975    };
976    let expected_len = 5 + 1 + 1 + 1;
977    assert_eq!(encode_len(&frame).unwrap(), expected_len);
978
979    let frame = Frame::Hello {
980      version: RespVersion::RESP3,
981      auth: Some(Auth {
982        username: "foo".into(),
983        password: "bar".into(),
984      }),
985    };
986    let expected_len = 5 + 1 + 1 + 1 + 4 + 1 + 3 + 1 + 3 + 1;
987    assert_eq!(encode_len(&frame).unwrap(), expected_len);
988  }
989
990  #[test]
991  fn should_get_encode_len_verbatimstring() {
992    let mut frame = Frame::VerbatimString {
993      format: VerbatimStringFormat::Markdown,
994      data: "foobarbaz".into(),
995      attributes: None,
996    };
997    let expected_len = 1 + 2 + 2 + 3 + 1 + 9 + 2;
998    assert_eq!(encode_len(&frame).unwrap(), expected_len);
999
1000    let (attributes, attributes_len) = create_attributes();
1001    let _ = frame.add_attributes(attributes).unwrap();
1002    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
1003
1004    let mut frame = Frame::VerbatimString {
1005      format: VerbatimStringFormat::Text,
1006      data: "foobarbaz".into(),
1007      attributes: None,
1008    };
1009    let expected_len = 1 + 2 + 2 + 3 + 1 + 9 + 2;
1010    assert_eq!(encode_len(&frame).unwrap(), expected_len);
1011
1012    let (attributes, attributes_len) = create_attributes();
1013    let _ = frame.add_attributes(attributes).unwrap();
1014    assert_eq!(encode_len(&frame).unwrap(), expected_len + attributes_len);
1015  }
1016
1017  #[test]
1018  fn should_get_encode_len_chunked_string() {
1019    let frame = Frame::ChunkedString("foobarbaz".as_bytes().into());
1020    let expected_len = 1 + 1 + 2 + 9 + 2;
1021    assert_eq!(encode_len(&frame).unwrap(), expected_len);
1022  }
1023
1024  #[test]
1025  fn should_get_encode_len_end_stream() {
1026    let end_frame = Frame::new_end_stream();
1027    let expected_len = 1 + 1 + 2;
1028    assert_eq!(encode_len(&end_frame).unwrap(), expected_len);
1029  }
1030}