1 use std::mem; 2 3 use super::value::ProtobufValue; 4 5 use crate::singular::*; 6 7 pub trait ReflectOptional: 'static { to_option(&self) -> Option<&dyn ProtobufValue>8 fn to_option(&self) -> Option<&dyn ProtobufValue>; 9 set_value(&mut self, value: &dyn ProtobufValue)10 fn set_value(&mut self, value: &dyn ProtobufValue); 11 } 12 13 impl<V: ProtobufValue + Clone + 'static> ReflectOptional for Option<V> { to_option(&self) -> Option<&dyn ProtobufValue>14 fn to_option(&self) -> Option<&dyn ProtobufValue> { 15 self.as_ref().map(|v| v as &dyn ProtobufValue) 16 } 17 set_value(&mut self, value: &dyn ProtobufValue)18 fn set_value(&mut self, value: &dyn 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> { to_option(&self) -> Option<&dyn ProtobufValue>27 fn to_option(&self) -> Option<&dyn ProtobufValue> { 28 self.as_ref().map(|v| v as &dyn ProtobufValue) 29 } 30 set_value(&mut self, value: &dyn ProtobufValue)31 fn set_value(&mut self, value: &dyn 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> { to_option(&self) -> Option<&dyn ProtobufValue>40 fn to_option(&self) -> Option<&dyn ProtobufValue> { 41 self.as_ref().map(|v| v as &dyn ProtobufValue) 42 } 43 set_value(&mut self, value: &dyn ProtobufValue)44 fn set_value(&mut self, value: &dyn 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 } 51