concept hexdump in category rust

appears as: hexdump, hexdump
Rust in Action

This is an excerpt from Manning's book Rust in Action.

7.3. Implementing a hexdump Clone

A very handy utility for inspecting files’ contents is hexdump. hexdump takes a stream of bytes, often from a file, then outputs those bytes in pairs of hexadecimal numbers. Table 7. 2 provides an example. As you’ll know from previous chapters, two hexadecimal numbers can represent all digits from 0 to 255, which is the number of bit patterns representable within a single byte. We’ll call our clone fview, short for file view.

Listing 7. 3. A hexdump clone with a hard-coded input that mocks file I/O. Demonstrates the use of multi-string literals and importing the std::io traits via std::io::prelude. This enables &[u8] types to be read as files, via the std::io::Read trait. (ch7/ch7-fview-str/src/main.rs)
use std::io::prelude::*;                              #1

const BYTES_PER_LINE: usize = 16;
const INPUT: &'static [u8] = br#"                      #2
fn main() {
    println!("Hello, world!)
}"#;

fn main() -> std::io::Result<()> {
    let mut buffer: Vec<u8> = vec!();                  #3
    INPUT.read_to_end(&mut buffer)?;                   #4

    let mut position_in_input = 0;
    for line in buffer.chunks(BYTES_PER_LINE) {
        print!("[0x{:08x}] ", position_in_input);      #5
        for byte in line {
            print!("{:02x} ", byte);
        }
        println!();                                    #6
        position_in_input += BYTES_PER_LINE;
    }

    Ok(())
}