modular-bitfield
modular-bitfield copied to clipboard
Make it possible to generate getters and setters as const fn
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.
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
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);
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.
Ah, thank you for letting me know. I will have to work around this using lazy_static
then.
you would want it to retern Result<Self, (OutOfBounds, Self)>
, as an error would result in losing ownership of the struct.
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?
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.