Skip to content
This repository has been archived by the owner on Sep 14, 2023. It is now read-only.

Commit

Permalink
Fixes #175.
Browse files Browse the repository at this point in the history
  • Loading branch information
BurntSushi committed Apr 7, 2016
1 parent c74adba commit aa9d578
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/dopt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::error::Error as StdError;
use std::fmt;
use std::fmt::{self, Debug};
use std::str::FromStr;

use rustc_serialize::Decodable;

Expand Down Expand Up @@ -666,13 +667,14 @@ be one of `cmd_`, `flag_` or `arg_`.",
Ok(v)
}

fn to_number(&mut self, expect: &str) -> Result<u64, Error> {
fn to_number<T>(&mut self, expect: &str) -> Result<T, Error>
where T: FromStr + ToString, <T as FromStr>::Err: Debug {
let (k, v) = try!(self.pop_key_val());
match v {
Counted(n) => Ok(n),
Counted(n) => Ok(n.to_string().parse().unwrap()), // lol
_ => {
if v.as_str().trim().is_empty() {
Ok(0)
Ok("0".parse().unwrap()) // lol
} else {
match v.as_str().parse() {
Err(_) => {
Expand Down Expand Up @@ -704,7 +706,7 @@ be one of `cmd_`, `flag_` or `arg_`.",
macro_rules! read_num {
($name:ident, $ty:ty) => (
fn $name(&mut self) -> Result<$ty, Error> {
self.to_number(stringify!($ty)).map(|n| n as $ty)
self.to_number::<$ty>(stringify!($ty)).map(|n| n as $ty)
}
);
}
Expand Down
10 changes: 10 additions & 0 deletions src/test/testcases.docopt
Original file line number Diff line number Diff line change
Expand Up @@ -1086,3 +1086,13 @@ Options:
"""
$ program --all foo --all bar
"user-error"

r"""Usage: prog --speed=ARG"""
$ program --speed 20
{"--speed": "20"}
$ program --speed=20
{"--speed": "20"}
$ program --speed=-20
{"--speed": "-20"}
$ program --speed -20
{"--speed": "-20"}
8 changes: 8 additions & 0 deletions src/test/testcases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -781,3 +781,11 @@ test_user_error!(test_209_testcases, "Usage: prog [options]
Options:
--all ARG ... Foo", &["--all", "foo", "--all", "bar"]);

test_expect!(test_210_testcases, "Usage: prog --speed=ARG", &["--speed", "20"], vec!(("--speed", Plain(Some("20".to_string())))));

test_expect!(test_211_testcases, "Usage: prog --speed=ARG", &["--speed=20"], vec!(("--speed", Plain(Some("20".to_string())))));

test_expect!(test_212_testcases, "Usage: prog --speed=ARG", &["--speed=-20"], vec!(("--speed", Plain(Some("-20".to_string())))));

test_expect!(test_213_testcases, "Usage: prog --speed=ARG", &["--speed", "-20"], vec!(("--speed", Plain(Some("-20".to_string())))));

0 comments on commit aa9d578

Please sign in to comment.