1#![no_std]
17
18use core::fmt;
19use core::fmt::Write;
20
21pub struct Hex<'a, T: 'a>(&'a [T]);
22
23pub struct PlainHex<'a, T: 'a> {
24 slice: &'a [T],
25 with_spaces: bool,
26}
27
28pub trait AsHex {
29 type Item;
30 fn as_hex<'a>(&'a self) -> Hex<'a, Self::Item>;
31
32 fn plain_hex<'a>(&'a self, with_spaces: bool) -> PlainHex<'a, Self::Item>;
33}
34
35fn fmt_inner_hex<T, F: Fn(&T, &mut fmt::Formatter) -> fmt::Result>(slice: &[T], f: &mut fmt::Formatter, fmt_fn: F, with_spaces: bool) -> fmt::Result {
36 for (i, val) in slice.iter().enumerate() {
37 if with_spaces && i > 0 {
38 f.write_char(' ')?;
39 }
40 fmt_fn(val, f)?;
41 }
42 Ok(())
43}
44
45impl<'a, T> Hex<'a, T> {
46 pub fn hex(slice: &'a [T]) -> Hex<'a, T> {
47 Hex(slice)
48 }
49}
50
51impl<'a, T: fmt::LowerHex> fmt::LowerHex for Hex<'a, T> {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 write!(f, "[")?;
54 fmt_inner_hex(self.0, f, fmt::LowerHex::fmt, true)?;
55 write!(f, "]")
56 }
57}
58
59impl<'a, T: fmt::UpperHex> fmt::UpperHex for Hex<'a, T> {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 write!(f, "[")?;
62 fmt_inner_hex(self.0, f, fmt::UpperHex::fmt, true)?;
63 write!(f, "]")
64 }
65}
66
67impl<'a, T: fmt::LowerHex> fmt::LowerHex for PlainHex<'a, T> {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 fmt_inner_hex(self.slice, f, fmt::LowerHex::fmt, self.with_spaces)
70 }
71}
72
73impl<'a, T: fmt::UpperHex> fmt::UpperHex for PlainHex<'a, T> {
74 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 fmt_inner_hex(self.slice, f, fmt::UpperHex::fmt, self.with_spaces)
76 }
77}
78
79impl<T> AsHex for [T] {
80 type Item = T;
81 fn as_hex<'a>(&'a self) -> Hex<'a, Self::Item> {
82 Hex::hex(self)
83 }
84
85 fn plain_hex<'a>(&'a self, with_spaces: bool) -> PlainHex<'a, Self::Item> {
86 PlainHex {
87 slice: self,
88 with_spaces,
89 }
90 }
91}