Chih-Hung Hsieh | cfc3a23 | 2020-06-10 20:13:05 -0700 | [diff] [blame] | 1 | use std::mem; |
| 2 | |
| 3 | use super::value::ProtobufValue; |
| 4 | |
Haibo Huang | d32e6ee | 2020-08-12 13:52:04 -0700 | [diff] [blame^] | 5 | use crate::singular::*; |
Chih-Hung Hsieh | cfc3a23 | 2020-06-10 20:13:05 -0700 | [diff] [blame] | 6 | |
| 7 | pub trait ReflectOptional: 'static { |
| 8 | fn to_option(&self) -> Option<&ProtobufValue>; |
| 9 | |
| 10 | fn set_value(&mut self, value: &ProtobufValue); |
| 11 | } |
| 12 | |
| 13 | impl<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 | |
| 26 | impl<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 | |
| 39 | impl<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 | } |