nbcs 0.2.0

A simple checksum calculator for hexadecimal strings.
Documentation
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)
}