拍原始字节参数

Clap raw bytes arguments

我想在 clap 中使用原始字节参数

例如 --raw $(echo -n -e 'B\x10CC\x01\xff') 将给我以下字节数组 [66, 16, 67, 67, 1, 239, 191, 189](使用 to_string_lossy().to_bytes())。

有没有办法使用 clap 获取精确的字节数组?

编辑

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 用于输入 --raw $(echo -n -e 'B\x10CC\x01\xff')

string_from_OsString:BCC�
OsString.to_lossy(bytes):[66, 16, 67, 67, 1, 239, 191, 189]

谢谢

clap 与平台无关,因此使用像 OsString 这样的抽象(这是您的 s 变量的类型)。

似乎没有通用的 as_bytes() 方法附加到 OsString,因为并非在每个操作系统上 OsString 实际上是 字节数组。

这里有更多关于这个主题的讨论:

因此,要解决您的问题,似乎有必要将兼容性缩小到特定操作系统。在您的情况下,您似乎正在使用 Unix。这很棒,因为对于 Unix,这样的方法 does exist!

给你:

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]

请注意,use std::os::unix::ffi::OsStrExt; 会将 .as_bytes() 功能添加到 OsString,但无法在 non-unix 系统上编译。