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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::any::Any;

#[cfg(feature = "bytes")]
use crate::chars::Chars;
#[cfg(feature = "bytes")]
use bytes::Bytes;

use super::*;

use crate::reflect::reflect_eq::{ReflectEq, ReflectEqMode};
use crate::reflect::transmute_eq::transmute_eq;

/// Type implemented by all protobuf singular types
/// (primitives, string, messages, enums).
///
/// Used for dynamic casting in reflection.
pub trait ProtobufValue: Any + 'static + Send + Sync {}

impl ProtobufValue for u32 {}

impl ProtobufValue for u64 {}

impl ProtobufValue for i32 {}

impl ProtobufValue for i64 {}

impl ProtobufValue for f32 {}

impl ProtobufValue for f64 {}

impl ProtobufValue for bool {}

impl ProtobufValue for String {}

impl ProtobufValue for Vec<u8> {}

#[cfg(feature = "bytes")]
impl ProtobufValue for Bytes {}

#[cfg(feature = "bytes")]
impl ProtobufValue for Chars {}

// conflicting implementations, so generated code is used instead
/*
impl<E : ProtobufEnum> ProtobufValue for E {
}

impl<M : Message> ProtobufValue for M {
}
*/

/// A reference to a value
#[derive(Debug, Clone)]
pub enum ReflectValueRef<'a> {
    /// `u32`
    U32(u32),
    /// `u64`
    U64(u64),
    /// `i32`
    I32(i32),
    /// `i64`
    I64(i64),
    /// `f32`
    F32(f32),
    /// `f64`
    F64(f64),
    /// `bool`
    Bool(bool),
    /// `string`
    String(&'a str),
    /// `bytes`
    Bytes(&'a [u8]),
    /// `enum`
    Enum(&'static EnumDescriptor, i32),
    /// `message`
    Message(&'a dyn Message),
}

impl<'a> ReflectValueRef<'a> {
    /// Value is "non-zero"?
    #[doc(hidden)]
    pub fn is_non_zero(&self) -> bool {
        match *self {
            ReflectValueRef::U32(v) => v != 0,
            ReflectValueRef::U64(v) => v != 0,
            ReflectValueRef::I32(v) => v != 0,
            ReflectValueRef::I64(v) => v != 0,
            ReflectValueRef::F32(v) => v != 0.,
            ReflectValueRef::F64(v) => v != 0.,
            ReflectValueRef::Bool(v) => v,
            ReflectValueRef::String(v) => !v.is_empty(),
            ReflectValueRef::Bytes(v) => !v.is_empty(),
            ReflectValueRef::Enum(_d, v) => v != 0,
            ReflectValueRef::Message(_) => true,
        }
    }

    /// Take `i32` value.
    pub fn to_i32(&self) -> Option<i32> {
        match *self {
            ReflectValueRef::I32(v) => Some(v),
            _ => None,
        }
    }

    /// Take `i64` value.
    pub fn to_i64(&self) -> Option<i64> {
        match *self {
            ReflectValueRef::I64(v) => Some(v),
            _ => None,
        }
    }

    /// Take `u32` value.
    pub fn to_u32(&self) -> Option<u32> {
        match *self {
            ReflectValueRef::U32(v) => Some(v),
            _ => None,
        }
    }

    /// Take `u64` value.
    pub fn to_u64(&self) -> Option<u64> {
        match *self {
            ReflectValueRef::U64(v) => Some(v),
            _ => None,
        }
    }

    /// Take `f32` value.
    pub fn to_f32(&self) -> Option<f32> {
        match *self {
            ReflectValueRef::F32(v) => Some(v),
            _ => None,
        }
    }

    /// Take `f64` value.
    pub fn to_f64(&self) -> Option<f64> {
        match *self {
            ReflectValueRef::F64(v) => Some(v),
            _ => None,
        }
    }

    /// Take `bool` value.
    pub fn to_bool(&self) -> Option<bool> {
        match *self {
            ReflectValueRef::Bool(v) => Some(v),
            _ => None,
        }
    }

    /// Take `str` value.
    pub fn to_str(&self) -> Option<&str> {
        match *self {
            ReflectValueRef::String(v) => Some(v),
            _ => None,
        }
    }

    /// Take `[u8]` value.
    pub fn to_bytes(&self) -> Option<&[u8]> {
        match *self {
            ReflectValueRef::Bytes(v) => Some(v),
            _ => None,
        }
    }

    /// Take message value.
    pub fn to_message(&self) -> Option<&'a dyn Message> {
        match *self {
            ReflectValueRef::Message(m) => Some(m),
            _ => None,
        }
    }

    /// Clone to a box
    pub(crate) fn to_box(&self) -> ReflectValueBox {
        match *self {
            ReflectValueRef::U32(v) => ReflectValueBox::U32(v),
            ReflectValueRef::U64(v) => ReflectValueBox::U64(v),
            ReflectValueRef::I32(v) => ReflectValueBox::I32(v),
            ReflectValueRef::I64(v) => ReflectValueBox::I64(v),
            ReflectValueRef::F32(v) => ReflectValueBox::F32(v),
            ReflectValueRef::F64(v) => ReflectValueBox::F64(v),
            ReflectValueRef::Bool(v) => ReflectValueBox::Bool(v),
            ReflectValueRef::String(v) => ReflectValueBox::String(v.to_owned()),
            ReflectValueRef::Bytes(v) => ReflectValueBox::Bytes(v.to_owned()),
            ReflectValueRef::Enum(d, v) => ReflectValueBox::Enum(d, v),
            ReflectValueRef::Message(v) => ReflectValueBox::Message(v.descriptor().clone(v)),
        }
    }

    /// Convert a value to arbitrary value.
    pub fn downcast_clone<V: ProtobufValue>(&self) -> Result<V, Self> {
        self.to_box().downcast().map_err(|_| self.clone())
    }
}

impl<'a> ReflectEq for ReflectValueRef<'a> {
    fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool {
        use super::ReflectValueRef::*;
        match (self, that) {
            (U32(a), U32(b)) => a == b,
            (U64(a), U64(b)) => a == b,
            (I32(a), I32(b)) => a == b,
            (I64(a), I64(b)) => a == b,
            (F32(a), F32(b)) => {
                if a.is_nan() || b.is_nan() {
                    a.is_nan() == b.is_nan() && mode.nan_equal
                } else {
                    a == b
                }
            }
            (F64(a), F64(b)) => {
                if a.is_nan() || b.is_nan() {
                    a.is_nan() == b.is_nan() && mode.nan_equal
                } else {
                    a == b
                }
            }
            (Bool(a), Bool(b)) => a == b,
            (String(a), String(b)) => a == b,
            (Bytes(a), Bytes(b)) => a == b,
            (Enum(ad, a), Enum(bd, b)) => ad == bd && a == b,
            (Message(a), Message(b)) => {
                let ad = a.descriptor();
                let bd = b.descriptor();
                ad == bd && ad.reflect_eq(*a, *b, mode)
            }
            _ => false,
        }
    }
}

#[doc(hidden)]
pub enum ReflectValueMut<'a> {
    Message(&'a mut dyn Message),
}

/// Owner value of any elementary type
#[derive(Debug, Clone)]
pub enum ReflectValueBox {
    /// `u32`
    U32(u32),
    /// `u64`
    U64(u64),
    /// `i32`
    I32(i32),
    /// `i64`
    I64(i64),
    /// `f32`
    F32(f32),
    /// `f64`
    F64(f64),
    /// `bool`
    Bool(bool),
    /// `string`
    String(String),
    /// `bytes`
    Bytes(Vec<u8>),
    /// `enum`
    Enum(&'static EnumDescriptor, i32),
    /// `message`
    Message(Box<dyn Message>),
}

impl From<u32> for ReflectValueBox {
    fn from(v: u32) -> Self {
        ReflectValueBox::U32(v)
    }
}

impl From<u64> for ReflectValueBox {
    fn from(v: u64) -> Self {
        ReflectValueBox::U64(v)
    }
}

impl From<i32> for ReflectValueBox {
    fn from(v: i32) -> Self {
        ReflectValueBox::I32(v)
    }
}

impl From<i64> for ReflectValueBox {
    fn from(v: i64) -> Self {
        ReflectValueBox::I64(v)
    }
}

impl From<f32> for ReflectValueBox {
    fn from(v: f32) -> Self {
        ReflectValueBox::F32(v)
    }
}

impl From<f64> for ReflectValueBox {
    fn from(v: f64) -> Self {
        ReflectValueBox::F64(v)
    }
}

impl From<bool> for ReflectValueBox {
    fn from(v: bool) -> Self {
        ReflectValueBox::Bool(v)
    }
}

impl From<String> for ReflectValueBox {
    fn from(v: String) -> Self {
        ReflectValueBox::String(v)
    }
}

impl From<Vec<u8>> for ReflectValueBox {
    fn from(v: Vec<u8>) -> Self {
        ReflectValueBox::Bytes(v)
    }
}

impl From<&'static EnumValueDescriptor> for ReflectValueBox {
    fn from(v: &'static EnumValueDescriptor) -> Self {
        ReflectValueBox::Enum(v.enum_descriptor(), v.value())
    }
}

impl From<Box<dyn Message>> for ReflectValueBox {
    fn from(v: Box<dyn Message>) -> Self {
        ReflectValueBox::Message(v)
    }
}

fn _assert_value_box_send_sync() {
    fn _assert_send_sync<T: Send + Sync>() {}
    _assert_send_sync::<ReflectValueBox>();
}

#[cfg(not(feature = "bytes"))]
type VecU8OrBytes = Vec<u8>;
#[cfg(feature = "bytes")]
type VecU8OrBytes = Vec<u8>;
#[cfg(not(feature = "bytes"))]
type StringOrChars = String;
#[cfg(feature = "bytes")]
type StringOrChars = Chars;

impl ReflectValueBox {
    /// Downcast to real typed value.
    ///
    /// For `enum` `V` can be either `V: ProtobufEnum` or `V: ProtobufEnumOrUnknown<E>`.
    pub fn downcast<V: ProtobufValue>(self) -> Result<V, Self> {
        match self {
            ReflectValueBox::U32(v) => transmute_eq(v).map_err(ReflectValueBox::U32),
            ReflectValueBox::U64(v) => transmute_eq(v).map_err(ReflectValueBox::U64),
            ReflectValueBox::I32(v) => transmute_eq(v).map_err(ReflectValueBox::I32),
            ReflectValueBox::I64(v) => transmute_eq(v).map_err(ReflectValueBox::I64),
            ReflectValueBox::F32(v) => transmute_eq(v).map_err(ReflectValueBox::F32),
            ReflectValueBox::F64(v) => transmute_eq(v).map_err(ReflectValueBox::F64),
            ReflectValueBox::Bool(v) => transmute_eq(v).map_err(ReflectValueBox::Bool),
            ReflectValueBox::String(v) => transmute_eq::<String, _>(v)
                .or_else(|v: String| transmute_eq::<StringOrChars, _>(v.into()))
                .map_err(|v: StringOrChars| ReflectValueBox::String(v.into())),
            ReflectValueBox::Bytes(v) => transmute_eq::<Vec<u8>, _>(v)
                .or_else(|v: Vec<u8>| transmute_eq::<VecU8OrBytes, _>(v.into()))
                .map_err(|v: VecU8OrBytes| ReflectValueBox::Bytes(v.into())),
            ReflectValueBox::Enum(d, e) => d.cast(e).ok_or(ReflectValueBox::Enum(d, e)),
            ReflectValueBox::Message(m) => m
                .downcast_box::<V>()
                .map(|m| *m)
                .map_err(ReflectValueBox::Message),
        }
    }
}