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

Getting a reference to sub-struct #57

Open dali99 opened 3 years ago

dali99 commented 3 years ago

I'm not sure how feasible it is, but I would like to implement some functions that take &mut self on my sub-structs

Right now I can only set fields in the main struct via set_foo(), if I want to set a subfield I therefore have to do something like self.set_foo(self.foo().with_bar(true))

instead I would like some way of getting a reference to an object i.e self.foo_ref_mut().set_bar(true)

this would also allow custom functions to be implemented on the substructs that take references rather than making copies.

Robbepop commented 3 years ago

That's a nice idea!

However, from the current tech stack it is unlikely that conventional references will work here. However, it might be possible to create reference-like types that represent the bitfield struct in a borrowed instead of an owned way and return an instance of this type. This should actually be feasible by extending the codegen of the crate.

dali99 commented 3 years ago

This actually would have a lot of added usesbility

One example being accessing a field like some sort of slice-like structure.

struct Foo(B1, B1...)
impl Foo {
    fn index_ref_mut(&self, i: u8) -> RefThing {
        match i {
            0 => self.0_ref_mut(),
            1 => self.1_ref_mut(),
            ...
        }
    }
}

Which would allow changing the fields inside loops and iterators and such. Something i found myself really missing.