Tom Duff is a programmer for Pixar. Previously he worked for, among other places, Lucasfilm and Bell Labs. Duff is the creator of the rc shell for the Plan 9 operating system as well as the co-creator of Marionette, the animation system used by Pixar.
Duff’s Device is a clever exploit of a WTF in the C language. The goal in this case is loop unrolling, a manual optimization where an operation in a loop is done several times before checking whether the loop should continue. In order to do the operation the correct number of times, you may need to start midway through the unrolled loop. The code then looks like this example I copied from Wikipedia:
send(to, from, count)
register short *to, *from;
register count;
{
register n = (count + 7) / 8;
switch (count % 😎 {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);
}
}
This works because the switch statement is very loosely specified in C. The case labels (that tell the instruction pointer where to jump to) can appear anywhere inside the switch block, and cases “fall through” to the next statement unless the switch is explicitly terminated with the “break” statement. Meanwhile, because the assembly language equivalent of a do-while loop doesn’t really care if you entered the code block at the start (it merely does a test at the end and jumps to the beginning of the block if the test succeeds), all subsequent iterations of the loop after the first one start at the top. Cool, huh?
Though it has a very limited utility, the greatness of Duff’s Device lies in the eponymous’s Zen-like comment about its relation to case fall-through:
“This code forms some sort of argument in that debate, but I’m not sure whether it’s for or against.”
