I would like to use raw byte argument with clap
For example --raw $(echo -n -e 'B\x10CC\x01\xff')
will give me the following bytes array [66, 16, 67, 67, 1, 239, 191, 189]
(using to_string_lossy().to_bytes()
).
Is there a way to get exact bytes array using clap?
EDIT
let cmd = Command::new(
env!("CARGO_CRATE_NAME")
).bin_name(
env!("CARGO_CRATE_NAME")
).arg(
Arg::new("raw").long("raw").takes_value(true).allow_invalid_utf8(true)
);
let matches = cmd.get_matches();
match matches.value_of_os("raw") {
Some(s) => {
match s.to_str() {
Some(s3) => {
let v2: &[u8] = s3.as_bytes();
println!("OsStr(bytes):{:?}", v2);
},
None => {},
}
let s2 = s.to_string_lossy();
println!("string_from_OsString:{}", s2);
let v3: &[u8] = s2.as_bytes();
println!("OsString.to_lossy(bytes):{:?}", v3);
},
None => {},
}
return for input --raw $(echo -n -e 'B\x10CC\x01\xff')
string_from_OsString:BCC�
OsString.to_lossy(bytes):[66, 16, 67, 67, 1, 239, 191, 189]
Thank you
clap
is platform agnostic and therefore uses abstractions likeOsString
(which is the type of yours
variable).There seems to be no generic
as_bytes()
method attached toOsString
, because not on every operating systemOsString
is actually a raw bytes array.Here is a lot more discussion about this very topic: How can I convert OsStr to &[u8]/Vec<u8> on Windows?
So to solve your problem, it seems necessary that you narrow your compatibility down to a specific operating system. In your case, it seems that you are using
Unix
. Which is great, because forUnix
, such a method does exist!Here you go:
Note that the
use std::os::unix::ffi::OsStrExt;
will add the.as_bytes()
functionality toOsString
, but will fail to compile on non-unix systems.