1
1
use crate :: ast:: Span ;
2
2
use itertools:: Itertools ;
3
3
use serde:: { Deserialize , Serialize } ;
4
- use std:: { convert :: TryFrom , fmt, iter:: FromIterator } ;
4
+ use std:: { fmt, iter:: FromIterator , str :: FromStr } ;
5
5
6
6
pub type Result < T > = std:: result:: Result < T , ConversionError > ;
7
7
@@ -34,7 +34,7 @@ impl From<String> for DynVal {
34
34
35
35
impl fmt:: Display for DynVal {
36
36
fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
37
- write ! ( f, "\" {} \" " , self . 0 )
37
+ write ! ( f, "{} " , self . 0 )
38
38
}
39
39
}
40
40
impl fmt:: Debug for DynVal {
@@ -70,32 +70,46 @@ impl std::str::FromStr for DynVal {
70
70
}
71
71
}
72
72
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 }
80
93
} ) *
81
94
} ;
82
95
}
83
- macro_rules! impl_primval_from {
96
+ macro_rules! impl_dynval_from {
84
97
( $( $t: ty) ,* ) => {
85
98
$( impl From <$t> for DynVal {
86
99
fn from( x: $t) -> Self { DynVal ( x. to_string( ) , None ) }
87
100
} ) *
88
101
} ;
89
102
}
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
- } ) ;
97
103
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 ) ;
99
113
100
114
impl From < & serde_json:: Value > for DynVal {
101
115
fn from ( v : & serde_json:: Value ) -> Self {
@@ -118,6 +132,10 @@ impl DynVal {
118
132
DynVal ( s, None )
119
133
}
120
134
135
+ pub fn read_as < E , T : FromDynVal < Err = E > > ( & self ) -> std:: result:: Result < T , E > {
136
+ T :: from_dynval ( self )
137
+ }
138
+
121
139
pub fn into_inner ( self ) -> String {
122
140
self . 0
123
141
}
0 commit comments