1 //! Wrapper object for encoding reference types.
2 // TODO(tarcieri): replace with blanket impls of `Encode(Value)` for reference types?
3 
4 use crate::{Encode, EncodeValue, Length, Result, Tag, Tagged, ValueOrd, Writer};
5 use core::cmp::Ordering;
6 
7 /// Reference encoder: wrapper type which impls `Encode` for any reference to a
8 /// type which impls the same.
9 pub struct EncodeRef<'a, T>(pub &'a T);
10 
11 impl<'a, T> AsRef<T> for EncodeRef<'a, T> {
as_ref(&self) -> &T12     fn as_ref(&self) -> &T {
13         self.0
14     }
15 }
16 
17 impl<'a, T> Encode for EncodeRef<'a, T>
18 where
19     T: Encode,
20 {
encoded_len(&self) -> Result<Length>21     fn encoded_len(&self) -> Result<Length> {
22         self.0.encoded_len()
23     }
24 
encode(&self, writer: &mut impl Writer) -> Result<()>25     fn encode(&self, writer: &mut impl Writer) -> Result<()> {
26         self.0.encode(writer)
27     }
28 }
29 
30 /// Reference value encoder: wrapper type which impls `EncodeValue` and `Tagged`
31 /// for any reference type which impls the same.
32 ///
33 /// By virtue of the blanket impl, this type also impls `Encode`.
34 pub struct EncodeValueRef<'a, T>(pub &'a T);
35 
36 impl<'a, T> AsRef<T> for EncodeValueRef<'a, T> {
as_ref(&self) -> &T37     fn as_ref(&self) -> &T {
38         self.0
39     }
40 }
41 
42 impl<'a, T> EncodeValue for EncodeValueRef<'a, T>
43 where
44     T: EncodeValue,
45 {
value_len(&self) -> Result<Length>46     fn value_len(&self) -> Result<Length> {
47         self.0.value_len()
48     }
49 
encode_value(&self, writer: &mut impl Writer) -> Result<()>50     fn encode_value(&self, writer: &mut impl Writer) -> Result<()> {
51         self.0.encode_value(writer)
52     }
53 }
54 
55 impl<'a, T> Tagged for EncodeValueRef<'a, T>
56 where
57     T: Tagged,
58 {
tag(&self) -> Tag59     fn tag(&self) -> Tag {
60         self.0.tag()
61     }
62 }
63 
64 impl<'a, T> ValueOrd for EncodeValueRef<'a, T>
65 where
66     T: ValueOrd,
67 {
value_cmp(&self, other: &Self) -> Result<Ordering>68     fn value_cmp(&self, other: &Self) -> Result<Ordering> {
69         self.0.value_cmp(other.0)
70     }
71 }
72