hecatia-elegua / bilge

Use bitsized types as if they were a feature of rust.
Apache License 2.0
171 stars 17 forks source link

Allow others to define their own `-Bits` derives #11

Closed hecatia-elegua closed 1 year ago

hecatia-elegua commented 1 year ago

We currently split attributes into those using field information and those using the generated internal value. All attributes which are not handled here just get applied on the internal value. To allow devs to define their own bit-derives, we just need to define a convention for them. We have two ways to do this:

  1. a Bits postfix in the derive's name

This would clutter the code less and can only lead to breakage if some other unrelated macro uses the same postfix (in which case one could report that macro here so we can handle it differently).

  1. let the user do the splitting
#[derive(Debug, PartialEq, Clone, Copy)]
#[bitsize(2)]
#[derive(TryFromBits)]
enum HaveFun {
    Yes, No, Maybe,
}

This would even allow you to use normal derive names below #[bitsize] and let them change into our names automatically, i.e. #[derive(Debug)] turns into #[derive(DebugBits)], which means users could just remove #[bitsize] when rust starts supporting arbitrary ints in the future. Edit: but that's a bit hacky and maybe doesn't let you auto-import.

hecatia-elegua commented 1 year ago

I think we should go for (1.) to keep readability. If anyone wants to contribute, this is a nice little task, feel free to ask for help though!

gwendalF commented 1 year ago

@hecatia-elegua Hello, I would like to try implementing this. Just to be sure, you would like to have the possibility of the users of this crate to define their own macro? And be able to write something like this:

#[derive(bitsize(6))]
#[derive (CustomBits)]
struct Packet {
field1...,
field2....
}

So CustomBits has still Access to fields of the struct?

hecatia-elegua commented 1 year ago

@gwendalF Hey there, thank you. Yes, exactly. Depending on how much you want to do there, it can be a ~3 lines change. The split_attributes function is kinda ugly though, so if you want to restructure it to have less nesting, go for it.