summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: fb030d034f3c296a24aa3de18f8a0481cc8d4061 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use std::io::BufReader;
use std::{env, fs::File, io::Read};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    const CHUNK_SIZE: usize = 8;
    let mut file: Box<dyn Read>;

    file = if let Some(filename) = env::args().nth(1) {
        Box::new(BufReader::new(File::open(&filename)?))
    } else {
        Box::new(BufReader::new(std::io::stdin()))
    };

    let mut chunk = Vec::with_capacity(CHUNK_SIZE);
    let mut idx = 0;

    while {
        file.by_ref()
            .take(CHUNK_SIZE as u64)
            .read_to_end(&mut chunk)?
            > 0
    } {
        // write index
        print!("{:010}: ", idx);

        // write hex
        for byte in &chunk {
            print!("{:02X} ", byte);
        }

        // write ascii
        println!("{}", String::from_utf8_lossy(&chunk).replace('\n', "⏎"));
        idx += CHUNK_SIZE;
        chunk.clear();
    }

    Ok(())
}