1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Helper type for mesh-encoding a type that must first be translated to
//! another type.

use super::encoding::MessageEncoding;
use super::fmt;
use super::protobuf::MessageReader;
use super::protobuf::MessageSizer;
use super::protobuf::MessageWriter;
use super::DefaultEncoding;
use super::InplaceOption;
use super::MessageDecode;
use super::MessageEncode;
use super::Result;
use crate::inplace;
use crate::Downcast;
use std::ops::Deref;
use std::ops::DerefMut;

/// Wrapper type to easily support custom mesh encoding.
///
/// This type acts as `T` but encodes on a mesh channel as `U`. This is useful
/// when `T` cannot be encoded directly via the derive macro but can be
/// converted to a type that can be encoded directly.
pub struct EncodeAs<T, U>(Inner<T, U>);

pub struct EncodedMessage<E>(E);

#[derive(Copy, Clone)]
enum Inner<T, U> {
    Unencoded(T),
    Encoded(U),
    Invalid,
}

impl<T, U> Deref for EncodeAs<T, U> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match &self.0 {
            Inner::Unencoded(v) => v,
            _ => unreachable!(),
        }
    }
}

impl<T, U> DerefMut for EncodeAs<T, U> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match &mut self.0 {
            Inner::Unencoded(v) => v,
            _ => unreachable!(),
        }
    }
}

impl<T, U> EncodeAs<T, U> {
    /// Extracts the inner `T`.
    pub fn into_inner(self) -> T {
        match self.0 {
            Inner::Unencoded(t) => t,
            _ => unreachable!(),
        }
    }
}

impl<T, U: From<T>> EncodeAs<T, U> {
    /// Constructs a new `EncodeAs` wrapping `t`.
    pub fn new(t: T) -> Self {
        Self(Inner::Unencoded(t))
    }

    fn encode(&mut self) -> &mut U {
        match std::mem::replace(&mut self.0, Inner::Invalid) {
            Inner::Unencoded(t) => {
                self.0 = Inner::Encoded(t.into());
            }
            _ => unreachable!("already encoded"),
        }
        match &mut self.0 {
            Inner::Encoded(u) => u,
            _ => unreachable!(),
        }
    }
}

impl<T, U: From<T>> From<T> for EncodeAs<T, U> {
    fn from(t: T) -> Self {
        Self::new(t)
    }
}

impl<T: Clone, U> Clone for EncodeAs<T, U> {
    fn clone(&self) -> Self {
        match &self.0 {
            Inner::Unencoded(v) => Self(Inner::Unencoded(v.clone())),
            _ => unreachable!(),
        }
    }
}

impl<T: Copy, U: Copy> Copy for EncodeAs<T, U> {}

impl<T: Default, U> Default for Inner<T, U> {
    fn default() -> Self {
        Inner::Unencoded(Default::default())
    }
}

impl<T: fmt::Display, U> fmt::Display for EncodeAs<T, U> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.deref(), f)
    }
}

impl<T: fmt::Debug, U> fmt::Debug for EncodeAs<T, U> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.deref(), f)
    }
}

impl<T, U: From<T>, R, E: MessageEncode<U, R>> MessageEncode<EncodeAs<T, U>, R>
    for EncodedMessage<E>
{
    fn write_message(item: EncodeAs<T, U>, writer: MessageWriter<'_, '_, R>) {
        match item.0 {
            Inner::Encoded(err) => E::write_message(err, writer),
            _ => unreachable!("compute_message_size has not been called"),
        }
    }

    fn compute_message_size(item: &mut EncodeAs<T, U>, sizer: MessageSizer<'_>) {
        E::compute_message_size(item.encode(), sizer);
    }
}

impl<'a, T, U: From<T> + Into<T>, R, E: MessageDecode<'a, U, R>>
    MessageDecode<'a, EncodeAs<T, U>, R> for EncodedMessage<E>
{
    fn read_message(
        item: &mut InplaceOption<'_, EncodeAs<T, U>>,
        reader: MessageReader<'a, '_, R>,
    ) -> Result<()> {
        let encoded = item.take().map(|v| v.into_inner().into());
        inplace!(encoded);
        E::read_message(&mut encoded, reader)?;
        item.set(EncodeAs(Inner::Unencoded(
            encoded.take().expect("should be constructed").into(),
        )));
        Ok(())
    }
}

impl<T, U: From<T> + Into<T> + DefaultEncoding> DefaultEncoding for EncodeAs<T, U> {
    type Encoding = MessageEncoding<EncodedMessage<U::Encoding>>;
}

impl<T, U> Downcast<EncodeAs<T, U>> for EncodeAs<T, U> where U: From<T> + Into<T> {}