IT’s Portfolio

[Rust] How to study Rust? - "Copycat" (4) 본문

Development Study/Rust

[Rust] How to study Rust? - "Copycat" (4)

f1r3_r41n 2023. 9. 23. 14:37
728x90
반응형

숫자 단어들에 대한 unsigned 정수를 구한 후 전체 합 출력(X'...' 형태 : 16진수, C'...' 형태 : ASCII 코드로 이루어진 16진수)


입력 파일

numb.s
81 B


소스 코드

use std::{fs, io::Read, error::Error, process};
use regex::Regex;

fn read_file() -> Result<String, Box<dyn Error>> {
    let mut f = fs::File::open("numb.s")?;
    let mut contents = String::new();
    f.read_to_string(&mut contents)?;

    Ok(contents)
}

fn split_contents(contents: &str) -> (Vec<u64>, Vec<u64>, Vec<u64>) {
    let mut hex = vec![];
    let mut ascii_hex = vec![];
    let mut dec = vec![];
    let re1 = Regex::new(r"X'([A-Z0-9]+?)'").unwrap();
    let re2 = Regex::new(r"C'([A-Z0-9]+?)'").unwrap();
    for token in contents.split_whitespace() {
        if re1.is_match(token) {
            let tmp = re1.captures(token).unwrap().get(1).unwrap().as_str();
            hex.push(u64::from_str_radix(tmp, 16).unwrap());
            println!("token: {token}\t\t\tdec: {}", u64::from_str_radix(tmp, 16).unwrap());
        } else if re2.is_match(token) {
            let mut t = String::new();
            let tmp = re2.captures(token).unwrap().get(1).unwrap().as_str();
            for b in tmp.bytes() {
                t.push_str(&format!("{b:X}"));
            }
            ascii_hex.push(u64::from_str_radix(&t, 16).unwrap());
            println!("token: {token}\thex: {t}\tdec: {}", u64::from_str_radix(&t, 16).unwrap());
        } else {
            println!("token: {token}\t\t\tdec: {token}");
            dec.push(token.parse::<u64>().unwrap());
        }
    }
    (hex, ascii_hex, dec)
}

fn main() {
    let contents = read_file().unwrap_or_else(
        |err| {
            eprintln!("Error!\n{err}");
            process::exit(1);
        }
    );
    let (hex, ascii_hex, dec) = split_contents(&contents);
    println!(
        "\nsum = {}",
        hex.iter().sum::<u64>() + ascii_hex.iter().sum::<u64>() + dec.iter().sum::<u64>()
    )
}

결과

token: X'323'                   dec: 803
token: C'EOF'   hex: 454F46     dec: 4542278
token: 2134                     dec: 2134
token: C'F1'    hex: 4631       dec: 17969
token: 78                       dec: 78
token: X'57'                    dec: 87
token: 98                       dec: 98
token: X'BA'                    dec: 186
token: C'05'    hex: 3035       dec: 12341
token: X'1CF'                   dec: 463
token: X'D12'                   dec: 3346
token: 9                        dec: 9
token: X'1234'                  dec: 4660
token: C'ABC'   hex: 414243     dec: 4276803

sum = 8861255

출처

728x90
반응형
Comments