[英]Clap raw bytes arguments
I would like to use raw byte argument with clap我想将原始字节参数与 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()
).例如--raw $(echo -n -e 'B\x10CC\x01\xff')
会给我以下字节数组[66, 16, 67, 67, 1, 239, 191, 189]
(使用to_string_lossy().to_bytes()
).
Is there a way to get exact bytes array using clap?有没有办法使用 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')
返回输入 --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 like OsString
(which is the type of your s
variable). clap
与平台无关,因此使用像OsString
这样的抽象(这是你s
变量的类型)。
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.似乎没有通用as_bytes()
方法附加到OsString
,因为并非在每个操作系统上OsString
实际上都是原始字节数组。
Here is a lot more discussion about this very topic: How can I convert OsStr to &[u8]/Vec<u8> on Windows?这里有更多关于这个主题的讨论: 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
.在您的情况下,您似乎正在使用Unix
。 Which is great, because for Unix
, such a method does exist !这很好,因为对于Unix
, 确实存在这样的方法!
Here you go:给你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;
注意use std::os::unix::ffi::OsStrExt;
will add the .as_bytes()
functionality to OsString
, but will fail to compile on non-unix systems.会将.as_bytes()
功能添加到OsString
,但无法在非 unix 系统上编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.