display_bytes/
hex.rs

1// Copyright 2017 Austin Bonander
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7use super::ByteFormat;
8
9use std::fmt;
10
11/// Default hexadecimal byte format used by this crate.
12pub const DEFAULT_HEX: FormatHex<'static> = FormatHex {
13    prefix: "",
14    separator: " ",
15    uppercase: true,
16};
17
18/// Formats bytes in hexadecimal pairs (`00 - FF`).
19#[derive(Copy, Clone, Debug)]
20pub struct FormatHex<'s> {
21    /// The prefix, if any, for each byte.
22    pub prefix: &'s str,
23    /// The separator for individual hex-formatted bytes.
24    pub separator: &'s str,
25    /// Whether or not to write the hex-pairs in uppercase
26    pub uppercase: bool,
27}
28
29impl<'s> ByteFormat for FormatHex<'s> {
30    fn fmt_bytes(&self, bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
31        let mut written = false;
32
33        for b in bytes {
34            if written {
35                f.write_str(self.separator)?;
36            }
37
38            if self.uppercase {
39                write!(f, "{}{:02X}", self.prefix, b)?;
40            } else {
41                write!(f, "{}{:02x}", self.prefix, b)?;
42            }
43
44            written = true;
45        }
46
47        Ok(())
48    }
49}
50
51#[test]
52fn test_hex() {
53    assert_eq!(DEFAULT_HEX.bytes_to_string(b"\xAB\xCD\xEF\x00\x10"), "AB CD EF 00 10");
54}