use std::env;
use std::process;
use nbcs::checksum;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("用法: {} <十六进制字符串或以空格分割的十六进制值>", args[0]);
eprintln!("示例: {} 01020a0b0c", args[0]);
eprintln!("或者: {} 01 02 0a 0b 0c", args[0]);
eprintln!("或者: {} 1 2 a b c", args[0]);
process::exit(1);
}
let bytes = if args.len() == 2 {
let hex_string = &args[1];
match parse_hex_string(hex_string) {
Ok(bytes) => bytes,
Err(e) => {
eprintln!("错误: {}", e);
process::exit(1);
}
}
} else {
let hex_values = &args[1..];
match parse_hex_values(hex_values) {
Ok(bytes) => bytes,
Err(e) => {
eprintln!("错误: {}", e);
process::exit(1);
}
}
};
let result = checksum(&bytes);
println!("{:02x}", result);
}
fn parse_hex_string(hex: &str) -> Result<Vec<u8>, String> {
let hex = hex.trim().trim_start_matches("0x");
if hex.len() % 2 != 0 {
return Err("十六进制字符串长度必须是偶数".to_string());
}
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Err("包含无效的十六进制字符".to_string());
}
let mut bytes = Vec::new();
for chunk in hex.as_bytes().chunks(2) {
let hex_byte = std::str::from_utf8(chunk).unwrap();
let byte = u8::from_str_radix(hex_byte, 16).unwrap();
bytes.push(byte);
}
Ok(bytes)
}
fn parse_hex_values(hex_values: &[String]) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
for hex_value in hex_values {
let hex = hex_value.trim().trim_start_matches("0x");
if !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(format!("'{}' 包含无效的十六进制字符", hex_value));
}
match u8::from_str_radix(hex, 16) {
Ok(byte) => bytes.push(byte),
Err(_) => return Err(format!("'{}' 不是有效的8位十六进制值", hex_value)),
}
}
Ok(bytes)
}