serde_hkx_features/
dump.rs

1//! Dump binary data in hexadecimal
2use crate::{
3    error::{Error, Result},
4    fs::ReadExt as _,
5};
6pub use serde_hkx::bytes::hexdump;
7use std::path::Path;
8use tokio::fs;
9
10/// Output bytes to stdout/file.
11///
12/// # Errors
13/// If `output` is [`None`].(Unable to write bytes to stdout.)
14pub async fn to_bytes<I, O>(input: I, output: Option<O>) -> Result<()>
15where
16    I: AsRef<Path>,
17    O: AsRef<Path>,
18{
19    match output {
20        Some(output) => {
21            let bytes = hexdump::to_bytes(&input.read_any_string().await?);
22            fs::write(output, &bytes).await?;
23        }
24        None => return Err(Error::InvalidStdout),
25    };
26    Ok(())
27}
28
29/// Output hexdump to stdout/file.
30/// - `output`: If not provided, then stdout.
31///
32/// # Errors
33/// - If the path does not exist.
34/// - When an interrupt is received during reading.
35/// - No write permission to the given path.
36pub async fn to_string<I, O>(input: I, output: Option<O>) -> Result<()>
37where
38    I: AsRef<Path>,
39    O: AsRef<Path>,
40{
41    let hexdump = hexdump::to_string(input.read_bytes().await?); // NOTE: With newline.
42    match output {
43        Some(output) => fs::write(output, &hexdump).await?,
44        None => print!("{hexdump}"),
45    };
46    Ok(())
47}