Search code examples
rustrust-no-std

How to make Debug emit hex values in no_std code?


I'm making a bare metal application in Rust. I can easily make any given struct print its debug information, but I'd like some of them to print some of their values in hex.

For example:

impl core::fmt::Debug for Task {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Task")
            // ...
            .field("SP", &self.context.sp)
            .field("KSP", &self.context.ksp)
            // ...
            .finish()
    }
}

I cannot figure out how to make sp and ksp (both i64) print as hexadecimal numbers. My first thought was to somehow use the format! macro, but since I'm using #![no_std], I don't have access to it.

How can I make the debug output to print these values in hex?


Solution

  • You can use the format_args!() macro. It is the source of all formatting machinery, but does not allocate and thus available in core:

    impl core::fmt::Debug for Task {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt.debug_struct("Task")
                // ...
                .field("SP", &format_args!("{:X}", self.context.sp))
                .field("KSP", &format_args!("{:X}", self.context.ksp))
                // ...
                .finish()
        }
    }