blob: 4d33752f4c1ffaa01718a63f39685e97048c5409 [file] [log] [blame]
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -07001use std::mem;
2
3use super::value::ProtobufValue;
4
5use singular::*;
6
7pub trait ReflectOptional: 'static {
8 fn to_option(&self) -> Option<&ProtobufValue>;
9
10 fn set_value(&mut self, value: &ProtobufValue);
11}
12
13impl<V: ProtobufValue + Clone + 'static> ReflectOptional for Option<V> {
14 fn to_option(&self) -> Option<&ProtobufValue> {
15 self.as_ref().map(|v| v as &ProtobufValue)
16 }
17
18 fn set_value(&mut self, value: &ProtobufValue) {
19 match value.as_any().downcast_ref::<V>() {
20 Some(v) => mem::replace(self, Some(v.clone())),
21 None => panic!(),
22 };
23 }
24}
25
26impl<V: ProtobufValue + Clone + 'static> ReflectOptional for SingularField<V> {
27 fn to_option(&self) -> Option<&ProtobufValue> {
28 self.as_ref().map(|v| v as &ProtobufValue)
29 }
30
31 fn set_value(&mut self, value: &ProtobufValue) {
32 match value.as_any().downcast_ref::<V>() {
33 Some(v) => mem::replace(self, SingularField::some(v.clone())),
34 None => panic!(),
35 };
36 }
37}
38
39impl<V: ProtobufValue + Clone + 'static> ReflectOptional for SingularPtrField<V> {
40 fn to_option(&self) -> Option<&ProtobufValue> {
41 self.as_ref().map(|v| v as &ProtobufValue)
42 }
43
44 fn set_value(&mut self, value: &ProtobufValue) {
45 match value.as_any().downcast_ref::<V>() {
46 Some(v) => mem::replace(self, SingularPtrField::some(v.clone())),
47 None => panic!(),
48 };
49 }
50}