I have this code:
#[derive(StructOpt)]
pub struct Opt {
/// Data stream to send to the device
#[structopt(help = "Data to send", parse(try_from_str = "parse_hex"))]
data: Vec<u8>,
}
fn parse_hex(s: &str) -> Result<u8, ParseIntError> {
u8::from_str_radix(s, 16)
}
This works for myexe AA BB
, but I need to take myexe AABB
as input.
Is there a way to pass a custom parser to structopt
to parse AABB
into a Vec<u8>
? I need to parse only the second form (no space).
I know I can do it in 2 steps (storing into a String
in the struct then parse it, but I like the idea that my Opt
has the final type for everything.
I tried a parser like this:
fn parse_hex_string(s: &str) -> Result<Vec<u8>, ParseIntError>
The StructOpt
macro panics about type mismatches because it seems to produce a Vec<Vec<u8>>
.
StructOpt makes the distinction that a
Vec<T>
will always map to multiple arguments:That means you need a single type to represent your data. Replace your
Vec<u8>
with a newtype:This leads to the error:
Let's implement
FromStr
:And it works: