const_hex/
display.rs

1use core::fmt;
2
3/// Returns a value that can be formatted using the [`fmt`] traits.
4///
5/// Supports [`fmt::LowerHex`], [`fmt::UpperHex`], and [`fmt::Display`]
6/// (which is the same as [`fmt::LowerHex`]),
7/// as well as using the alternate flag (`:#`) to write the hex prefix.
8///
9/// # Examples
10///
11/// ```
12/// let bytes: &[u8] = &[0xde, 0xad, 0xbe, 0xef];
13/// let displayed = const_hex::display(bytes);
14/// let s = format!("{displayed} {displayed:#X}");
15/// assert_eq!(s, "deadbeef 0xDEADBEEF");
16/// ```
17#[inline]
18pub fn display<T: AsRef<[u8]>>(input: T) -> impl fmt::Display + fmt::LowerHex + fmt::UpperHex {
19    Display(input)
20}
21
22struct Display<T: AsRef<[u8]>>(T);
23
24impl<T: AsRef<[u8]>> fmt::Display for Display<T> {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        fmt::LowerHex::fmt(self, f)
27    }
28}
29
30impl<T: AsRef<[u8]>> fmt::LowerHex for Display<T> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        self.write::<false>(f)
33    }
34}
35
36impl<T: AsRef<[u8]>> fmt::UpperHex for Display<T> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        self.write::<true>(f)
39    }
40}
41
42impl<T: AsRef<[u8]>> Display<T> {
43    fn write<const UPPER: bool>(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        if f.alternate() {
45            f.write_str("0x")?;
46        }
47        unsafe { crate::imp::encode::<UPPER>(self.0.as_ref(), f) };
48        Ok(())
49    }
50}