'Clap raw bytes arguments
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
Solution 1:[1]
clap
is platform agnostic and therefore uses abstractions like OsString
(which is the type of your s
variable).
There seems to be no generic as_bytes()
method attached to OsString
, because not on every operating system OsString
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 for Unix
, such a method does exist!
Here you go:
use clap::{Arg, Command};
use std::os::unix::ffi::OsStrExt;
fn main() {
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) => {
println!(".as_bytes(): {:?}", s.as_bytes());
}
None => {}
}
}
.as_bytes(): [66, 16, 67, 67, 1, 255]
Note that the use std::os::unix::ffi::OsStrExt;
will add the .as_bytes()
functionality to OsString
, but will fail to compile on non-unix systems.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Finomnis |