modular-bitfield icon indicating copy to clipboard operation
modular-bitfield copied to clipboard

Support rust union structs

Open MarcelCoding opened this issue 2 years ago • 1 comments

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 avatar Mar 26 '22 12:03 MarcelCoding

I've updated the description.

MarcelCoding avatar Mar 26 '22 15:03 MarcelCoding