In games/networking/systems programming there’s often times where being space-efficient is (slightly) more desirable than being time-efficient. When this happens it is sometimes the case where storing information in memory at the bit, rather than byte, level is desirable.
Doing so is prone to human error. Counting bits, generating masks, and generally packing data is a minefield of potential off-by-one mathematical errors.
I have written such things several times in the past and it struck me that this is a case where the ability to simply define new syntax would make scheme a strong language for this problem.
Featured below is a gist detailing the test-case for the output of my experiment. It looks big, but keep in mind that the actual work being done by the module can be found in naught but two s-expr in the test: the test-bits define and the later execution of it!
The trick is this: the user utilizes the (make-bits) macro to describe the layout of their data. The bit, nibble, byte, and bytes descriptions are available; although I intend to support all of the core data types and srfi-4 vectors in the future. The macro then generates a lambda-function which, given (thing, read?, blob, and start-index) will either write or read between thing and the blob beginning at the bit-index start-index.
You can see this in the invocation of (test-bits).