1- use clap:: builder:: { TypedValueParser , ValueParserFactory } ;
21use derive_more:: { AsRef , Deref , Display , Into } ;
32use std:: {
43 convert:: { TryFrom , TryInto } ,
54 num:: ParseFloatError ,
65 str:: FromStr ,
76} ;
7+ use thiserror:: Error ;
88
99/// Floating-point value that is greater than or equal to 0 and less than 1.
1010#[ derive( Debug , Default , Clone , Copy , PartialEq , PartialOrd , AsRef , Deref , Display , Into ) ]
1111pub struct Fraction ( f32 ) ;
1212
1313/// Error that occurs when calling [`Fraction::new`].
14- #[ derive( Debug , Clone , Copy , PartialEq , Eq , Display ) ]
14+ #[ derive( Debug , Clone , Copy , PartialEq , Eq , Error ) ]
1515pub enum ConversionError {
1616 /// Provided value is greater than or equal to 1.
17- #[ display ( fmt = "greater than or equal to 1" ) ]
17+ #[ error ( "greater than or equal to 1" ) ]
1818 UpperBound ,
1919 /// Provided value is less than 0.
20- #[ display ( fmt = "less than 0" ) ]
20+ #[ error ( "less than 0" ) ]
2121 LowerBound ,
2222}
2323
@@ -42,7 +42,8 @@ impl TryFrom<f32> for Fraction {
4242 }
4343}
4444
45- #[ derive( Debug , Clone , PartialEq , Eq , Display ) ]
45+ #[ derive( Debug , Clone , PartialEq , Eq , Error ) ]
46+ #[ error( "{_0}" ) ]
4647pub enum FromStrError {
4748 ParseFloatError ( ParseFloatError ) ,
4849 Conversion ( ConversionError ) ,
@@ -57,39 +58,3 @@ impl FromStr for Fraction {
5758 . map_err ( FromStrError :: Conversion )
5859 }
5960}
60-
61- impl ValueParserFactory for Fraction {
62- type Parser = FractionValueParser ;
63- fn value_parser ( ) -> Self :: Parser {
64- FractionValueParser
65- }
66- }
67-
68- /// The [parser](ValueParserFactory::Parser) of [`Fraction`].
69- #[ derive( Debug , Clone ) ]
70- #[ non_exhaustive]
71- pub struct FractionValueParser ;
72-
73- impl TypedValueParser for FractionValueParser {
74- type Value = Fraction ;
75-
76- fn parse_ref (
77- & self ,
78- _: & clap:: Command ,
79- arg : Option < & clap:: Arg > ,
80- value : & std:: ffi:: OsStr ,
81- ) -> Result < Self :: Value , clap:: Error > {
82- let value = value
83- . to_str ( )
84- . ok_or_else ( || clap:: Error :: raw ( clap:: ErrorKind :: InvalidUtf8 , "Invalid UTF-8" ) ) ?;
85- value. parse ( ) . map_err ( |error| {
86- clap:: Error :: raw (
87- clap:: ErrorKind :: ValueValidation ,
88- format_args ! (
89- "Invalid value {value:?} for '{arg}': {error}\n \n For more information try --help\n " ,
90- arg = arg. map_or_else( || "..." . to_string( ) , |arg| arg. to_string( ) ) ,
91- ) ,
92- )
93- } )
94- }
95- }
0 commit comments