Skip to content

Commit

Permalink
Pass the try_from_str functions a &str instead of a &String. (#282)
Browse files Browse the repository at this point in the history
In most cases this doesn't matter, as &String is coerced to a &str, but
this fails for generic functions like CString::new.
  • Loading branch information
m-ou-se authored and TeXitoi committed Nov 22, 2019
1 parent e84b1cb commit 1b998f5
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,7 @@
# Upcoming

* `try_from_str` functions are now called with a `&str` instead of a `&String` ([#282](https://github.com/TeXitoi/structopt/pull/282))

# v0.3.4 (2019-11-08)

* `rename_all` does not apply to fields that were annotated with explicit
Expand Down
2 changes: 1 addition & 1 deletion structopt-derive/src/lib.rs
Expand Up @@ -126,7 +126,7 @@ fn gen_augmentation(
let validator = match *parser.kind {
ParserKind::TryFromStr => quote_spanned! { func.span()=>
.validator(|s| {
#func(&s)
#func(s.as_str())
.map(|_: #convert_type| ())
.map_err(|e| e.to_string())
})
Expand Down
16 changes: 15 additions & 1 deletion tests/custom-string-parsers.rs
Expand Up @@ -8,7 +8,7 @@

use structopt::StructOpt;

use std::ffi::{OsStr, OsString};
use std::ffi::{CString, OsStr, OsString};
use std::num::ParseIntError;
use std::path::PathBuf;

Expand Down Expand Up @@ -290,3 +290,17 @@ fn test_custom_bool() {
Opt::from_iter(&["test", "-dtrue", "-bfalse", "-btrue", "-bfalse", "-bfalse"])
);
}

#[test]
fn test_cstring() {
#[derive(StructOpt)]
struct Opt {
#[structopt(parse(try_from_str = CString::new))]
c_string: CString,
}
assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err());
assert_eq!(Opt::from_iter(&["test", "bla"]).c_string.to_bytes(), b"bla");
assert!(Opt::clap()
.get_matches_from_safe(&["test", "bla\0bla"])
.is_err());
}

0 comments on commit 1b998f5

Please sign in to comment.