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

Make it possible to generate getters and setters as const fn

Open Robbepop opened this issue 4 years ago • 7 comments

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 avatar Oct 18 '20 18:10 Robbepop

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

Robbepop avatar Oct 25 '20 18:10 Robbepop

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);

T-Bakker avatar Dec 30 '20 21:12 T-Bakker

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.

Robbepop avatar Dec 30 '20 23:12 Robbepop

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

T-Bakker avatar Dec 31 '20 10:12 T-Bakker

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

Ben-PH avatar May 14 '21 10:05 Ben-PH

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?

reinerp avatar Feb 05 '22 17:02 reinerp

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.

Robbepop avatar Feb 05 '22 18:02 Robbepop