11use crate :: ast:: Span ;
22use itertools:: Itertools ;
33use serde:: { Deserialize , Serialize } ;
4- use std:: { convert :: TryFrom , fmt, iter:: FromIterator } ;
4+ use std:: { fmt, iter:: FromIterator , str :: FromStr } ;
55
66pub type Result < T > = std:: result:: Result < T , ConversionError > ;
77
@@ -34,7 +34,7 @@ impl From<String> for DynVal {
3434
3535impl fmt:: Display for DynVal {
3636 fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
37- write ! ( f, "\" {} \" " , self . 0 )
37+ write ! ( f, "{} " , self . 0 )
3838 }
3939}
4040impl fmt:: Debug for DynVal {
@@ -70,32 +70,46 @@ impl std::str::FromStr for DynVal {
7070 }
7171}
7272
73- macro_rules! impl_try_from {
74- ( impl From <$typ: ty> {
75- $( for $for: ty => |$arg: ident| $code: expr) ;* ;
76- } ) => {
77- $( impl TryFrom <$typ> for $for {
78- type Error = ConversionError ;
79- fn try_from( $arg: $typ) -> std:: result:: Result <Self , Self :: Error > { $code }
73+ pub trait FromDynVal : Sized {
74+ type Err ;
75+ fn from_dynval ( x : & DynVal ) -> std:: result:: Result < Self , Self :: Err > ;
76+ }
77+
78+ impl < E , T : FromStr < Err = E > > FromDynVal for T {
79+ type Err = E ;
80+
81+ fn from_dynval ( x : & DynVal ) -> std:: result:: Result < Self , Self :: Err > {
82+ x. 0 . parse ( )
83+ }
84+ }
85+
86+ macro_rules! impl_from_dynval {
87+ (
88+ $( for $for: ty => |$name: ident| $code: expr) ;* ;
89+ ) => {
90+ $( impl FromDynVal for $for {
91+ type Err = ConversionError ;
92+ fn from_dynval( $name: DynVal ) -> std:: result:: Result <Self , Self :: Err > { $code }
8093 } ) *
8194 } ;
8295}
83- macro_rules! impl_primval_from {
96+ macro_rules! impl_dynval_from {
8497 ( $( $t: ty) ,* ) => {
8598 $( impl From <$t> for DynVal {
8699 fn from( x: $t) -> Self { DynVal ( x. to_string( ) , None ) }
87100 } ) *
88101 } ;
89102}
90- impl_try_from ! ( impl From <DynVal > {
91- for String => |x| x. as_string( ) ;
92- for f64 => |x| x. as_f64( ) ;
93- for i32 => |x| x. as_i32( ) ;
94- for bool => |x| x. as_bool( ) ;
95- //for Vec<String> => |x| x.as_vec();
96- } ) ;
97103
98- impl_primval_from ! ( bool , i32 , u32 , f32 , u8 , f64 , & str ) ;
104+ // impl_from_dynval! {
105+ // for String => |x| x.as_string();
106+ // for f64 => |x| x.as_f64();
107+ // for i32 => |x| x.as_i32();
108+ // for bool => |x| x.as_bool();
109+ ////for Vec<String> => |x| x.as_vec();
110+ //}
111+
112+ impl_dynval_from ! ( bool , i32 , u32 , f32 , u8 , f64 , & str ) ;
99113
100114impl From < & serde_json:: Value > for DynVal {
101115 fn from ( v : & serde_json:: Value ) -> Self {
@@ -118,6 +132,10 @@ impl DynVal {
118132 DynVal ( s, None )
119133 }
120134
135+ pub fn read_as < E , T : FromDynVal < Err = E > > ( & self ) -> std:: result:: Result < T , E > {
136+ T :: from_dynval ( self )
137+ }
138+
121139 pub fn into_inner ( self ) -> String {
122140 self . 0
123141 }
0 commit comments