Rust二进制数据可视化库nu-pretty-hex的使用:高效转换和美化Hex格式的字节流

Rust二进制数据可视化库nu-pretty-hex的使用:高效转换和美化Hex格式的字节流

nu-pretty-hex是一个Rust库,提供漂亮的十六进制转储功能。它是pretty-hex库的更新版本,使其更加美观。

功能特点

  • simple_hex():渲染单行十六进制转储
  • pretty_hex():渲染带地址和ASCII表示的多列多行十六进制转储
  • config_hex():以指定格式渲染十六进制转储

示例代码

1. simple_hex()示例

use pretty_hex::*;

let v = vec![222, 173, 190, 239, 202, 254, 32, 24];
assert_eq!(simple_hex(&v), format!("{}", v.hex_dump()));

println!("{}", v.hex_dump());

输出:

de ad be ef  ca fe 20 18

2. pretty_hex()示例

use pretty_hex::*;

let v: &[u8] = &random::<[u8;30]>();
assert_eq!(pretty_hex(&v), format!("{:?}", v.hex_dump()));

println!("{:?}", v.hex_dump());

输出:

Length: 30 (0x1e) bytes
0000:   6b 4e 1a c3  af 03 d2 1e  7e 73 ba c8  bd 84 0f 83   kN......~s......
0010:   89 d5 cf 90  23 67 4b 48  db b1 bc 35  bf ee         ....#gKH...5..

3. config_hex()示例

use pretty_hex::*;

let cfg = HexConfig {title: false, width: 8, group: 0, ..HexConfig::default() };

let v = &include_bytes!("data");
assert_eq!(config_hex(&v, cfg), format!("{:?}", v.hex_conf(cfg)));

println!("{:?}", v.hex_conf(cfg));

输出:

0000:   6b 4e 1a c3 af 03 d2 1e   kN......
0008:   7e 73 ba c8 bd 84 0f 83   ~s......
0010:   89 d5 cf 90 23 67 4b 48   ....#gKH
0018:   db b1 bc 35 bf ee         ...5..

完整示例demo

下面是一个完整的示例程序,展示如何使用nu-pretty-hex库的所有主要功能:

use pretty_hex::*;
use rand::random;

fn main() {
    // 示例1: 使用simple_hex()
    let data1 = vec![0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe];
    println!("Simple hex dump:");
    println!("{}", data1.hex_dump());
    println!();

    // 示例2: 使用pretty_hex()
    let data2: [u8; 32] = random();
    println!("Pretty hex dump:");
    println!("{:?}", data2.hex_dump());
    println!();

    // 示例3: 使用config_hex()自定义配置
    let cfg = HexConfig {
        title: true,       // 显示标题
        width: 16,         // 每行16字节
        group: 4,          // 每4字节一组
        ..HexConfig::default()
    };
    
    let data3 = include_bytes!("Cargo.toml"); // 读取项目文件作为示例数据
    println!("Custom configured hex dump:");
    println!("{:?}", data3.hex_conf(cfg));
}

这个示例展示了:

  1. 基本单行十六进制转储
  2. 带格式的多行转储,包含地址和ASCII表示
  3. 自定义配置的转储格式

要运行这个示例,需要在Cargo.toml中添加以下依赖:

[dependencies]
pretty-hex = "0.3.0"
rand = "0.8.5"

nu-pretty-hex库对于调试二进制数据、分析网络协议或文件格式非常有用,可以清晰直观地查看字节流内容。


1 回复

Rust二进制数据可视化库nu-pretty-hex使用指南

概述

nu-pretty-hex是一个Rust库,专门用于将二进制数据转换为美观且易读的十六进制格式。它特别适合调试、日志记录和数据可视化场景,能够高效地处理字节流并以直观的方式呈现。

主要特性

  • 高效的二进制到十六进制转换
  • 可定制的输出格式
  • 支持多种显示风格
  • 轻量级且无依赖

安装

在Cargo.toml中添加依赖:

[dependencies]
nu-pretty-hex = "0.1"

基本使用方法

简单示例

use nu_pretty_hex::*;

fn main() {
    let data = b"Hello, world!";
    println!("{}", pretty_hex(&data));
}

输出:

Length: 13 (0xd) bytes
0000:   48 65 6c 6c  6f 2c 20 77  6f 72 6c 64  21            Hello, world!

配置显示选项

use nu_pretty_hex::*;

fn main() {
    let data = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    
    let config = HexConfig {
        title: false,       // 不显示标题
        ascii: false,       // 不显示ASCII表示
        width: 8,          // 每行8字节
        group: 4,           // 每4字节一组
        ..HexConfig::simple()
    };
    
    println!("{}", pretty_hex_conf(&data, &config));
}

输出:

0000:   00 01 02 03  04 05 06 07
0008:   08 09 0a 0b  0c 0d 0e 0f

高级用法

完整示例:自定义格式的二进制数据查看器

use nu_pretty_hex::*;
use colored::*;
use std::fs::File;
use std::io::Read;

fn main() -> std::io::Result<()> {
    // 示例数据
    let sample_data = b"Rust二进制数据可视化示例\x00\x01\x02\x7F\x80\xFF";
    
    // 基本用法
    println!("=== 基本用法 ===");
    println!("{}", pretty_hex(&sample_data));
    
    // 自定义配置
    println!("\n=== 自定义配置 ===");
    let config = HexConfig {
        title: true,
        ascii: true,
        width: 8,
        group: 2,
        format: HexFormat {
            offset: "Offset: ".bright_blue().bold().to_string(),
            byte: |b| format!("{:02x}", b).bright_yellow().to_string(),
            ascii: |c| {
                if c.is_ascii_graphic() {
                    c.to_string().bright_green().to_string()
                } else {
                    ".".dimmed().to_string()
                }
            },
            ..HexFormat::default()
        },
        ..HexConfig::default()
    };
    println!("{}", pretty_hex_conf(&sample_data, &config));
    
    // 文件处理示例
    println!("\n=== 文件处理 ===");
    let mut file = File::open("example.bin")?;
    let mut buffer = [0; 64]; // 64字节缓冲区
    
    file.read_exact(&mut buffer)?;
    
    let file_config = HexConfig {
        title: true,
        ascii: true,
        width: 16,
        group: 4,
        format: HexFormat {
            offset: "位置: ".bright_white().bold().to_string(),
            byte: |b| format!("{:02X}", b).bright_magenta().to_string(),
            ascii: |c| {
                if c.is_ascii_alphanumeric() {
                    c.to_string().bright_cyan().to_string()
                } else {
                    "·".dimmed().to_string()
                }
            },
            ..HexFormat::default()
        },
        ..HexConfig::default()
    };
    
    println!("{}", pretty_hex_conf(&buffer, &file_config));
    
    Ok(())
}

输出示例

基本用法输出:

Length: 23 (0x17) bytes
0000:   52 75 73 74  e4 ba 8c e8  bf 9b e5 88  b6 e6 95 b0  Rust二进制数
0010:   e6 8d ae e5 8f af e8 a7  86 e5 8c 96  e7 a4 ba 00  据可视化示例.
0020:   01 02 7f 80  ff                                     .....

自定义配置输出:

Length: 23 (0x17) bytes
位置: 0000:   52 75  73 74  e4 ba  e8 bf  Rust·.·.
位置: 0008:   9b e5  88 b6  e6 95  b0 e6  ····0···
位置: 0010:   8d ae  e5 8f  af e8  a7 86  ········ 
位置: 0018:   e5 8c  96 e7  a4 ba  00 01  ······..
位置: 0020:   02 7f  80 ff                ····

配置选项详解

HexConfig结构体提供以下配置项:

  • title: 是否显示标题(默认true)
  • ascii: 是否显示ASCII表示(默认true)
  • width: 每行显示的字节数(默认16)
  • group: 分组大小(默认4)
  • chunk: 每行显示的块数(默认4)
  • format: 格式化选项(颜色、样式等)

性能提示

对于大型二进制数据,考虑以下优化:

  1. 使用pretty_hex_simple函数获取基本输出
  2. 禁用ASCII表示以提升速度
  3. 增大每行显示的字节数减少格式化开销
use nu_pretty_hex::*;

fn main() {
    let large_data = vec![0u8; 1024 * 1024]; // 1MB数据
    
    let config = HexConfig {
        ascii: false,
        width: 32,
        ..HexConfig::simple()
    };
    
    println!("{}", pretty_hex_conf(&large_data, &config));
}

总结

nu-pretty-hex是Rust中处理二进制数据可视化的强大工具,通过简单的API提供了丰富的格式化选项。无论是调试、日志记录还是数据分析,它都能帮助开发者更直观地理解二进制内容。

回到顶部