deseresp/
types.rs

1//! Contains specific RESP types implemented with custom Serialize/Deserialize
2//! to tell [`Serializer`](crate::Serializer)/[`Deserializer`](crate::Deserializer)
3//! to se/der correctly.
4pub(crate) const SIMPLE_ERROR_TOKEN: &str = "$SimpleError";
5pub(crate) const BLOB_ERROR_TOKEN: &str = "$BulkError";
6pub(crate) const SIMPLE_STRING_TOKEN: &str = "$SimpleString";
7pub(crate) const BLOB_STRING_TOKEN: &str = "$BulkString";
8pub(crate) const ATTRIBUTE_SKIP_TOKEN: &str = "$AttributeSkip";
9pub(crate) const WITH_ATTRIBUTE_TOKEN: &str = "$WithAttribute";
10pub(crate) const PUSH_TOKEN: &str = "$Push";
11pub(crate) const VALUE_TOKEN: &str = "$Value";
12pub(crate) const PUSH_OR_VALUE_TOKEN: &str = "$PushOrValue";
13
14use std::marker::PhantomData;
15
16use serde::{
17    de::{self, DeserializeOwned, Visitor},
18    ser::SerializeTupleStruct,
19    Deserialize, Serialize,
20};
21pub mod owned {
22    //! Contain owned types (String, Vec)
23    use serde::{de::Visitor, Serialize};
24
25    use super::*;
26
27    /// Expects a SimpleError from deserializer,
28    /// Serialize as a RESP SimpleError
29    #[derive(PartialEq, Eq, Debug)]
30    pub struct SimpleError(pub String);
31    /// Expects a BlobError from deserializer,
32    /// Serialize as a RESP BlobError
33    #[derive(PartialEq, Eq, Debug)]
34    pub struct BlobError(pub String);
35    /// Expects a SimpleString from deserializer,
36    /// Serialize as a RESP SimpleString
37    #[derive(PartialEq, Eq, Debug)]
38    pub struct SimpleString(pub String);
39    /// Expects a BlobString from deserializer,
40    /// Serialize as a RESP BlobString
41    #[derive(PartialEq, Eq, Debug)]
42    pub struct BlobString(pub String);
43
44    macro_rules! impl_initializers {
45        ($type_name:ident) => {
46            impl From<String> for $type_name {
47                fn from(s: String) -> Self {
48                    $type_name(s)
49                }
50            }
51            impl From<&str> for $type_name {
52                fn from(s: &str) -> Self {
53                    $type_name(s.to_owned())
54                }
55            }
56        };
57    }
58    impl_initializers!(SimpleError);
59    impl_initializers!(BlobError);
60    impl_initializers!(SimpleString);
61    impl_initializers!(BlobString);
62
63    macro_rules! impl_deserialize {
64        ($type_name:ident: $token:ident => $visitor_name:ident) => {
65            struct $visitor_name;
66            impl<'de> Visitor<'de> for $visitor_name {
67                type Value = $type_name;
68
69                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
70                    write!(formatter, "expecting str")
71                }
72
73                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
74                where
75                    E: serde::de::Error,
76                {
77                    Ok($type_name(v.to_owned()))
78                }
79            }
80            impl<'de> Deserialize<'de> for $type_name {
81                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
82                where
83                    D: serde::Deserializer<'de>,
84                {
85                    deserializer.deserialize_newtype_struct($token, $visitor_name)
86                }
87            }
88        };
89    }
90    impl_deserialize!(SimpleError: SIMPLE_ERROR_TOKEN => SimpleErrorVisitor);
91    impl_deserialize!(BlobError: BLOB_ERROR_TOKEN => BlobErrorVisitor);
92    impl_deserialize!(SimpleString: SIMPLE_STRING_TOKEN => SimpleStringVisitor);
93    impl_deserialize!(BlobString: BLOB_STRING_TOKEN => BlobStringVisitor);
94
95    macro_rules! impl_serialize {
96        ($type_name:ident: $token:ident) => {
97            impl Serialize for $type_name {
98                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
99                where
100                    S: serde::Serializer,
101                {
102                    serializer.serialize_newtype_struct($token, &self.0)
103                }
104            }
105        };
106    }
107    impl_serialize!(SimpleError: SIMPLE_ERROR_TOKEN);
108    impl_serialize!(BlobError: BLOB_ERROR_TOKEN);
109    impl_serialize!(SimpleString: SIMPLE_STRING_TOKEN);
110    impl_serialize!(BlobString: BLOB_STRING_TOKEN);
111}
112
113pub mod borrowed {
114    //! Contain borrowed types (&str, &[])
115    use std::borrow::Cow;
116
117    use serde::{de::Visitor, Serialize};
118
119    use super::*;
120
121    /// Expects a SimpleError from deserializer,
122    /// Serialize as a RESP SimpleError
123    #[derive(PartialEq, Eq, Debug)]
124    pub struct SimpleError<'a>(pub Cow<'a, str>);
125    /// Expects a BlobError from deserializer,
126    /// Serialize as a RESP BlobError
127    #[derive(PartialEq, Eq, Debug)]
128    pub struct BlobError<'a>(pub Cow<'a, str>);
129    /// Expects a SimpleString from deserializer,
130    /// Serialize as a RESP SimpleString
131    #[derive(PartialEq, Eq, Debug)]
132    pub struct SimpleString<'a>(pub Cow<'a, str>);
133    /// Expects a BlobString from deserializer,
134    /// Serialize as a RESP BlobString
135    #[derive(PartialEq, Eq, Debug)]
136    pub struct BlobString<'a>(pub Cow<'a, str>);
137
138    macro_rules! impl_initializers {
139        ($type_name:ident<$lt:lifetime>) => {
140            impl<$lt> From<String> for $type_name<$lt> {
141                fn from(s: String) -> Self {
142                    $type_name(Cow::from(s))
143                }
144            }
145            impl<$lt> From<&$lt str> for $type_name<$lt> {
146                fn from(s: &$lt str) -> Self {
147                    $type_name(Cow::from(s))
148                }
149            }
150        }
151    }
152    impl_initializers!(SimpleError<'a>);
153    impl_initializers!(BlobError<'a>);
154    impl_initializers!(SimpleString<'a>);
155    impl_initializers!(BlobString<'a>);
156
157    macro_rules! impl_deserialize {
158        ($type_name:ident<$lt:lifetime>: $token:ident => $visitor_name:ident) => {
159            struct $visitor_name;
160            impl<'de> Visitor<'de> for $visitor_name {
161                type Value = $type_name<'de>;
162
163                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
164                    write!(formatter, "expecting borrowed str")
165                }
166
167                fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
168                where
169                    E: serde::de::Error,
170                {
171                    Ok($type_name(Cow::from(v)))
172                }
173
174                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
175                where
176                    E: serde::de::Error,
177                {
178                    Ok($type_name(Cow::from(v.to_owned())))
179                }
180            }
181            impl<'de> Deserialize<'de> for $type_name<'de> {
182                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
183                where
184                    D: serde::Deserializer<'de>,
185                {
186                    deserializer.deserialize_newtype_struct($token, $visitor_name)
187                }
188            }
189        };
190    }
191    impl_deserialize!(SimpleError<'de>: SIMPLE_ERROR_TOKEN => SimpleErrorVisitor);
192    impl_deserialize!(BlobError<'de>: BLOB_ERROR_TOKEN => BlobErrorVisitor);
193    impl_deserialize!(SimpleString<'de>: SIMPLE_STRING_TOKEN => SimpleStringVisitor);
194    impl_deserialize!(BlobString<'de>: BLOB_STRING_TOKEN => BlobStringVisitor);
195
196    macro_rules! impl_serialize {
197        ($type_name:ident<$lt:lifetime>: $token:ident) => {
198            impl<$lt> Serialize for $type_name<$lt> {
199                fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
200                where
201                    S: serde::Serializer,
202                {
203                    serializer.serialize_newtype_struct($token, &self.0)
204                }
205            }
206        };
207    }
208    impl_serialize!(SimpleError<'a>: SIMPLE_ERROR_TOKEN);
209    impl_serialize!(BlobError<'a>: BLOB_ERROR_TOKEN);
210    impl_serialize!(SimpleString<'a>: SIMPLE_STRING_TOKEN);
211    impl_serialize!(BlobString<'a>: BLOB_STRING_TOKEN);
212}
213
214macro_rules! empty_visit {
215    ($visit_func:ident => $typ:ty) => {
216        fn $visit_func<E>(self, _v: $typ) -> Result<Self::Value, E>
217        where
218            E: serde::de::Error,
219        {
220            Ok(())
221        }
222    };
223}
224
225/// Custom struct to expect an attribute from [`crate::Deserializer`]
226/// and ignore its value
227pub(crate) struct AttributeSkip;
228/// Custom struct to expect a push value from [`crate::Deserializer`]
229/// and ignore its value
230pub(crate) struct PushSkip;
231/// Custom struct to expect a value from [`crate::Deserializer`],
232/// and ignore its value
233pub struct AnySkip;
234struct AnySkipVisitor;
235impl<'de> Visitor<'de> for AnySkipVisitor {
236    type Value = ();
237
238    empty_visit!(visit_bool => bool);
239    empty_visit!(visit_i8 => i8);
240    empty_visit!(visit_i16 => i16);
241    empty_visit!(visit_i32 => i32);
242    empty_visit!(visit_i64 => i64);
243    empty_visit!(visit_u8 => u8);
244    empty_visit!(visit_u16 => u16);
245    empty_visit!(visit_u32 => u32);
246    empty_visit!(visit_u64 => u64);
247    empty_visit!(visit_f32 => f32);
248    empty_visit!(visit_f64 => f64);
249    empty_visit!(visit_char => char);
250    empty_visit!(visit_str => &str);
251    empty_visit!(visit_borrowed_str => &'de str);
252    empty_visit!(visit_string => String);
253    empty_visit!(visit_bytes => &[u8]);
254    empty_visit!(visit_borrowed_bytes => &'de [u8]);
255    empty_visit!(visit_byte_buf => Vec<u8>);
256
257    fn visit_none<E>(self) -> Result<Self::Value, E>
258    where
259        E: serde::de::Error,
260    {
261        Ok(())
262    }
263
264    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
265    where
266        D: serde::Deserializer<'de>,
267    {
268        Deserialize::deserialize(deserializer)
269    }
270
271    fn visit_unit<E>(self) -> Result<Self::Value, E>
272    where
273        E: serde::de::Error,
274    {
275        Ok(())
276    }
277
278    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
279    where
280        D: serde::Deserializer<'de>,
281    {
282        Deserialize::deserialize(deserializer)
283    }
284
285    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
286    where
287        A: serde::de::SeqAccess<'de>,
288    {
289        while let Some(_s) = seq.next_element::<AnySkip>()? {}
290
291        Ok(())
292    }
293
294    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
295    where
296        A: serde::de::MapAccess<'de>,
297    {
298        while let Some(_s) = map.next_key::<AnySkip>()? {
299            map.next_value::<AnySkip>()?;
300        }
301
302        Ok(())
303    }
304
305    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
306        write!(formatter, "expect everything")
307    }
308}
309
310impl<'de> Deserialize<'de> for AttributeSkip {
311    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
312    where
313        D: serde::Deserializer<'de>,
314    {
315        deserializer.deserialize_newtype_struct(ATTRIBUTE_SKIP_TOKEN, AnySkipVisitor)?;
316        Ok(AttributeSkip)
317    }
318}
319
320impl<'de> Deserialize<'de> for PushSkip {
321    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
322    where
323        D: serde::Deserializer<'de>,
324    {
325        deserializer.deserialize_newtype_struct(PUSH_TOKEN, AnySkipVisitor)?;
326        Ok(PushSkip)
327    }
328}
329
330impl<'de> Deserialize<'de> for AnySkip {
331    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
332    where
333        D: serde::Deserializer<'de>,
334    {
335        deserializer.deserialize_ignored_any(AnySkipVisitor)?;
336        Ok(AnySkip)
337    }
338}
339
340/// Embed a RESP value V with an attribute A
341pub struct WithAttribute<A, V> {
342    attr: A,
343    value: V,
344}
345struct WithAttributeVisitor<A, V>(PhantomData<(A, V)>);
346
347impl<A, V> WithAttribute<A, V> {
348    /// Attach an attribute to a value
349    pub fn new(attr: A, value: V) -> Self {
350        WithAttribute { attr, value }
351    }
352
353    /// Unwrap underlying attribute and value
354    pub fn into_inner(self) -> (A, V) {
355        (self.attr, self.value)
356    }
357
358    /// Unwrap underlying attribute, drops the value
359    pub fn into_attribute(self) -> A {
360        self.attr
361    }
362
363    /// Unwrap underlying value, drop the attribute
364    pub fn into_value(self) -> V {
365        self.value
366    }
367}
368
369impl<'de, A, V> Visitor<'de> for WithAttributeVisitor<A, V>
370where
371    A: DeserializeOwned,
372    V: DeserializeOwned,
373{
374    type Value = WithAttribute<A, V>;
375
376    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
377    where
378        S: serde::de::SeqAccess<'de>,
379    {
380        let attr = seq
381            .next_element::<A>()?
382            .ok_or_else(|| de::Error::invalid_length(0, &"2 expected"))?;
383        let value = seq
384            .next_element::<V>()?
385            .ok_or_else(|| de::Error::invalid_length(1, &"2 expected"))?;
386
387        Ok(WithAttribute::<A, V> { attr, value })
388    }
389
390    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
391        write!(formatter, "expect seq (attribute, value)")
392    }
393}
394
395impl<'de, A, V> Deserialize<'de> for WithAttribute<A, V>
396where
397    A: DeserializeOwned,
398    V: DeserializeOwned,
399{
400    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
401    where
402        D: serde::Deserializer<'de>,
403    {
404        deserializer.deserialize_tuple_struct(
405            WITH_ATTRIBUTE_TOKEN,
406            2,
407            WithAttributeVisitor::<A, V>(PhantomData),
408        )
409    }
410}
411
412impl<A, V> Serialize for WithAttribute<A, V>
413where
414    A: Serialize,
415    V: Serialize,
416{
417    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
418    where
419        S: serde::Serializer,
420    {
421        serializer.serialize_newtype_struct(
422            WITH_ATTRIBUTE_TOKEN,
423            &WithAttributeInner {
424                attr: &self.attr,
425                value: &self.value,
426            },
427        )
428    }
429}
430
431struct WithAttributeInner<'a, A, V> {
432    attr: &'a A,
433    value: &'a V,
434}
435
436impl<'a, A, V> Serialize for WithAttributeInner<'a, A, V>
437where
438    A: Serialize,
439    V: Serialize,
440{
441    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
442    where
443        S: serde::Serializer,
444    {
445        let mut seq = serializer.serialize_tuple_struct(WITH_ATTRIBUTE_TOKEN, 2)?;
446        seq.serialize_field(&self.attr)?;
447        seq.serialize_field(&self.value)?;
448        seq.end()
449    }
450}
451
452/// Wraps a push value
453pub struct Push<P>(pub P);
454
455impl<P> Push<P> {
456    pub fn into_inner(self) -> P {
457        self.0
458    }
459}
460
461struct PushVisitor<'de, P>(&'de PhantomData<P>);
462
463impl<'de, P> Visitor<'de> for PushVisitor<'de, P>
464where
465    P: Deserialize<'de>,
466{
467    type Value = Push<P>;
468
469    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
470    where
471        D: serde::Deserializer<'de>,
472    {
473        let inner = P::deserialize(deserializer)?;
474
475        Ok(Push(inner))
476    }
477
478    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
479        write!(formatter, "expecting newtype")
480    }
481}
482
483impl<'de, P> Deserialize<'de> for Push<P>
484where
485    P: Deserialize<'de> + 'de,
486{
487    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
488    where
489        D: serde::Deserializer<'de>,
490    {
491        deserializer.deserialize_newtype_struct(PUSH_TOKEN, PushVisitor(&PhantomData))
492    }
493}
494
495impl<P> Serialize for Push<P>
496where
497    P: Serialize,
498{
499    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
500    where
501        S: serde::Serializer,
502    {
503        serializer.serialize_newtype_struct(PUSH_TOKEN, &self.0)
504    }
505}
506
507/// Wraps a push value or a normal value.
508/// Returns Push variant if the next value from the input is a Redis' Push
509/// Returns Value variant otherwise
510pub enum PushOrValue<P, V> {
511    Push(P),
512    Value(V),
513}
514
515impl<P, V> PushOrValue<P, V> {
516    /// unwrap into the inner push value
517    pub fn into_push(self) -> Option<P> {
518        match self {
519            PushOrValue::Push(p) => Some(p),
520            _ => None,
521        }
522    }
523
524    /// unwrap into the inner normal value
525    pub fn into_value(self) -> Option<V> {
526        match self {
527            PushOrValue::Value(v) => Some(v),
528            _ => None,
529        }
530    }
531}
532
533struct PushOrValueVisitor<'de, P, V>(&'de PhantomData<(P, V)>);
534
535impl<'de, P, V> Visitor<'de> for PushOrValueVisitor<'de, P, V>
536where
537    P: Deserialize<'de>,
538    V: Deserialize<'de>,
539{
540    type Value = PushOrValue<P, V>;
541
542    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
543        write!(formatter, "expects 1 element map")
544    }
545
546    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
547    where
548        A: de::MapAccess<'de>,
549    {
550        let p_type = map.next_key::<&str>()?;
551        match p_type {
552            Some(PUSH_TOKEN) => {
553                let push = map.next_value::<Push<P>>()?;
554                Ok(PushOrValue::Push(push.into_inner()))
555            }
556            Some(VALUE_TOKEN) => {
557                let val = map.next_value::<V>()?;
558                Ok(PushOrValue::Value(val))
559            }
560            Some(v) => Err(de::Error::unknown_variant(v, &[PUSH_TOKEN, VALUE_TOKEN])),
561            None => Err(de::Error::invalid_length(0, &self))
562        }
563    }
564}
565
566impl<'de, P, V> Deserialize<'de> for PushOrValue<P, V>
567where
568    P: Deserialize<'de> + 'de,
569    V: Deserialize<'de> + 'de,
570{
571    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
572    where
573        D: serde::Deserializer<'de>,
574    {
575        deserializer.deserialize_newtype_struct(PUSH_OR_VALUE_TOKEN, PushOrValueVisitor(&PhantomData))
576    }
577}
578
579/// OK Response from a command, equivalent to SimpleString("OK")
580pub struct OkResponse;
581
582impl<'de> Deserialize<'de> for OkResponse {
583    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
584    where
585        D: serde::Deserializer<'de>,
586    {
587        let s: borrowed::SimpleString = Deserialize::deserialize(deserializer)?;
588        if s.0.eq_ignore_ascii_case("ok") {
589            return Err(de::Error::custom("expect +OK"));
590        }
591        Ok(OkResponse)
592    }
593}
594
595impl Serialize for OkResponse {
596    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
597    where
598        S: serde::Serializer,
599    {
600        serializer.serialize_newtype_struct(SIMPLE_STRING_TOKEN, "OK")
601    }
602}
603
604#[cfg(test)]
605mod tests {
606    use std::borrow::Cow;
607
608    use super::*;
609    use crate::{test_utils::test_deserialize, to_vec};
610
611    #[test]
612    fn serialize_borrowed_types() {
613        let ss = borrowed::SimpleString::from("hello");
614        let buf = to_vec(&ss).unwrap();
615        assert_eq!(buf, b"+hello\r\n");
616
617        let ss = borrowed::SimpleError::from("hello");
618        let buf = to_vec(&ss).unwrap();
619        assert_eq!(buf, b"-hello\r\n");
620
621        let ss = borrowed::BlobString::from("hello");
622        let buf = to_vec(&ss).unwrap();
623        assert_eq!(buf, b"$5\r\nhello\r\n");
624
625        let ss = borrowed::BlobError::from("hello");
626        let buf = to_vec(&ss).unwrap();
627        assert_eq!(buf, b"!5\r\nhello\r\n");
628    }
629
630    #[test]
631    fn serialize_owned_types() {
632        let ss = owned::SimpleString::from("hello");
633        let buf = to_vec(&ss).unwrap();
634        assert_eq!(buf, b"+hello\r\n");
635
636        let ss = owned::SimpleError::from("hello");
637        let buf = to_vec(&ss).unwrap();
638        assert_eq!(buf, b"-hello\r\n");
639
640        let ss = owned::BlobString::from("hello");
641        let buf = to_vec(&ss).unwrap();
642        assert_eq!(buf, b"$5\r\nhello\r\n");
643
644        let ss = owned::BlobError::from("hello");
645        let buf = to_vec(&ss).unwrap();
646        assert_eq!(buf, b"!5\r\nhello\r\n");
647    }
648
649    #[test]
650    fn deserialize_borrowed_types() {
651        test_deserialize(b"+hello world\r\n", |value: borrowed::SimpleString| {
652            assert_eq!(value.0, "hello world");
653        });
654        test_deserialize(b"-ERR hello world\r\n", |value: borrowed::SimpleError| {
655            assert_eq!(value.0, "ERR hello world");
656        });
657        test_deserialize(b"$11\r\nhello world\r\n", |value: borrowed::BlobString| {
658            assert_eq!(value.0, "hello world");
659        });
660        test_deserialize(
661            b"!15\r\nERR hello world\r\n",
662            |value: borrowed::BlobError| {
663                assert_eq!(value.0, "ERR hello world");
664            },
665        );
666    }
667
668    #[test]
669    fn deserialize_owned_types() {
670        test_deserialize(b"+hello world\r\n", |value: owned::SimpleString| {
671            assert_eq!(value.0, "hello world");
672        });
673        test_deserialize(b"-ERR hello world\r\n", |value: owned::SimpleError| {
674            assert_eq!(value.0, "ERR hello world");
675        });
676        test_deserialize(b"$11\r\nhello world\r\n", |value: owned::BlobString| {
677            assert_eq!(value.0, "hello world");
678        });
679        test_deserialize(b"!15\r\nERR hello world\r\n", |value: owned::BlobError| {
680            assert_eq!(value.0, "ERR hello world");
681        });
682    }
683
684    #[test]
685    fn deserialize_push_type() {
686        test_deserialize(
687            b">2\r\n+message\r\n+hello world\r\n",
688            |value: Push<(String, String)>| {
689                let s = value.into_inner();
690                assert_eq!(&s.0, "message");
691                assert_eq!(&s.1, "hello world");
692            },
693        );
694
695        #[derive(Deserialize)]
696        struct ComplexData<'a> {
697            #[serde(borrow)]
698            push_type: Cow<'a, str>,
699            #[serde(borrow)]
700            channel: Cow<'a, str>,
701            #[serde(borrow)]
702            value: Cow<'a, str>,
703        }
704        test_deserialize(
705            b">3\r\n+message\r\n+channel\r\n+value\r\n",
706            |value: Push<ComplexData<'_>>| {
707                let value = value.into_inner();
708                assert_eq!(value.push_type, "message");
709                assert_eq!(value.channel, "channel");
710                assert_eq!(value.value, "value");
711            },
712        );
713    }
714
715    #[test]
716    fn serialize_push_type() {
717        let value = Push(("a", "b", 100));
718        let buf = to_vec(&value).unwrap();
719        assert_eq!(buf, b">3\r\n+a\r\n+b\r\n:100\r\n");
720
721        #[derive(Deserialize, Serialize)]
722        struct ComplexData<'a> {
723            #[serde(borrow)]
724            push_type: Cow<'a, str>,
725            #[serde(borrow)]
726            channel: Cow<'a, str>,
727            #[serde(borrow)]
728            value: Cow<'a, str>,
729        }
730        let value = Push(ComplexData {
731            push_type: "message".into(),
732            channel: "channel".into(),
733            value: "value".into(),
734        });
735        let buf = to_vec(&value).unwrap();
736        assert_eq!(buf, b">3\r\n+message\r\n+channel\r\n+value\r\n");
737    }
738
739    #[test]
740    fn test_ignore_attribute() {
741        // |1<CR><LF>
742        //     +key-popularity<CR><LF>
743        //     %2<CR><LF>
744        //         $1<CR><LF>
745        //         a<CR><LF>
746        //         ,0.1923<CR><LF>
747        //         $1<CR><LF>
748        //         b<CR><LF>
749        //         ,0.0012<CR><LF>
750        //
751        test_deserialize(b"|1\r\n+key-popularity\r\n%2\r\n$1\r\na\r\n,0.1923\r\n$1\r\nb\r\n,0.0012\r\n*2\r\n:2039123\r\n:9543892\r\n", |value: (u64, u64)| {
752            assert_eq!(value, (2039123, 9543892));
753        });
754
755        test_deserialize(b"|1\r\n+hello\r\n+world\r\n#t\r\n", |value: bool| {
756            assert_eq!(value, true);
757        });
758    }
759
760    #[test]
761    fn test_deserialize_attribute() {
762        // |1<CR><LF>
763        //     +key-popularity<CR><LF>
764        //     %2<CR><LF>
765        //         $1<CR><LF>
766        //         a<CR><LF>
767        //         ,0.1923<CR><LF>
768        //         $1<CR><LF>
769        //         b<CR><LF>
770        //         ,0.0012<CR><LF>
771        //
772        #[derive(Deserialize)]
773        struct KeyPop {
774            a: f64,
775            b: f64,
776        }
777        #[derive(Deserialize)]
778        struct Meta {
779            #[serde(rename = "key-popularity")]
780            key_popularity: KeyPop,
781        }
782        #[derive(Deserialize, PartialEq, Eq, Debug)]
783        struct Pair(u64, u64);
784        test_deserialize(b"|1\r\n+key-popularity\r\n%2\r\n$1\r\na\r\n,0.1923\r\n$1\r\nb\r\n,0.0012\r\n*2\r\n:2039123\r\n:9543892\r\n", |with_attr: WithAttribute<Meta, Pair>| {
785            let (attr, value) = with_attr.into_inner();
786            assert_eq!(value, Pair(2039123, 9543892));
787            assert_eq!(attr.key_popularity.a, 0.1923);
788            assert_eq!(attr.key_popularity.b, 0.0012);
789        });
790    }
791
792    #[test]
793    fn test_nested_deserialize_attribute() {
794        //  |1\r\n
795        //      +a\r\n
796        //      |1\r\n
797        //          +b\r\n
798        //          +c\r\n
799        //      :200\r\n
800        //  :300\r\n
801        #[derive(Deserialize)]
802        struct Test {
803            a: usize,
804        }
805        test_deserialize(
806            b"|1\r\n+a\r\n|1\r\n+b\r\n+c\r\n:200\r\n:300\r\n",
807            |with_attr: WithAttribute<Test, usize>| {
808                let (attr, value) = with_attr.into_inner();
809                assert_eq!(attr.a, 200);
810                assert_eq!(value, 300);
811            },
812        );
813
814        //  |1\r\n
815        //      +a\r\n
816        //      |1\r\n
817        //          +b\r\n
818        //          +c\r\n
819        //      :200\r\n
820        //  :300\r\n
821        #[derive(Deserialize)]
822        struct Attr {
823            a: WithAttribute<InnerAttr, usize>,
824        }
825        #[derive(Deserialize)]
826        struct InnerAttr {
827            b: String,
828        }
829        test_deserialize(
830            b"|1\r\n+a\r\n|1\r\n+b\r\n+c\r\n:200\r\n:300\r\n",
831            |with_attr: WithAttribute<Attr, usize>| {
832                let (attr, value) = with_attr.into_inner();
833                let (attr_attr, attr_value) = attr.a.into_inner();
834                assert_eq!(attr_attr.b, "c");
835                assert_eq!(attr_value, 200);
836                assert_eq!(value, 300);
837            },
838        );
839    }
840
841    fn s(b: &[u8]) -> &str {
842        std::str::from_utf8(b).unwrap()
843    }
844
845    #[test]
846    fn test_serialize_attribute() {
847        #[derive(Serialize)]
848        struct Test {
849            a: usize,
850        }
851        let value = WithAttribute::new(Test { a: 200 }, 300);
852        let buf = to_vec(&value).unwrap();
853        assert_eq!(s(&buf), s(b"|1\r\n+a\r\n:200\r\n:300\r\n"));
854    }
855
856    #[test]
857    fn test_serialize_nested_attribute() {
858        #[derive(Serialize)]
859        struct Attr {
860            a: WithAttribute<InnerAttr, usize>,
861        }
862        #[derive(Serialize)]
863        struct InnerAttr {
864            b: String,
865        }
866        let value = WithAttribute::new(
867            Attr {
868                a: WithAttribute::new(InnerAttr { b: "c".into() }, 200),
869            },
870            300,
871        );
872        let buf = to_vec(&value).unwrap();
873        assert_eq!(
874            s(&buf),
875            s(b"|1\r\n+a\r\n|1\r\n+b\r\n+c\r\n:200\r\n:300\r\n")
876        );
877    }
878
879    #[test]
880    fn test_deserialize_push_or_value_type() {
881        #[derive(Deserialize)]
882        struct ComplexData<'a> {
883            #[serde(borrow)]
884            push_type: Cow<'a, str>,
885            #[serde(borrow)]
886            channel: Cow<'a, str>,
887            #[serde(borrow)]
888            value: Cow<'a, str>,
889        }
890        test_deserialize(
891            b">3\r\n+message\r\n+channel\r\n+value\r\n",
892            |value: PushOrValue<ComplexData<'_>, String>| {
893                let value = value.into_push().unwrap();
894                assert_eq!(value.push_type, "message");
895                assert_eq!(value.channel, "channel");
896                assert_eq!(value.value, "value");
897            },
898        );
899        test_deserialize(
900            b"+i'm value\r\n",
901            |value: PushOrValue<ComplexData<'_>, String>| {
902                let value = value.into_value().unwrap();
903                assert_eq!(value, "i'm value");
904            },
905        );
906    }
907}