1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub use crate as ctb_formats_hexdump;
30use anyhow::{Context, Result};
31use std::path::{Path, PathBuf};
32
33#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
35#[command(
36 name = "hex2bin",
37 after_help = "Examples:\n $ ctoolbox hex2bin \"48656c6c6f\"\n Hello\n\n $ echo \"48 65 6c 6c 6f\" | ctoolbox hex2bin\n Hello\n\n $ ctoolbox hex2bin -f file.hex -o file.bin\n $ ctoolbox hex2bin \"48656c6c6f\" > output.bin"
38)]
39pub struct Hex2BinArgs {
40 pub value: Option<String>,
42 #[arg(short = 'f', long = "file")]
44 pub file: Option<PathBuf>,
45 #[arg(short = 'o', long = "output")]
47 pub output: Option<PathBuf>,
48}
49
50#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
52#[command(
53 name = "bin2hex",
54 after_help = "Examples:\n $ ctoolbox bin2hex \"Hello\"\n 48656c6c6f\n\n $ echo -n \"Hello\" | ctoolbox bin2hex\n 48656c6c6f\n\n $ cat file.exe | ctoolbox bin2hex\n 4d5a...\n\n $ ctoolbox bin2hex -f file.bin -o file.hex\n $ ctoolbox bin2hex --hd -f file.bin\n $ ctoolbox bin2hex --hf \"Hello\"\n $ ctoolbox bin2hex --xxd \"Hello\""
55)]
56pub struct Bin2HexArgs {
57 pub value: Option<String>,
59 #[arg(short = 'f', long = "file")]
61 pub file: Option<PathBuf>,
62 #[arg(short = 'o', long = "output")]
64 pub output: Option<PathBuf>,
65 #[arg(long = "hd", conflicts_with = "hf", conflicts_with = "xxd")]
67 pub hd: bool,
68 #[arg(long = "hf", conflicts_with = "hd", conflicts_with = "xxd")]
70 pub hf: bool,
71 #[arg(long = "xxd", conflicts_with = "hd", conflicts_with = "hf")]
73 pub xxd: bool,
74}
75
76#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
78#[command(
79 name = "hexdump",
80 after_help = "Examples:\n $ ctoolbox hexdump \"Hello\"\n $ ctoolbox hd -f file.bin\n $ ctoolbox hexdump --plain \"Hello\"\n $ ctoolbox hexdump --xxd \"Hello\""
81)]
82pub struct HexDumpArgs {
83 pub value: Option<String>,
85 #[arg(short = 'f', long = "file")]
87 pub file: Option<PathBuf>,
88 #[arg(short = 'o', long = "output")]
90 pub output: Option<PathBuf>,
91 #[arg(long = "plain", conflicts_with = "xxd")]
93 pub plain: bool,
94 #[arg(long = "xxd", conflicts_with = "plain")]
96 pub xxd: bool,
97}
98
99#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
101#[command(
102 name = "xxd",
103 after_help = "Examples:\n $ ctoolbox xxd \"Hello\"\n $ echo -n \"Hello\" | ctoolbox xxd\n $ ctoolbox xxd -f file.bin -o file.hex\n $ ctoolbox xxd --plain \"Hello\"\n $ ctoolbox xxd --fancy \"Hello\""
104)]
105pub struct XxdArgs {
106 pub value: Option<String>,
108 #[arg(short = 'f', long = "file")]
110 pub file: Option<PathBuf>,
111 #[arg(short = 'o', long = "output")]
113 pub output: Option<PathBuf>,
114 #[arg(long = "plain", conflicts_with = "fancy")]
116 pub plain: bool,
117 #[arg(long = "fancy", conflicts_with = "plain")]
119 pub fancy: bool,
120}
121
122pub type CliHex2BinArgs = Hex2BinArgs;
123pub type CliBin2HexArgs = Bin2HexArgs;
124pub type CliHexDumpArgs = HexDumpArgs;
125pub type CliXxdArgs = XxdArgs;
126
127pub fn execute_cli_hex2bin<FRead>(
132 args: Hex2BinArgs,
133 read_data: FRead,
134) -> Result<Option<Vec<u8>>>
135where
136 FRead: Fn(&Path) -> Result<Vec<u8>>,
137{
138 let input_bytes = if let Some(ref file_path) = args.file {
139 read_data(file_path)?
140 } else if let Some(ref val) = args.value {
141 val.as_bytes().to_vec()
142 } else {
143 read_data(Path::new("-"))?
144 };
145
146 let input_str =
147 String::from_utf8(input_bytes).context("Input is not valid UTF-8")?;
148 let decoded = crate::hex2bin(&input_str)?;
149
150 if let Some(ref out_path) = args.output {
151 if out_path.as_path() == Path::new("-") {
152 Ok(Some(decoded))
153 } else {
154 std::fs::write(out_path, &decoded).with_context(|| {
155 format!(
156 "Failed to write output file: {path_display}",
157 path_display = out_path.display()
158 )
159 })?;
160 Ok(None)
161 }
162 } else {
163 Ok(Some(decoded))
164 }
165}
166
167pub fn execute_cli_bin2hex<FRead>(
172 args: Bin2HexArgs,
173 read_data: FRead,
174) -> Result<Option<Vec<u8>>>
175where
176 FRead: Fn(&Path) -> Result<Vec<u8>>,
177{
178 let input_bytes = if let Some(ref file_path) = args.file {
179 read_data(file_path)?
180 } else if let Some(ref val) = args.value {
181 val.as_bytes().to_vec()
182 } else {
183 read_data(Path::new("-"))?
184 };
185
186 let encoded = if args.hd {
187 crate::to_hex_dump(&input_bytes)
188 } else if args.hf {
189 crate::to_fancy_hex_dump(&input_bytes)
190 } else if args.xxd {
191 crate::to_xxd_hex_dump(&input_bytes)
192 } else {
193 crate::bin2hex(&input_bytes)
194 };
195
196 if let Some(ref out_path) = args.output {
197 if out_path.as_path() == Path::new("-") {
198 Ok(Some(encoded.into_bytes()))
199 } else {
200 std::fs::write(out_path, encoded.as_bytes()).with_context(
201 || {
202 format!(
203 "Failed to write output file: {path_display}",
204 path_display = out_path.display()
205 )
206 },
207 )?;
208 Ok(None)
209 }
210 } else {
211 Ok(Some(encoded.into_bytes()))
212 }
213}
214
215pub fn execute_cli_hexdump<FRead>(
219 args: HexDumpArgs,
220 read_data: FRead,
221) -> Result<Option<Vec<u8>>>
222where
223 FRead: Fn(&Path) -> Result<Vec<u8>>,
224{
225 let input_bytes = if let Some(ref file_path) = args.file {
226 read_data(file_path)?
227 } else if let Some(ref val) = args.value {
228 val.as_bytes().to_vec()
229 } else {
230 read_data(Path::new("-"))?
231 };
232
233 let dump = if args.plain {
234 crate::to_hex_dump(&input_bytes)
235 } else if args.xxd {
236 crate::to_xxd_hex_dump(&input_bytes)
237 } else {
238 crate::to_fancy_hex_dump(&input_bytes)
239 };
240
241 if let Some(ref out_path) = args.output {
242 if out_path.as_path() == Path::new("-") {
243 Ok(Some(dump.into_bytes()))
244 } else {
245 std::fs::write(out_path, dump.as_bytes()).with_context(|| {
246 format!(
247 "Failed to write output file: {path_display}",
248 path_display = out_path.display()
249 )
250 })?;
251 Ok(None)
252 }
253 } else {
254 Ok(Some(dump.into_bytes()))
255 }
256}
257
258pub fn execute_cli_xxd<FRead>(
262 args: XxdArgs,
263 read_data: FRead,
264) -> Result<Option<Vec<u8>>>
265where
266 FRead: Fn(&Path) -> Result<Vec<u8>>,
267{
268 let input_bytes = if let Some(ref file_path) = args.file {
269 read_data(file_path)?
270 } else if let Some(ref val) = args.value {
271 val.as_bytes().to_vec()
272 } else {
273 read_data(Path::new("-"))?
274 };
275
276 let dump = if args.plain {
277 crate::to_hex_dump(&input_bytes)
278 } else if args.fancy {
279 crate::to_fancy_hex_dump(&input_bytes)
280 } else {
281 crate::to_xxd_hex_dump(&input_bytes)
282 };
283
284 if let Some(ref out_path) = args.output {
285 if out_path.as_path() == Path::new("-") {
286 Ok(Some(dump.into_bytes()))
287 } else {
288 std::fs::write(out_path, dump.as_bytes()).with_context(|| {
289 format!(
290 "Failed to write output file: {path_display}",
291 path_display = out_path.display()
292 )
293 })?;
294 Ok(None)
295 }
296 } else {
297 Ok(Some(dump.into_bytes()))
298 }
299}
300
301#[cfg(test)]
302#[allow(
303 clippy::panic,
304 clippy::expect_used,
305 clippy::unwrap_used,
306 clippy::unwrap_in_result,
307 clippy::panic_in_result_fn,
308 clippy::indexing_slicing,
309 clippy::arithmetic_side_effects,
310 reason = "Standard repository test boilerplate"
311)]
312mod tests {
313 use super::*;
314 use clap::{Args, Command, FromArgMatches};
315
316 #[crate::ctb_test]
317 fn test_hex2bin_cli_args_parsing() {
318 let cmd = Hex2BinArgs::augment_args(Command::new("hex2bin"));
319 let matches = cmd
320 .try_get_matches_from(["hex2bin", "48656c6c6f"])
321 .expect("Parse hex2bin value");
322 let parsed = Hex2BinArgs::from_arg_matches(&matches).unwrap();
323 assert_eq!(parsed.value, Some("48656c6c6f".to_string()));
324 assert_eq!(parsed.file, None);
325 assert_eq!(parsed.output, None);
326
327 let cmd2 = Hex2BinArgs::augment_args(Command::new("hex2bin"));
328 let matches2 = cmd2
329 .try_get_matches_from(["hex2bin", "-f", "in.hex", "-o", "out.bin"])
330 .expect("Parse hex2bin with flags");
331 let parsed_flags = Hex2BinArgs::from_arg_matches(&matches2).unwrap();
332 assert_eq!(parsed_flags.file, Some(PathBuf::from("in.hex")));
333 assert_eq!(parsed_flags.output, Some(PathBuf::from("out.bin")));
334 }
335
336 #[crate::ctb_test]
337 fn test_bin2hex_cli_args_parsing() {
338 let cmd = Bin2HexArgs::augment_args(Command::new("bin2hex"));
339 let matches = cmd
340 .try_get_matches_from(["bin2hex", "Hello"])
341 .expect("Parse bin2hex value");
342 let parsed = Bin2HexArgs::from_arg_matches(&matches).unwrap();
343 assert_eq!(parsed.value, Some("Hello".to_string()));
344 assert_eq!(parsed.file, None);
345 assert_eq!(parsed.output, None);
346 assert!(!parsed.hd);
347 assert!(!parsed.hf);
348 assert!(!parsed.xxd);
349
350 let cmd_hd = Bin2HexArgs::augment_args(Command::new("bin2hex"));
351 let matches_hd = cmd_hd
352 .try_get_matches_from([
353 "bin2hex", "-f", "in.bin", "-o", "out.hex", "--hd",
354 ])
355 .expect("Parse bin2hex with --hd");
356 let parsed_hd = Bin2HexArgs::from_arg_matches(&matches_hd).unwrap();
357 assert_eq!(parsed_hd.file, Some(PathBuf::from("in.bin")));
358 assert_eq!(parsed_hd.output, Some(PathBuf::from("out.hex")));
359 assert!(parsed_hd.hd);
360 assert!(!parsed_hd.hf);
361 assert!(!parsed_hd.xxd);
362
363 let cmd_hf = Bin2HexArgs::augment_args(Command::new("bin2hex"));
364 let matches_hf = cmd_hf
365 .try_get_matches_from(["bin2hex", "--hf"])
366 .expect("Parse bin2hex with --hf");
367 let parsed_hf = Bin2HexArgs::from_arg_matches(&matches_hf).unwrap();
368 assert!(!parsed_hf.hd);
369 assert!(parsed_hf.hf);
370 assert!(!parsed_hf.xxd);
371
372 let cmd_xxd = Bin2HexArgs::augment_args(Command::new("bin2hex"));
373 let matches_xxd = cmd_xxd
374 .try_get_matches_from(["bin2hex", "--xxd"])
375 .expect("Parse bin2hex with --xxd");
376 let parsed_xxd = Bin2HexArgs::from_arg_matches(&matches_xxd).unwrap();
377 assert!(!parsed_xxd.hd);
378 assert!(!parsed_xxd.hf);
379 assert!(parsed_xxd.xxd);
380
381 let cmd_conflict = Bin2HexArgs::augment_args(Command::new("bin2hex"));
383 cmd_conflict
384 .try_get_matches_from(["bin2hex", "--hd", "--hf"])
385 .unwrap_err();
386 let cmd_conflict2 = Bin2HexArgs::augment_args(Command::new("bin2hex"));
387 cmd_conflict2
388 .try_get_matches_from(["bin2hex", "--hd", "--xxd"])
389 .unwrap_err();
390 }
391
392 #[crate::ctb_test]
393 fn test_hexdump_and_xxd_cli_args_parsing() {
394 let cmd_hd = HexDumpArgs::augment_args(Command::new("hexdump"));
395 let matches_hd = cmd_hd
396 .try_get_matches_from(["hexdump", "Hello"])
397 .expect("Parse hexdump default");
398 let parsed_hd = HexDumpArgs::from_arg_matches(&matches_hd).unwrap();
399 assert_eq!(parsed_hd.value, Some("Hello".to_string()));
400 assert!(!parsed_hd.plain);
401 assert!(!parsed_hd.xxd);
402
403 let cmd_hd_plain = HexDumpArgs::augment_args(Command::new("hexdump"));
404 let matches_hd_plain = cmd_hd_plain
405 .try_get_matches_from(["hexdump", "--plain", "Hello"])
406 .expect("Parse hexdump --plain");
407 let parsed_hd_plain =
408 HexDumpArgs::from_arg_matches(&matches_hd_plain).unwrap();
409 assert!(parsed_hd_plain.plain);
410 assert!(!parsed_hd_plain.xxd);
411
412 let cmd_hd_xxd = HexDumpArgs::augment_args(Command::new("hexdump"));
413 let matches_hd_xxd = cmd_hd_xxd
414 .try_get_matches_from(["hexdump", "--xxd", "Hello"])
415 .expect("Parse hexdump --xxd");
416 let parsed_hd_xxd =
417 HexDumpArgs::from_arg_matches(&matches_hd_xxd).unwrap();
418 assert!(!parsed_hd_xxd.plain);
419 assert!(parsed_hd_xxd.xxd);
420
421 let cmd_hd_conflict =
422 HexDumpArgs::augment_args(Command::new("hexdump"));
423 cmd_hd_conflict
424 .try_get_matches_from(["hexdump", "--plain", "--xxd", "Hello"])
425 .unwrap_err();
426
427 let cmd_xxd = XxdArgs::augment_args(Command::new("xxd"));
428 let matches_xxd = cmd_xxd
429 .try_get_matches_from(["xxd", "Hello"])
430 .expect("Parse xxd default");
431 let parsed_xxd = XxdArgs::from_arg_matches(&matches_xxd).unwrap();
432 assert_eq!(parsed_xxd.value, Some("Hello".to_string()));
433 assert!(!parsed_xxd.plain);
434 assert!(!parsed_xxd.fancy);
435
436 let cmd_xxd_plain = XxdArgs::augment_args(Command::new("xxd"));
437 let matches_xxd_plain = cmd_xxd_plain
438 .try_get_matches_from(["xxd", "--plain", "Hello"])
439 .expect("Parse xxd --plain");
440 let parsed_xxd_plain =
441 XxdArgs::from_arg_matches(&matches_xxd_plain).unwrap();
442 assert!(parsed_xxd_plain.plain);
443 assert!(!parsed_xxd_plain.fancy);
444 }
445
446 #[crate::ctb_test]
447 fn test_execute_cli_hex2bin_direct() {
448 let args = Hex2BinArgs {
449 value: Some("48656c6c6f".to_string()),
450 file: None,
451 output: None,
452 };
453 let out = execute_cli_hex2bin(args, |_| Ok(Vec::new())).unwrap();
454 assert_eq!(out, Some(b"Hello".to_vec()));
455 }
456
457 #[crate::ctb_test]
458 fn test_execute_cli_hex2bin_file_io() {
459 let temp_dir = tempfile::tempdir().expect("Create temp dir");
460 let in_path = temp_dir.path().join("in.hex");
461 let out_path = temp_dir.path().join("out.bin");
462
463 std::fs::write(&in_path, b"48656c6c6f").expect("Write input file");
464
465 let args = Hex2BinArgs {
466 value: None,
467 file: Some(in_path.clone()),
468 output: Some(out_path.clone()),
469 };
470 let out = execute_cli_hex2bin(args, |p| Ok(std::fs::read(p)?)).unwrap();
471 assert_eq!(out, None);
472
473 let written = std::fs::read(out_path).expect("Read output file");
474 assert_eq!(written, b"Hello");
475 }
476
477 #[crate::ctb_test]
478 fn test_execute_cli_bin2hex_direct() {
479 let args = Bin2HexArgs {
480 value: Some("Hello".to_string()),
481 file: None,
482 output: None,
483 hd: false,
484 hf: false,
485 xxd: false,
486 };
487 let out = execute_cli_bin2hex(args, |_| Ok(Vec::new())).unwrap();
488 assert_eq!(out, Some(b"48656c6c6f".to_vec()));
489 }
490
491 #[crate::ctb_test]
492 fn test_execute_cli_hexdump_and_xxd_execution() {
493 let data = b"Hello, World!\x00\x01\xff";
494
495 let args_hd_default = HexDumpArgs {
497 value: None,
498 file: None,
499 output: None,
500 plain: false,
501 xxd: false,
502 };
503 let out_hd_default =
504 execute_cli_hexdump(args_hd_default, |_| Ok(data.to_vec()))
505 .unwrap();
506 assert_eq!(
507 out_hd_default,
508 Some(crate::to_fancy_hex_dump(data).into_bytes())
509 );
510
511 let args_hd_plain = HexDumpArgs {
513 value: None,
514 file: None,
515 output: None,
516 plain: true,
517 xxd: false,
518 };
519 let out_hd_plain =
520 execute_cli_hexdump(args_hd_plain, |_| Ok(data.to_vec())).unwrap();
521 assert_eq!(out_hd_plain, Some(crate::to_hex_dump(data).into_bytes()));
522
523 let args_hd_xxd = HexDumpArgs {
525 value: None,
526 file: None,
527 output: None,
528 plain: false,
529 xxd: true,
530 };
531 let out_hd_xxd =
532 execute_cli_hexdump(args_hd_xxd, |_| Ok(data.to_vec())).unwrap();
533 assert_eq!(out_hd_xxd, Some(crate::to_xxd_hex_dump(data).into_bytes()));
534
535 let args_xxd_default = XxdArgs {
537 value: None,
538 file: None,
539 output: None,
540 plain: false,
541 fancy: false,
542 };
543 let out_xxd_default =
544 execute_cli_xxd(args_xxd_default, |_| Ok(data.to_vec())).unwrap();
545 assert_eq!(
546 out_xxd_default,
547 Some(crate::to_xxd_hex_dump(data).into_bytes())
548 );
549
550 let args_xxd_fancy = XxdArgs {
552 value: None,
553 file: None,
554 output: None,
555 plain: false,
556 fancy: true,
557 };
558 let out_xxd_fancy =
559 execute_cli_xxd(args_xxd_fancy, |_| Ok(data.to_vec())).unwrap();
560 assert_eq!(
561 out_xxd_fancy,
562 Some(crate::to_fancy_hex_dump(data).into_bytes())
563 );
564 }
565
566 #[crate::ctb_test]
567 fn test_hex2bin_and_bin2hex_commands() {
568 let args = Hex2BinArgs {
569 value: Some("48656c6c6f".to_string()),
570 file: None,
571 output: None,
572 };
573 let out = execute_cli_hex2bin(args, |p| Ok(std::fs::read(p)?))
574 .expect("Run hex2bin");
575 assert_eq!(out, Some(b"Hello".to_vec()));
576
577 let args2 = Bin2HexArgs {
578 value: Some("Hello".to_string()),
579 file: None,
580 output: None,
581 hd: false,
582 hf: false,
583 xxd: false,
584 };
585 let out2 = execute_cli_bin2hex(args2, |p| Ok(std::fs::read(p)?))
586 .expect("Run bin2hex");
587 assert_eq!(out2, Some(b"48656c6c6f".to_vec()));
588
589 let args_hd = HexDumpArgs {
590 value: Some("Hello".to_string()),
591 file: None,
592 output: None,
593 plain: false,
594 xxd: false,
595 };
596 let out_hd = execute_cli_hexdump(args_hd, |p| Ok(std::fs::read(p)?))
597 .expect("Run hexdump");
598 assert_eq!(
599 out_hd,
600 Some(ctb_formats_hexdump::to_fancy_hex_dump(b"Hello").into_bytes())
601 );
602
603 let args_hd_plain = HexDumpArgs {
604 value: Some("Hello".to_string()),
605 file: None,
606 output: None,
607 plain: true,
608 xxd: false,
609 };
610 let out_hd_plain =
611 execute_cli_hexdump(args_hd_plain, |p| Ok(std::fs::read(p)?))
612 .expect("Run hexdump --plain");
613 assert_eq!(
614 out_hd_plain,
615 Some(ctb_formats_hexdump::to_hex_dump(b"Hello").into_bytes())
616 );
617
618 let args_hd_xxd = HexDumpArgs {
619 value: Some("Hello".to_string()),
620 file: None,
621 output: None,
622 plain: false,
623 xxd: true,
624 };
625 let out_hd_xxd =
626 execute_cli_hexdump(args_hd_xxd, |p| Ok(std::fs::read(p)?))
627 .expect("Run hexdump --xxd");
628 assert_eq!(
629 out_hd_xxd,
630 Some(ctb_formats_hexdump::to_xxd_hex_dump(b"Hello").into_bytes())
631 );
632
633 let args_xxd = XxdArgs {
634 value: Some("Hello".to_string()),
635 file: None,
636 output: None,
637 plain: false,
638 fancy: false,
639 };
640 let out_xxd = execute_cli_xxd(args_xxd, |p| Ok(std::fs::read(p)?))
641 .expect("Run xxd");
642 assert_eq!(
643 out_xxd,
644 Some(ctb_formats_hexdump::to_xxd_hex_dump(b"Hello").into_bytes())
645 );
646 }
647}