technocreatives / dbc-codegen

Generate Rust structs for messages from a dbc (CAN bus definition) file.
Apache License 2.0
48 stars 31 forks source link

Making illegal states unrepresentable #93

Open projectgus opened 5 days ago

projectgus commented 5 days ago

This is another idea for a change, relating to #92 a bit. I've been thinking about the phrase "make illegal[/invalid] states unrepresentable" when working with structs generated from DBC files.

My main concern is that the try_from() message constructor only validates length, it doesn't validate signal values. So it's possible to parse a message with a payload where message.set_signalname(message.signalname()) would fail...

Of course, there are plenty of cases where a programmer might want this, for example a module which sends some signals initialised to FFs during startup. The programmer might even want to parse this partially invalid message, despite some signals being invalid.

I am not sure about this, but I have been wondering if it'd be convenient to have a generated signal API that knows about the possibility of invalid fields. Something like:

Of course this would be another breaking change, similar to #92, and I'm not sure about how ergonomic it would be to use.

The "purest" approach to "make illegal states unrepresentable" might be to encode signal restrictions in the types themselves, by having the signal functions get and set types such as bounded integers...