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

Make it possible to generate getters and setters as const fn #26

Open Robbepop opened 3 years ago

Robbepop commented 3 years ago

Currently the getters and setters generated by the #[bitfield] proc. macro for its bitfield struct are not const fn. This is because they are making heavy use of functionality that current stable Rust does not yet support within const fn. However, having those getters and setters as const fn is undoubtly to great value and should probably be possible with serious changes to the code generation and the backend.

This is probably a more involved task.

Robbepop commented 3 years ago

Currently this feature is blocked by not being able to have &self or &mut self methods of a struct as const fn. This might be available sooner or later though. We should track the tracking issue for this: https://github.com/rust-lang/rust/issues/57563

T-Bakker commented 3 years ago

Is it possible to make the fn new() -> Self, fn with_a(self, new_value: bool) -> Self, and/or fn with_a_checked(self, new_value: bool) -> Result<Self, OutOfBounds> a const fn as they do not borrow self? This would allow defining static const bitfields ala: const STATUS_A: Status = Status::new().with_value_a(1).with_value_b(3);

Robbepop commented 3 years ago

Technically this is possible. However, the current implementation of with_x(self, new_value: T) -> Self bitfield calls the &mut self taking methods under the hood. While this is not technically needed, it is where we are right now. Changing this would be involved.

T-Bakker commented 3 years ago

Ah, thank you for letting me know. I will have to work around this using lazy_static then.

Ben-PH commented 3 years ago

you would want it to retern Result<Self, (OutOfBounds, Self)>, as an error would result in losing ownership of the struct.

reinerp commented 2 years ago

For what it's worth, const fn getters (with &self argument) are already possible in stable Rust: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6d129f311dcfce598be4446a298818fe.

I'd find const fn getters useful, even if const fn setters were unavailable. Would you consider providing that?

Robbepop commented 2 years ago

I'd accept PRs to add this as long as they are not exploding the complexity of the macros. Note thought that from what I remember, the implementation uses traits extensively and there is no const fn for traits nowadays in Rust.