@@ -9,11 +9,11 @@ use serde::Deserialize;
9
9
#[ derive( Clone , Debug , Deserialize ) ]
10
10
#[ serde( try_from = "&str" ) ]
11
11
pub struct Amount {
12
- pub pence : u32 ,
12
+ pub pence : i64 ,
13
13
}
14
14
15
- impl From < u32 > for Amount {
16
- fn from ( pence : u32 ) -> Self {
15
+ impl From < i64 > for Amount {
16
+ fn from ( pence : i64 ) -> Self {
17
17
Amount { pence }
18
18
}
19
19
}
@@ -36,12 +36,11 @@ impl TryFrom<&str> for Amount {
36
36
}
37
37
}
38
38
39
- impl TryFrom < i64 > for Amount {
39
+ impl TryInto < u32 > for Amount {
40
40
type Error = TryFromIntError ;
41
41
42
- fn try_from ( value : i64 ) -> Result < Self , Self :: Error > {
43
- let pence = u32:: try_from ( value) ?;
44
- Ok ( Amount { pence } )
42
+ fn try_into ( self ) -> Result < u32 , Self :: Error > {
43
+ self . pence . try_into ( )
45
44
}
46
45
}
47
46
@@ -69,13 +68,14 @@ impl Display for Amount {
69
68
70
69
#[ cfg( test) ]
71
70
mod test {
71
+
72
72
use super :: * ;
73
73
74
74
#[ test]
75
75
fn format_currency_decimals ( ) {
76
76
let pence = 890 ;
77
77
78
- let value = Amount :: from ( pence) . to_string ( ) ;
78
+ let value = Amount { pence } . to_string ( ) ;
79
79
80
80
assert_eq ! ( value, "8.90" )
81
81
}
@@ -89,7 +89,7 @@ mod test {
89
89
] ;
90
90
91
91
for ( pence, expected) in cases {
92
- let value = Amount :: from ( pence) . to_string ( ) ;
92
+ let value = Amount { pence } . to_string ( ) ;
93
93
94
94
assert_eq ! ( value, expected) ;
95
95
}
@@ -99,7 +99,7 @@ mod test {
99
99
fn parse_currency_decimals ( ) {
100
100
let pence = "10.05" ;
101
101
102
- let value = Amount :: from_str ( pence)
102
+ let value = Amount :: try_from ( pence)
103
103
. expect ( "must parse fixed value" )
104
104
. pence ;
105
105
@@ -110,19 +110,28 @@ mod test {
110
110
fn parse_currency_separators ( ) {
111
111
let pence = "1,010.05" ;
112
112
113
- let value = Amount :: from_str ( pence)
113
+ let value = Amount :: try_from ( pence)
114
114
. expect ( "must parse fixed value" )
115
115
. pence ;
116
116
117
117
assert_eq ! ( value, 101005 ) ;
118
118
}
119
119
120
120
#[ test]
121
- fn try_from_i64 ( ) {
121
+ fn from_i64 ( ) {
122
122
let pence: i64 = 953578513525 ;
123
123
124
- let value = Amount :: try_from ( pence) ;
124
+ let value = Amount :: from ( pence) ;
125
+
126
+ assert_eq ! ( value. pence, pence) ;
127
+ }
128
+
129
+ #[ test]
130
+ fn try_into_u32 ( ) {
131
+ let pence = 1024 ;
132
+
133
+ let res: Result < u32 , _ > = Amount { pence } . try_into ( ) ;
125
134
126
- assert_eq ! ( value . is_err ( ) , true ) ;
135
+ assert_eq ! ( res . is_ok ( ) , true ) ;
127
136
}
128
137
}
0 commit comments