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

Variable bitfield sizes in structs #64

Open mthom opened 3 years ago

mthom commented 3 years ago

I'm writing a dynamic language interpreter that uses pointer tagging to identify records in memory. It uses staged tagging, so that the number of tag bits can vary depending on the type of record. These records are primarily defined as values of:

#[bitfield]
#[repr(u64)]
#[derive(Copy, Clone, Debug)]
pub struct HeapCellValue {
    value: B56,
    f: bool,
    m: bool,
    tag: HeapCellValueTag,
}

where tag is a bitfield specifier enum:

#[derive(BitfieldSpecifier, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[bits = 6]
pub enum HeapCellValueTag {
    Cons = 0b00,
    F64 = 0b01,
    Atom = 0b1010,
    ...
}

I highlight Cons, F64 and Atom because their tag sizes are 2 bits, 2 bits, and 4 bits respectively. All other tags use the full 6 bits of HeapCellValueTag. For the smaller tags, the remaining tag bits of HeapCellValue are used for other data. In particular, Atom-tagged cells are actually formatted like this:

#[bitfield]
#[repr(u64)]
#[derive(Copy, Clone, Debug)]
pub struct AtomCell {
    name: B45,
    prec: B11,
    spec: B3,
    m: bool,
    tag: B4,
}

My problem is that I can't extract the smaller tags from HeapCellValue values using the generated bitfield functions without adjacent bits of AtomCell being included in the resulting HeapCellValue's tag field upon conversion. Is it possible to access the bits of the bitfield without making assumptions about the endianness of the machine?

hecatia-elegua commented 1 year ago

I'm not sure I entirely understand, but would an API like this work for you?

pub enum HeapCellValueTag {
    Cons(Cons) = 0b00,
    F64(F64) = 0b01,
    Atom(Atom) = 0b1010,
    /* ... */
}
struct Atom {
    spec_bit_3: B1, //or with your newer verion: `is_functor: bool,`
    m: bool,
}
stevefan1999-personal commented 9 months ago

Ah, it is just tagged union with bitfields