| 1 | //! The purpose of this crate is to extend the `UpperHex` and `LowerHex` |
| 2 | //! traits to slices, as well as the integers it is currently implemented for. |
| 3 | //! |
| 4 | //! # Examples |
| 5 | //! |
| 6 | //! ```rust |
| 7 | //! extern crate hex_slice; |
| 8 | //! use hex_slice::AsHex; |
| 9 | //! |
| 10 | //! fn main() { |
| 11 | //! let foo = vec![0u32, 1 ,2 ,3]; |
| 12 | //! println!("{:x}", foo.as_hex()); |
| 13 | //! } |
| 14 | //! ``` |
| 15 | |
| 16 | #![no_std] |
| 17 | |
| 18 | use core::fmt; |
| 19 | use core::fmt::Write; |
| 20 | |
| 21 | pub struct Hex<'a, T: 'a>(&'a [T]); |
| 22 | |
| 23 | pub struct PlainHex<'a, T: 'a> { |
| 24 | slice: &'a [T], |
| 25 | with_spaces: bool, |
| 26 | } |
| 27 | |
| 28 | pub 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 | |
| 35 | fn 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 | |
| 45 | impl<'a, T> Hex<'a, T> { |
| 46 | pub fn hex(slice: &'a [T]) -> Hex<'a, T> { |
| 47 | Hex(slice) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl<'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 | |
| 59 | impl<'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 | |
| 67 | impl<'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 | |
| 73 | impl<'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 | |
| 79 | impl<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 | } |