1use std::iter::Iterator;
2
3pub const DEFAULT_INDENT: usize = 4;
4use crate::Error;
5
6#[cfg(feature = "debug")]
7pub fn format_bytes(bytes: &[u8], indent: Option<usize>) -> String {
8 let indent = indent.unwrap_or_else(|| DEFAULT_INDENT);
9 let padding = " ".repeat(indent);
10 fn pad(byte: u8, indent: usize) -> String {
11 let byte = byte.to_string();
12 let pad = " ".repeat(indent - (1 - byte.len()));
13 format!("{byte}{pad}")
14 }
15 format!(
16 "[\n{}{}\n]",
17 padding,
18 bytes
19 .iter()
20 .map(Clone::clone)
21 .map(|c| format!(
22 "{}{}, // {:#?}",
23 " ".repeat(indent + DEFAULT_INDENT),
24 pad(c, indent),
25 char::from(c)
26 ))
27 .collect::<Vec<String>>()
28 .join("\n"),
29 )
30}
31#[cfg(not(feature = "debug"))]
32pub fn format_bytes(bytes: &[u8], indent: Option<usize>) -> String {
33 let pad = " ".repeat(unwrap_indent(indent));
34 format!(
35 "{pad}[{}]",
36 bytes
37 .into_iter()
38 .map(|c| c.to_string())
39 .collect::<Vec<String>>()
40 .join(", ")
41 )
42}
43
44#[cfg(feature = "debug")]
45pub fn display_error<'e>(error: Error<'e>, ptr: *const u8, length: usize) {
46 let filename = file!();
47 let lineno = line!();
48 eprintln!("{filename}:{lineno} {error}");
49}
50#[cfg(not(feature = "debug"))]
51pub fn display_error<'e>(_error: Error<'e>, _ptr: *const u8, _length: usize) {}
52
53
54pub fn unwrap_indent(indent: Option<usize>) -> usize {
55 indent.unwrap_or_else(|| DEFAULT_INDENT)
56}