@@ -28,8 +28,13 @@ use std::{
2828use uuid:: Uuid ;
2929
3030pub enum DynTypeError {
31+ Empty ,
3132 NoConstructorContainerProvided ,
3233 NoConstructorForTypeUuid ( Uuid ) ,
34+ TypeCast {
35+ actual_type_name : & ' static str ,
36+ requested_type_name : & ' static str ,
37+ } ,
3338}
3439
3540impl DynTypeError {
@@ -55,6 +60,19 @@ impl Display for DynTypeError {
5560 there's no constructor provided for the {uuid} type!"
5661 )
5762 }
63+ DynTypeError :: Empty => {
64+ write ! ( f, "The container is empty" )
65+ }
66+ DynTypeError :: TypeCast {
67+ actual_type_name,
68+ requested_type_name,
69+ } => {
70+ write ! (
71+ f,
72+ "The actual type ({actual_type_name}) of the \
73+ dynamic type is different ({requested_type_name})."
74+ )
75+ }
5876 }
5977 }
6078}
@@ -207,6 +225,27 @@ impl DynTypeContainer {
207225 pub fn value_mut ( & mut self ) -> Option < & mut dyn DynType > {
208226 self . 0 . as_mut ( ) . map ( |v| & mut * v. 0 )
209227 }
228+
229+ pub fn data_ref < T : DynType > ( & self ) -> Result < & T , DynTypeError > {
230+ let value = self . value_ref ( ) . ok_or ( DynTypeError :: Empty ) ?;
231+ ( value as & dyn Any )
232+ . downcast_ref ( )
233+ . ok_or_else ( || DynTypeError :: TypeCast {
234+ actual_type_name : Reflect :: type_name ( value) ,
235+ requested_type_name : type_name :: < T > ( ) ,
236+ } )
237+ }
238+
239+ pub fn data_mut < T : DynType > ( & mut self ) -> Result < & mut T , DynTypeError > {
240+ let value = self . value_mut ( ) . ok_or ( DynTypeError :: Empty ) ?;
241+ let actual_type_name = Reflect :: type_name ( value) ;
242+ ( value as & mut dyn Any )
243+ . downcast_mut ( )
244+ . ok_or_else ( || DynTypeError :: TypeCast {
245+ actual_type_name,
246+ requested_type_name : type_name :: < T > ( ) ,
247+ } )
248+ }
210249}
211250
212251impl Visit for DynTypeContainer {
0 commit comments