Skip to main content

der/
encode_ref.rs

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