hex_view/
lib.rs

1//! *NOTE:* As of Rust 1.26.0, this crate is no longer necessary because an `&[u8]` can be
2//! formatted as hex using the `:x?` and `:X?` formatters.
3//!
4//! Easily format a `&[u8]` as hex.
5//!
6//! ```rust
7//! use hex_view::HexView;
8//!
9//! let ff00_slice: &[u8] = &[255, 0];
10//! assert_eq!(format!("{:x}", HexView::from(&ff00_slice)), "ff00")
11//!
12//! ```
13//!
14//! `HexView::from` also works on anything that implements `AsRef<[u8]>`, such as a `&Vec<u8>`:
15//!
16//! ```rust
17//! use hex_view::HexView;
18//!
19//! let ff00_vec: Vec<u8> = vec![255, 0];
20//! assert_eq!(format!("{:X}", HexView::from(&ff00_vec)), "FF00")
21//! ```
22
23#![no_std]
24#![deny(missing_docs)]
25#![deny(warnings)]
26
27use core::fmt;
28use core::fmt::{Formatter, LowerHex, UpperHex};
29
30/// This struct can be formatted with the `core::fmt::LowerHex` and `core::fmt::UpperHex` formatting
31/// traits.
32pub struct HexView<'a> {
33    bytes: &'a [u8],
34}
35
36impl<'a> LowerHex for HexView<'a> {
37    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
38        for b in self.bytes {
39            write!(f, "{:02x}", b)?;
40        }
41        Ok(())
42    }
43}
44
45impl<'a> UpperHex for HexView<'a> {
46    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
47        for b in self.bytes {
48            write!(f, "{:02X}", b)?;
49        }
50        Ok(())
51    }
52}
53
54impl<'a, T> From<&'a T> for HexView<'a>
55where
56    T: ?Sized,
57    T: AsRef<[u8]>,
58    T: 'a,
59{
60    fn from(bytes: &'a T) -> Self {
61        HexView {
62            bytes: bytes.as_ref(),
63        }
64    }
65}