1- use std:: { fmt:: Display , time:: Duration } ;
1+ use std:: { fmt:: Display , str :: FromStr , time:: Duration } ;
22
33use schemars:: JsonSchema ;
44use serde:: { Deserialize , Serialize } ;
@@ -181,7 +181,24 @@ pub struct Percentage {
181181}
182182
183183impl Percentage {
184- pub fn from_str ( s : & str ) -> Result < Self , String > {
184+ pub fn from_f64 ( value : f64 ) -> Result < Self , String > {
185+ if !( 0.0 ..=1.0 ) . contains ( & value) {
186+ return Err ( format ! (
187+ "Percentage value must be between 0 and 1, got: {}" ,
188+ value
189+ ) ) ;
190+ }
191+ Ok ( Percentage { value } )
192+ }
193+ pub fn as_f64 ( & self ) -> f64 {
194+ self . value
195+ }
196+ }
197+
198+ impl FromStr for Percentage {
199+ type Err = String ;
200+
201+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
185202 let s_trimmed = s. trim ( ) ;
186203 if let Some ( number_part) = s_trimmed. strip_suffix ( '%' ) {
187204 let value: f64 = number_part. parse ( ) . map_err ( |err| {
@@ -198,25 +215,13 @@ impl Percentage {
198215 ) )
199216 }
200217 }
201- pub fn from_f64 ( value : f64 ) -> Result < Self , String > {
202- if !( 0.0 ..=1.0 ) . contains ( & value) {
203- return Err ( format ! (
204- "Percentage value must be between 0 and 1, got: {}" ,
205- value
206- ) ) ;
207- }
208- Ok ( Percentage { value } )
209- }
210- pub fn as_f64 ( & self ) -> f64 {
211- self . value
212- }
213218}
214219
215220impl Display for Percentage {
216221 fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
217222 write ! ( f, "{}%" , self . value * 100.0 )
218223 }
219- }
224+ }
220225
221226// Deserializer from `n%` string to `Percentage` struct
222227impl < ' de > Deserialize < ' de > for Percentage {
0 commit comments