1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
 * Copyright 2022, Isaac Woods
 * SPDX-License-Identifier: MPL-2.0
 */

use core::{fmt, mem};
use num_traits::PrimInt;

/// Values can be wrapped in this type when they're printed to display them as easy-to-read binary
/// numbers. `Display` is implemented to print the value in the form `00000000-00000000`, while
/// `Debug` will print it in the form `00000000(8)-00000000(0)` (with offsets of each byte).
pub struct BinaryPrettyPrint<T: fmt::Binary + PrimInt>(pub T);

impl<T: fmt::Binary + PrimInt> fmt::Display for BinaryPrettyPrint<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let byte_mask: T = T::from(0xff).unwrap();
        let max_byte = mem::size_of::<T>() - 1;

        for i in 0..max_byte {
            let byte = max_byte - i;
            write!(f, "{:>08b}-", (self.0 >> (byte * 8)) & byte_mask).unwrap();
        }
        write!(f, "{:>08b}", self.0 & byte_mask).unwrap();

        Ok(())
    }
}

impl<T: fmt::Binary + PrimInt> fmt::Debug for BinaryPrettyPrint<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let byte_mask: T = T::from(0xff).unwrap();
        let max_byte = mem::size_of::<T>() - 1;

        for i in 0..max_byte {
            let byte = max_byte - i;
            write!(f, "{:>08b}({})-", (self.0 >> (byte * 8)) & byte_mask, byte * 8).unwrap();
        }
        write!(f, "{:>08b}(0)", self.0 & byte_mask).unwrap();

        Ok(())
    }
}

#[test]
fn test() {
    assert_eq!(format!("{}", BinaryPrettyPrint(0 as u8)), "00000000");
    assert_eq!(format!("{}", BinaryPrettyPrint(0 as u16)), "00000000-00000000");
    assert_eq!(format!("{}", BinaryPrettyPrint(0 as u32)), "00000000-00000000-00000000-00000000");
}