How to convert an array of bytes into an array of ASCII in Rust

1 Answer

0 votes
/// Validates a byte array at compile/runtime and ensures all elements are valid ASCII.
/// Returns the array wrapped in `Ok` if valid, or an error if invalid.
pub fn validate_ascii_array<const N: usize>(bytes: [u8; N]) -> Result<[u8; N], &'static str> {
    // .is_ascii() is an optimized standard library method for byte slices/arrays.
    if bytes.is_ascii() {
        Ok(bytes)
    } else {
        Err("Error: The byte array contains non-ASCII characters.")
    }
}

/// Converts a byte array into an array of Rust `char` types after verifying ASCII validity.
pub fn bytes_to_ascii_chars<const N: usize>(bytes: [u8; N]) -> Result<[char; N], &'static str> {
    if !bytes.is_ascii() {
        return Err("Error: Non-ASCII byte detected.");
    }
    
    // Initialize an array of null chars with the same size N using const generics
    let mut chars = ['\0'; N];
    
    // Safe to cast each u8 to char because we already verified .is_ascii()
    for (i, &b) in bytes.iter().enumerate() {
        chars[i] = b as char;
    }
    
    Ok(chars)
}

fn main() {
    // Example 1: Valid ASCII byte array using byte string syntax
    let ascii_bytes = *b"Rust"; // type is [u8; 4]

    match validate_ascii_array(ascii_bytes) {
        Ok(arr) => println!("Valid ASCII bytes: {:?}", arr),
        Err(e) => println!("{}", e),
    }

    // Example 2: Converting valid bytes into an array of `char`
    match bytes_to_ascii_chars(ascii_bytes) {
        Ok(char_array) => println!("Converted char array: {:?}", char_array),
        Err(e) => println!("{}", e),
    }

    // Example 3: Handling invalid ASCII (e.g., UTF-8 extended byte)
    let invalid_bytes: [u8; 3] = [72, 105, 255]; // 255 is out of ASCII range
    match validate_ascii_array(invalid_bytes) {
        Ok(arr) => println!("{:?}", arr),
        Err(e) => println!("Caught expected error: {}", e),
    }
}


/*
run:

ERROR!
Valid ASCII bytes: [82, 117, 115, 116]
Converted char array: ['R', 'u', 's', 't']
Caught expected error: Error: The byte array contains non-ASCII characters.

*/

 



answered 3 days ago by avibootz
...