@@ -119,6 +119,7 @@ use std::ffi::OsStr;
119119use std:: fmt;
120120use std:: iter:: { repeat, IntoIterator } ;
121121use std:: result;
122+ use std:: str:: FromStr ;
122123
123124/// A description of the options that a program can handle.
124125pub struct Options {
@@ -841,6 +842,20 @@ impl Matches {
841842 }
842843 }
843844
845+ /// Returns the matching value or `None`.
846+ ///
847+ /// Similar to opt_default, except the two differences. Instead of
848+ /// returning None when option was not present, return `def`. Instead of
849+ /// returning &str slice return valued of type T parsed using str::parse().
850+ pub fn opt_get < T > ( & self , nm : & str , def : T )
851+ -> result:: Result < T , <T as FromStr >:: Err > where T : FromStr
852+ {
853+ match self . opt_val ( nm) {
854+ Some ( Val ( s) ) => s. parse ( ) ,
855+ Some ( Given ) => Ok ( def) ,
856+ None => Ok ( def) ,
857+ }
858+ }
844859}
845860
846861fn is_arg ( arg : & str ) -> bool {
@@ -2018,4 +2033,46 @@ Options:
20182033 Err ( e) => panic ! ( "{}" , e)
20192034 }
20202035 }
2036+
2037+ #[ test]
2038+ fn test_opt_default ( ) {
2039+ let mut opts = Options :: new ( ) ;
2040+ opts. optflag ( "h" , "help" , "Description" ) ;
2041+ opts. optflag ( "i" , "ignore" , "Description" ) ;
2042+ opts. optflag ( "r" , "run" , "Description" ) ;
2043+ opts. long_only ( false ) ;
2044+
2045+ let args: Vec < String > = [ "-i" , "-r" , "10" ]
2046+ . iter ( ) . map ( |x| x. to_string ( ) ) . collect ( ) ;
2047+ let matches = & match opts. parse ( & args) {
2048+ Ok ( m) => m,
2049+ Err ( e) => panic ! ( "{}" , e)
2050+ } ;
2051+ assert_eq ! ( matches. opt_default( "help" , "" ) , None ) ;
2052+ assert_eq ! ( matches. opt_default( "i" , "def" ) , Some ( "def" . to_string( ) ) ) ;
2053+ }
2054+
2055+ #[ test]
2056+ fn test_opt_get ( ) {
2057+ let mut opts = Options :: new ( ) ;
2058+ opts. optflag ( "h" , "help" , "Description" ) ;
2059+ opts. optflagopt ( "i" , "ignore" , "Description" , "true | false" ) ;
2060+ opts. optflagopt ( "r" , "run" , "Description" , "0 .. 10" ) ;
2061+ opts. optflagopt ( "p" , "percent" , "Description" , "0.0 .. 10.0" ) ;
2062+ opts. long_only ( false ) ;
2063+
2064+ let args: Vec < String > = [
2065+ "-i" , "true" , "-p" , "1.1"
2066+ ] . iter ( ) . map ( |x| x. to_string ( ) ) . collect ( ) ;
2067+ let matches = & match opts. parse ( & args) {
2068+ Ok ( m) => m,
2069+ Err ( e) => panic ! ( "{}" , e)
2070+ } ;
2071+ let h_arg =matches. opt_get ( "help" , 10 ) ;
2072+ assert_eq ! ( h_arg, Ok ( 10 ) ) ;
2073+ let i_arg = matches. opt_get ( "i" , false ) ;
2074+ assert_eq ! ( i_arg, Ok ( true ) ) ;
2075+ let p_arg = matches. opt_get ( "p" , 10.2 ) ;
2076+ assert_eq ! ( p_arg, Ok ( 1.1 ) ) ;
2077+ }
20212078}
0 commit comments