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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Type-erased protobuf message support.

use crate::decode;
use crate::encode;
use crate::encoding::MessageEncoding;
use crate::inplace::InplaceOption;
use crate::protobuf::MessageReader;
use crate::protobuf::MessageSizer;
use crate::protobuf::MessageWriter;
use crate::protofile::DescribeField;
use crate::protofile::FieldType;
use crate::protofile::MessageDescription;
use crate::table::DescribeTable;
use crate::DefaultEncoding;
use crate::DescribedProtobuf;
use crate::Error;
use crate::MessageDecode;
use crate::MessageEncode;
use crate::Protobuf;
use thiserror::Error;

/// An opaque protobuf message.
//
// TODO: delay encoding like in mesh::Message. This requires splitting some of
// the encoding traits up to remove the resource type.
#[derive(Debug)]
pub struct ProtobufMessage(Vec<u8>);

impl ProtobufMessage {
    /// Encodes `data` as a protobuf message.
    pub fn new(data: impl Protobuf) -> Self {
        Self(encode(data))
    }

    /// Decodes the protobuf message into `T`.
    pub fn parse<T: Protobuf>(&self) -> Result<T, Error> {
        decode(&self.0)
    }
}

impl DefaultEncoding for ProtobufMessage {
    type Encoding = MessageEncoding<ProtobufMessageEncoding>;
}

impl DescribeField<ProtobufMessage> for MessageEncoding<ProtobufMessageEncoding> {
    const FIELD_TYPE: FieldType<'static> = FieldType::builtin("bytes");
}

/// Encoder for [`ProtobufMessage`].
#[derive(Debug)]
pub struct ProtobufMessageEncoding;

impl<R> MessageEncode<ProtobufMessage, R> for ProtobufMessageEncoding {
    fn write_message(item: ProtobufMessage, mut writer: MessageWriter<'_, '_, R>) {
        writer.bytes(&item.0);
    }

    fn compute_message_size(item: &mut ProtobufMessage, mut sizer: MessageSizer<'_>) {
        sizer.bytes(item.0.len());
    }
}

impl<R> MessageDecode<'_, ProtobufMessage, R> for ProtobufMessageEncoding {
    fn read_message(
        item: &mut InplaceOption<'_, ProtobufMessage>,
        reader: MessageReader<'_, '_, R>,
    ) -> crate::Result<()> {
        item.get_or_insert_with(|| ProtobufMessage(Vec::new()))
            .0
            .extend(reader.bytes());
        Ok(())
    }
}

/// A protobuf message and the associated protobuf type URL.
///
/// This has the encoding of `google.protobuf.Any`.
#[derive(Debug, Protobuf)]
pub struct ProtobufAny {
    #[mesh(1)]
    type_url: String, // FUTURE: avoid allocation here
    #[mesh(2)]
    value: ProtobufMessage,
}

#[derive(Debug, Error)]
#[error("protobuf type mismatch, expected {expected}, got {actual}")]
struct TypeMismatch {
    expected: String,
    actual: String,
}

impl DescribeTable for ProtobufAny {
    const DESCRIPTION: MessageDescription<'static> = MessageDescription::External {
        name: "google.protobuf.Any",
        import_path: "google/protobuf/any.proto",
    };
}

impl ProtobufAny {
    /// Encodes `data` as a protobuf message.
    pub fn new<T: DescribedProtobuf>(data: T) -> Self {
        Self {
            type_url: T::TYPE_URL.to_string(),
            value: ProtobufMessage::new(data),
        }
    }

    /// Decodes the protobuf message into `T`.
    ///
    /// Fails if this message is an encoding of a different type.
    pub fn parse<T: DescribedProtobuf>(&self) -> Result<T, Error> {
        if &T::TYPE_URL != self.type_url.as_str() {
            return Err(Error::new(TypeMismatch {
                expected: T::TYPE_URL.to_string(),
                actual: self.type_url.clone(),
            }));
        }
        self.value.parse()
    }

    /// Returns `true` if this message is an encoding of `T`.
    pub fn is_message<T: DescribedProtobuf>(&self) -> bool {
        &T::TYPE_URL == self.type_url.as_str()
    }
}

#[cfg(test)]
mod tests {
    use crate::encode;
    use crate::message::ProtobufAny;
    use crate::message::ProtobufMessage;
    use crate::Protobuf;

    #[test]
    fn test_message() {
        let message = (5u32,);

        // Round trips.
        assert_eq!(
            ProtobufMessage::new(message).parse::<(u32,)>().unwrap(),
            message
        );

        // Is transparent.
        assert_eq!(encode(ProtobufMessage::new(message)), encode(message));
    }

    #[test]
    fn test_any() {
        #[derive(Protobuf, PartialEq, Eq, Copy, Clone, Debug)]
        #[mesh(package = "test")]
        struct Message {
            #[mesh(1)]
            x: u32,
        }

        #[derive(Protobuf, Debug)]
        #[mesh(package = "test")]
        struct Other {
            #[mesh(1)]
            x: u32,
        }

        let msg = Message { x: 5 };
        let any = ProtobufAny::new(msg);

        assert_eq!(any.type_url, "type.googleapis.com/test.Message");
        assert!(any.is_message::<Message>());
        assert!(!any.is_message::<Other>());
        assert_eq!(any.parse::<Message>().unwrap(), msg);
        println!("{:?}", any.parse::<Other>().unwrap_err());
    }
}