Rust: Using two u8 struct fields as a u16

Viewed 474

For a Gameboy emulator, you have two u8 fields for registers A and F, but they can sometimes be accessed as AF, a combined u16 register.

In C, it looks like you can do something like this:

struct {
    union {
        struct {
            unsigned char f;
            unsigned char a;
        };
        unsigned short af;
    };
};

(Taken from here)

Is there a way in Rust, ideally without unsafe, of being able to access two u8s as registers.a/registers.f, but also be able to use them as the u16 registers.af?

1 Answers

I can give you a couple of ways to do it. First is a straightforward unsafe analogue but without boilerplate, the second one is safe but explicit.

  1. Unions in rust are very similar, so you can translate it to this:
#[repr(C)]
struct Inner {
    f: u8,
    a: u8,
}

#[repr(C)]
union S {
    inner: Inner,
    af: u16,
}

// Usage:

// Putting data is safe:
let s = S { af: 12345 };
// but retrieving is not:
let a = unsafe { s.inner.a };
  1. Or as an alternative you may manually do all of the explicit casts wrapped in a structure:
#[repr(transparent)]
// This is optional actually but allows a chaining,
// you may remove these derives and change method
// signatures to `&self` and `&mut self`.
#[derive(Clone, Copy)]
struct T(u16);

impl T {
    pub fn from_af(af: u16) -> Self {
        Self(af)
    }
    
    pub fn from_a_f(a: u8, f: u8) -> Self {
        Self::from_af(u16::from_le_bytes([a, f]))
    }

    pub fn af(self) -> u16 {
        self.0
    }

    pub fn f(self) -> u8 {
        self.0.to_le_bytes()[0]
    }

    pub fn set_f(self, f: u8) -> Self {
        Self::from_a_f(self.a(), f)
    }

    pub fn a(self) -> u8 {
        self.0.to_le_bytes()[1]
    }

    pub fn set_a(self, a: u8) -> Self {
        Self::from_a_f(a, self.f())
    }
}

// Usage:

let t = T::from_af(12345);
let a = t.a();

let new_af = t.set_a(12).set_f(t.f() + 1).af();
Related