Of interest only to my computer science friends who know and love C very well. I thought after over 30 years of using the language I had already seen every perversion and depravity possible in C, and yet, here’s a new one to me: you can abuse Duff’s Device plus macros to get co-routines. (The side effect may be to summon the old ones though.)
Apparently this was originally discovered by Tom Duff and he thought it was too disgusting to describe in his original Usenet posting on Duff’s Device. Simon Tatham’s “PuTTY” actually uses it throughout!
Holy crap.
LikeLike
Related: Golang uses Duff’s Device to clear and copy memory: http://luciotato.svbtle.com/golangs-duffs-devices
LikeLike
Tom Limoncelli: One wonders if the use of Duff’s Device with quite so long a routine length is worth it — these days cache misses are vastly more expensive than looping, especially given a good branch predictor. One would have to measure and it might change from processor to processor…
LikeLike
I don’t think Pike does anything without measuring it.
LikeLike
I don’t know if Pike wrote that code, though. There are a bunch of people involved. Still, an interesting trick doing that in machine language, I’ll have to think about that in the future.
LikeLike
The comments in the code indicate that there were some timing tests done related to which instructions were picked. Not the same thing, but a good indicator.
LikeLike
Hah, pretty awesome.
LikeLike