Robbepop / modular-bitfield

Macro to generate bitfields for structs that allow for modular use of enums.
Apache License 2.0
155 stars 40 forks source link

Support rust union structs #81

Open MarcelCoding opened 2 years ago

MarcelCoding commented 2 years ago

https://doc.rust-lang.org/reference/items/unions.html

The key property of unions is that all fields of a union share common storage. As a result, writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field.

#[bitfield]
#[derive(Clone, Debug)]
pub(crate) struct TextureSize1D {
  pub(crate) width: u32,
}

#[bitfield]
#[derive(Clone, Debug)]
pub(crate) struct TextureSize2D {
  pub(crate) width: u16,
  pub(crate) height: u16
}

#[bitfield]
#[derive(Clone, Debug)]
pub(crate) struct TextureSize3D {
  pub(crate) width: B11,
  pub(crate) height: B11,
  pub(crate) depth: B10,
}

#[derive(BitfieldSpecifier, Debug)]
pub(crate) union TextureSize {
  one_d: TextureSize1D,
  twp_d: TextureSize2D,
  three_d: TextureSize3D
}

#[bitfield]
#[derive(Debug)]
pub(crate) struct SomeBitField {
  pub(crate) texture_size: TextureSize,
}

An alternative solution (more like a workaround) is to use a u32 in the bitfield and decide when you need it what kind of texture dimension you need and decode the u32 to one of the first tree bitfields.

MarcelCoding commented 2 years ago

I've updated the description.