ctb_formats_hexdump/
hexdump.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Hex dump formatting utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29pub mod cli;
30
31use anyhow::{Result, anyhow};
32
33pub fn to_plain_hex_dump(data: &[u8]) -> String {
34    to_hex_dump(data)
35}
36
37pub fn to_hex_dump(data: &[u8]) -> String {
38    let mut out = String::new();
39    for (i, chunk) in data.chunks(16).enumerate() {
40        out.push_str(&format!("{:08x}: ", i.saturating_mul(16)));
41        for j in 0..16 {
42            if let Some(&b) = chunk.get(j) {
43                out.push_str(&format!("{b:02x} "));
44            } else {
45                out.push_str("   ");
46            }
47        }
48        out.push_str(" |");
49        for &b in chunk {
50            if (0x20..=0x7e).contains(&b) {
51                out.push(char::from(b));
52            } else {
53                out.push('.');
54            }
55        }
56        out.push_str("|\n");
57    }
58    out
59}
60
61pub fn to_xxd_hex_dump(data: &[u8]) -> String {
62    let mut out = String::new();
63    for (i, chunk) in data.chunks(16).enumerate() {
64        out.push_str(&format!("{:08x}: ", i.saturating_mul(16)));
65        let mut hex_col = String::new();
66        for (g_idx, group) in chunk.chunks(2).enumerate() {
67            if g_idx > 0 {
68                hex_col.push(' ');
69            }
70            for &b in group {
71                hex_col.push_str(&format!("{b:02x}"));
72            }
73        }
74        out.push_str(&hex_col);
75        let pad_len = 39usize.saturating_sub(hex_col.len());
76        for _ in 0..pad_len {
77            out.push(' ');
78        }
79        out.push_str("  ");
80        for &b in chunk {
81            if (0x20..=0x7e).contains(&b) {
82                out.push(char::from(b));
83            } else {
84                out.push('.');
85            }
86        }
87        out.push('\n');
88    }
89    out
90}
91
92pub fn to_fancy_hex_dump(data: &[u8]) -> String {
93    let mut out = String::new();
94    for (i, chunk) in data.chunks(16).enumerate() {
95        out.push_str(&format!("{:08x}: ", i.saturating_mul(16)));
96        for j in 0..16 {
97            if let Some(&b) = chunk.get(j) {
98                out.push_str(&format!("{b:02x} "));
99            } else {
100                out.push_str("   ");
101            }
102        }
103        out.push_str(" |");
104        for &b in chunk {
105            out.push(byte_to_graphical(b));
106        }
107        out.push_str("|\n");
108    }
109    out
110}
111
112#[expect(
113    clippy::expect_used,
114    reason = "CP437 mapping is defined for all u8 byte values 0..=255"
115)]
116pub fn byte_to_graphical(b: u8) -> char {
117    if b == 0 {
118        '␀'
119    } else if b == 1 {
120        '␁'
121    } else if b == 2 {
122        '␂'
123    } else if b == 3 {
124        '␃'
125    } else if b == 4 {
126        '␄'
127    } else if b == 5 {
128        '␅'
129    } else if b == 6 {
130        '␆'
131    } else if b == 7 {
132        '␇'
133    } else if b == 8 {
134        '␈'
135    } else if b == 9 {
136        '␉'
137    } else if b == 10 {
138        '␊'
139    } else if b == 11 {
140        '␋'
141    } else if b == 12 {
142        '␌'
143    } else if b == 13 {
144        '␍'
145    } else if b == 14 {
146        '␎'
147    } else if b == 15 {
148        '␏'
149    } else if b == 16 {
150        '␐'
151    } else if b == 17 {
152        '␑'
153    } else if b == 18 {
154        '␒'
155    } else if b == 19 {
156        '␓'
157    } else if b == 20 {
158        '␔'
159    } else if b == 21 {
160        '␕'
161    } else if b == 22 {
162        '␖'
163    } else if b == 23 {
164        '␗'
165    } else if b == 24 {
166        '␘'
167    } else if b == 25 {
168        '␙'
169    } else if b == 26 {
170        '␚'
171    } else if b == 27 {
172        '␛'
173    } else if b == 28 {
174        '␜'
175    } else if b == 29 {
176        '␝'
177    } else if b == 30 {
178        '␞'
179    } else if b == 31 {
180        '␟'
181    } else if b == 32 {
182        '␠'
183    } else if (33..=126).contains(&b) {
184        char::from(b)
185    } else if b == 127 {
186        '␡'
187    } else if b < 255 {
188        ctb_formats_encoding::chr_char(
189            ctb_formats_utilities::encoding::CharEncoding::cp437(),
190            b,
191        )
192        .expect("CP437 mapping is defined for all u8 byte values 0..=255")
193    } else {
194        '⍽'
195    }
196}
197
198/// Decodes a hexadecimal string into a byte vector.
199/// Decodes a hexadecimal string into a byte vector.
200///
201/// Any prefix of "0x" or "0X" is stripped, and whitespace or colons are ignored.
202pub fn hex2bin(s: &str) -> Result<Vec<u8>> {
203    let mut s = s.trim();
204    if let Some(stripped) = s.strip_prefix("0x") {
205        s = stripped;
206    } else if let Some(stripped) = s.strip_prefix("0X") {
207        s = stripped;
208    }
209    let clean: String = s
210        .chars()
211        .filter(|c| !c.is_whitespace() && *c != ':')
212        .collect();
213    hex::decode(&clean).map_err(|e| anyhow!("Failed to decode hex string: {e}"))
214}
215
216/// Encodes binary data into a lowercase hexadecimal string.
217pub fn bin2hex(data: &[u8]) -> String {
218    utilities::bin2hex(data)
219}
220
221#[cfg(test)]
222#[allow(
223    clippy::panic,
224    clippy::expect_used,
225    clippy::unwrap_used,
226    clippy::unwrap_in_result,
227    clippy::panic_in_result_fn,
228    clippy::indexing_slicing,
229    clippy::arithmetic_side_effects,
230    reason = "Standard repository test boilerplate"
231)]
232mod tests {
233    use super::*;
234
235    #[crate::ctb_test]
236    fn test_traditional_hexdump() {
237        let data = b"Hello, World!\x00\x01\xff";
238        let dump = to_hex_dump(data);
239        let expected = "00000000: 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 01 ff  |Hello, World!...|\n";
240        assert_eq!(dump, expected);
241    }
242
243    #[crate::ctb_test]
244    fn test_xxd_hexdump() {
245        let data = b"Hello, World!\x00\x01\xff";
246        let dump = to_xxd_hex_dump(data);
247        let expected = "00000000: 4865 6c6c 6f2c 2057 6f72 6c64 2100 01ff  Hello, World!...\n";
248        assert_eq!(dump, expected);
249
250        let partial = b"Hello";
251        let partial_dump = to_xxd_hex_dump(partial);
252        let expected_partial =
253            "00000000: 4865 6c6c 6f                             Hello\n";
254        assert_eq!(partial_dump, expected_partial);
255    }
256
257    #[crate::ctb_test]
258    fn test_fancy_hexdump() {
259        let data = b"Hello, World!\x00\x01\xff";
260        let dump = to_fancy_hex_dump(data);
261        // Note: 'H' is 'H' (72), '\x00' is '␀', '\x01' is '␁', '\xff' is ' ' (NBSP in CP437, code 160)
262        let expected = "00000000: 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 01 ff  |Hello,␠World!␀␁⍽|\n";
263        assert_eq!(dump, expected);
264    }
265
266    #[crate::ctb_test]
267    fn test_byte_to_graphical_all_bytes() {
268        // Verify every byte 0..=255 returns a unique character
269        let mut seen = std::collections::HashSet::new();
270        for b in 0u8..=255 {
271            let c = byte_to_graphical(b);
272            assert!(seen.insert(c), "Duplicate glyph found for byte {b}: {c}");
273        }
274        assert_eq!(seen.len(), 256);
275    }
276
277    #[crate::ctb_test]
278    fn test_hex2bin_and_bin2hex() {
279        let original = b"Hello, World!";
280        let encoded = bin2hex(original);
281        assert_eq!(encoded, "48656c6c6f2c20576f726c6421");
282
283        let decoded = hex2bin(&encoded).unwrap();
284        assert_eq!(decoded, original);
285
286        // Test with 0x prefix, whitespace, and colons
287        let complex = "0x48:65:6c:6c:6f 2c 20 57 6f 72 6c 64 21";
288        let decoded_complex = hex2bin(complex).unwrap();
289        assert_eq!(decoded_complex, original);
290
291        // Test invalid hex input
292        hex2bin("not a hex string").unwrap_err();
293    }
294}