Skip to main content
← PSoXide SDK guides and examples · SDK f2fec1c301f1 · All Cargo features enabled; check feature gates before use.

psx_font/
hex.rs

1//! Heap-free hex label formatting for debug HUDs.
2//!
3//! `no_std` guest code cannot reach for `format!`, so HUD overlays
4//! that want to print a counter next to a label need a tiny
5//! stack-buffer formatter. [`format_u16`] renders a `u16` as `0xABCD`
6//! into a [`HexU16`] whose [`as_str`](HexU16::as_str) feeds straight
7//! into [`FontAtlas::draw_text`](crate::FontAtlas::draw_text).
8
9/// A `u16` formatted as `0xABCD`, ready to draw.
10#[derive(Copy, Clone)]
11pub struct HexU16([u8; 6]);
12
13impl HexU16 {
14    /// The formatted text, e.g. `"0x1F40"`.
15    pub fn as_str(&self) -> &str {
16        // SAFETY: all bytes are ASCII ('0', 'x', hex digits).
17        unsafe { core::str::from_utf8_unchecked(&self.0) }
18    }
19}
20
21/// Format a `u16` as a fixed-width `0xABCD` hex label.
22pub fn format_u16(v: u16) -> HexU16 {
23    const HEX: &[u8; 16] = b"0123456789ABCDEF";
24    let mut out = [0u8; 6];
25    out[0] = b'0';
26    out[1] = b'x';
27    out[2] = HEX[((v >> 12) & 0xF) as usize];
28    out[3] = HEX[((v >> 8) & 0xF) as usize];
29    out[4] = HEX[((v >> 4) & 0xF) as usize];
30    out[5] = HEX[(v & 0xF) as usize];
31    HexU16(out)
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn formats_fixed_width_uppercase() {
40        assert_eq!(format_u16(0).as_str(), "0x0000");
41        assert_eq!(format_u16(0x1F40).as_str(), "0x1F40");
42        assert_eq!(format_u16(u16::MAX).as_str(), "0xFFFF");
43    }
44}