[sdiy] MIDI bytestream parser

Olivier Gillet ol.gillet at gmail.com
Tue Nov 16 12:36:20 CET 2010


> Ok, *now* I get it, thanks!
> It's a workaround for crap compilers to ensure that they produce something that is a reasonable approximation to efficient code. Because although the point of higher level languages is the easy readability and useful structures like switch, if you actually use them you finish up with hideous bloatware that won't go in your chip, let alone run fast and do the job in hand? Am I close?!

I actually find that the "handlers table" solution is more readable,
elegant and is a higher level "structure" than 120 lines of switch /
case /break (Here's how I wrote it with the switch:
https://github.com/pichenettes/shruthi-1/blob/master/hardware/midi/midi.h#L163).
It's not a hack, it's a common programming idiom seen in protocol
handling.

As a side-effect, it also adds a useful level of indirection, since
the handlers table can be hijacked at runtime to change how some
messages are handled.

> Grrr...not convinced by C. If that's the kind of stuff you have to do to make things work, I'm going back to assembly language...

Nothing prevents you from using a switch, but then you depend on your
compiler writing the best code for you. But even with a crappy
compiler, the generated code is likely to be of higher quality than
what an average assembly programmer does... I'm not sure every
assembly programmer would know how to code a jump table anyway!

Interestingly, I've rewritten my MIDI parser using this lookup table
approach (since I'm trying to put the Shruthi-1 code on a diet to add
new feature) and the code size was in the end very similar to the
switch approach (+50 bytes of data, -52 bytes of code). Maybe avr-gcc
is not that bad at all, and maybe the additional level of indirections
this adds can't be flatten as easily as with a switch (the way things
are currently done is such that the MIDI handlers are in the end
directly inlined at compile-time within the MIDI parser code) ; but
this is specific to the way I'm writing most of my code so this is not
something I would recommend to do in a library that aims to be as
cross-platform and universal as Neil's.

Olivier



More information about the Synth-diy mailing list