SOURCE MATERIAL no. 001 — ten pieces of legendary code

Ten routines, expressions, and fragments that changed how software is written, broke systems that mattered, or entered the culture on their own terms. Each appears as an artifact: the text itself, where it came from, what it actually does, and what it left behind.

compiled, edited & published by Steven Delpercio · delpercio.dev · 13 July 2026


Duff's Device

C — 1983

An interleaved switch and loop that horrified and delighted C programmers in equal measure — written to make a Lucasfilm graphics port fast enough to ship.

send(to, from, count)
register short *to, *from;
register count;
{
    register n = (count + 7) / 8;
    switch (count % 8) {
    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);
    }
}

Tom Duff wrote the device in November 1983 at Lucasfilm, unrolling a copy loop that fed bytes to an output register. He announced it to colleagues by mail with a mixture of pride and revulsion, remarking that the discovery gave an argument in the ongoing debate about fall-through in switch statements — though he declined to say which side it argued for.

The trick interlaces two control structures that most programmers keep apart. A switch computes the remainder of the count and jumps into the middle of an unrolled do-while loop; case labels land between statements, and C's fall-through semantics do the rest. Every byte of the loop body is executed the correct number of times, with the remainder handled by entry point rather than by a separate cleanup loop.

The device survives because it is legal, correct, and shocking at once — a standing exhibit of what the C grammar actually permits as opposed to what style guides pretend it does. Compiler writers used it as a stress test, teachers as a koan, and maintainers as a warning. Forty years on, it remains the canonical example of code that is admired and forbidden in the same breath.


0x5f3759df - fast inverse square root

C — 1999

One magic constant, one impossible comment, and a square root computed by treating a float's bits as an integer — the most famous hack in game-engine history.

float Q_rsqrt(float number)
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y = number;
    i = *(long *)&y;                    // bit-level type punning
    i = 0x5f3759df - (i >> 1);
    y = *(float *)&i;
    y = y * (threehalfs - (x2 * y * y));
    return y;
}

The routine shipped in id Software's Quake III Arena in 1999, where lighting calculations needed inverse square roots faster than the hardware could deliver them. When the source became public, readers found the constant 0x5f3759df beside a comment too profane to reprint and no explanation whatsoever of why any of it worked.

The code reads a float's bit pattern as an integer, shifts it right to halve the exponent, and subtracts from a constant that corrects the result toward the reciprocal square root — then polishes the estimate with one step of Newton's method. It exploits the IEEE 754 format itself as an approximate logarithm, doing analysis with bit surgery.

Attribution proved as slippery as the math: the trick predates Quake, tracing through Silicon Graphics and hardware circles, and the constant's true author remains uncertain. Numerical analysts later derived better constants, which is somehow the highest compliment — the folklore artifact became a research subject.


hello, world

B — 1972

Before it greeted the world from every tutorial in every language, the phrase made its documented debut in Bell Labs memoranda on a language called B.

main( )
{
    extrn a, b, c;
    putchar(a); putchar(b); putchar(c); putchar('!*n');
}

a 'hell';
b 'o, w';
c 'orld';

Brian Kernighan wrote the earliest documented hello-world programs in tutorials for B, the language Ken Thompson distilled while Unix was young. The B version had to assemble its greeting from pieces: character constants held at most four characters, so the string arrives in fragments, an accident of machine constraints preserved forever in the example's earliest form.

The program demonstrates the smallest possible unit of success: put characters on the output, prove the toolchain works end to end. That pedagogical insight — begin with observable output, not with theory — is the tutorial's real invention, and it carried into The C Programming Language, whose first example fixed the phrase in global memory.

Hello-world became the unit test of civilization's toolchains: the first program in essentially every language since, the standard measure of a development environment's overhead, and the shared first step of every programmer alive. Few artifacts of any kind are reenacted millions of times a year by people who have never seen the original.


apply / eval

LISP — 1960

McCarthy's universal function: a definition of a language written in the language itself, compact enough to fit on a page and deep enough to found a tradition.

# compressed M-expression-style transcription
apply[fn; x; a] =
  [atom[fn] -> ...;
   eq[car[fn]; LAMBDA] ->
     eval[caddr[fn]; pairlis[cadr[fn]; x; a]];
   eq[car[fn]; LABEL] ->
     apply[caddr[fn]; x;
           cons[list[cadr[fn]; caddr[fn]]; a]]]

eval[e; a] =
  [atom[e] -> assoc[e; a];
   eq[car[e]; QUOTE] -> cadr[e];
   eq[car[e]; COND] -> evcon[cdr[e]; a];
   T -> apply[car[e]; evlis[cdr[e]; a]; a]]

John McCarthy's 1960 paper on symbolic expressions defined Lisp mathematically, and near its center sits eval — a function that takes any Lisp expression as data and computes its value. Steve Russell then did what McCarthy had not intended: he implemented eval by hand for the IBM 704, and the notation became a running interpreter.

Eval works because Lisp programs are made of the same material as Lisp data — lists and atoms — so a dozen lines of conditional dispatch can carry the whole weight of interpretation: look up symbols, evaluate arguments, apply functions, recur. The metacircular definition is simultaneously a specification, an implementation, and a proof that the language can host itself.

From that single page descend interpreters, garbage collection's first home, and the idea that code is data — hence macros, self-hosting compilers, and much of programming-language theory's working vocabulary. Alan Kay called the definition the Maxwell's equations of software, and the comparison has never needed defending.


partition / quicksort

ALGOL — 1961

The partition step of quicksort as Hoare published it: the algorithm that made recursion respectable and average-case analysis famous.

procedure quicksort(A, lo, hi);
  if lo < hi then begin
    integer i, j;
    value pivot;
    pivot := A[(lo + hi) div 2];
    i := lo; j := hi;

    while i <= j do begin
      while A[i] < pivot do i := i + 1;
      while A[j] > pivot do j := j - 1;
      if i <= j then begin
        swap(A[i], A[j]);
        i := i + 1; j := j - 1
      end
    end;
    quicksort(A, lo, j);
    quicksort(A, i, hi)
  end

C. A. R. Hoare devised quicksort in 1959-60 while working on machine translation, needing to sort words before dictionary lookup. He published it through the ACM's algorithm series in 1961 in Algol, the lingua franca of published code, with partition as its beating heart: choose a bound, sweep from both ends, exchange what lies on the wrong side.

Partition rearranges a segment around a chosen element so that everything left of the split is small and everything right is large — after which the algorithm simply sorts the two sides by the same method. The recursion that Algol permitted, and that older languages made awkward, is what lets a dozen lines describe a procedure whose careful implementations still anchor standard libraries.

Quicksort became the canonical example of an algorithm whose worst case is tolerated for the sake of its average, and its analysis helped establish that studying expected behavior was serious mathematics. Sixty years of libraries, textbooks, and interview questions have not exhausted it.


life - Conway's Game of Life

APL — 2009

Conway's Game of Life in one line of APL: an entire universe's physics written as a single expression over arrays.

life ← {
  ⊃ 1 ⍵ ∨.∧ 3 4 = +/ +⌿
      ¯1 0 1 ∘.⊖ ¯1 0 1 ⌽¨ ⊂⍵
}

John Scholes of Dyalog recorded a short video in 2009 deriving Life in one expression, and it became the most-watched piece of APL evangelism ever made. The one-liner was a demonstration piece: Conway's cellular automaton, the century's favorite toy universe, compressed into a language whose unit of thought is the whole array.

The expression rotates the board in all eight directions at once, stacks the rotations, and sums them — computing every cell's neighbor count simultaneously. Comparing the sums against three and four, then combining with the current generation, yields the next generation with no loops, no cells, no coordinates: the rules of Life stated as algebra.

The artifact revived an old argument with new charm — that notation shapes thought, and that an array language lets you say what a program means rather than how it walks. Every modern vectorized idiom, from spreadssheet ranges to GPU kernels and array-programming libraries, is the same instinct wearing newer clothes.


goto fail;

C — 2014

One duplicated line in Apple's TLS stack skipped the check that binds a server's key to its certificate — security undone by indentation that lied.

static OSStatus
SSLVerifySignedServerKeyExchange(SSLContext *ctx, ...)
{
    OSStatus err;
    ...
    if ((err = SSLHashSHA1.update(&hashCtx,
                                   &clientRandom)) != 0)
        goto fail;
    if ((err = SSLHashSHA1.update(&hashCtx,
                                   &serverRandom)) != 0)
        goto fail;
    if ((err = SSLHashSHA1.update(&hashCtx,
                                   &signedParams)) != 0)
        goto fail;
        goto fail;          // unconditional
    if ((err = SSLHashSHA1.final(&hashCtx,
                                  &hashOut)) != 0)
        goto fail;
    ...
fail:
    SSLFreeBuffer(&signedHashes);
    return err;
}

In February 2014 Apple shipped an urgent fix for iOS and OS X, and readers of the published Secure Transport source found the cause within hours: a goto fail statement repeated on the next line, unconditionally jumping past the final verification step of the TLS handshake's signed key exchange.

The first goto belongs to the if above it; the duplicate belongs to nothing, executes always, and leaves the success code from an earlier step in place of the verdict that mattered. A network attacker could present a genuine certificate while substituting key-exchange parameters the certificate never signed — breaking the handshake's authentication precisely where it looked most routine.

The bug became the profession's favorite argument for braces, for compiler warnings on unreachable code, and for the humility that one line can defeat a security architecture. Its cause was never publicly established — merge accident is a theory, not a record — which makes it also a lesson in what post-mortems can and cannot know.


Bitcoin genesis block

C++ — 2009

The function that mints block zero of Bitcoin — with a London newspaper headline sealed inside as both timestamp and thesis.

// current Bitcoin Core reconstruction, abridged
static CBlock CreateGenesisBlock(
    uint32_t nTime, uint32_t nNonce,
    uint32_t nBits, int32_t nVersion,
    const CAmount& genesisReward)
{
    const char* pszTimestamp =
      "The Times 03/Jan/2009 Chancellor on brink of"
      " second bailout for banks";

    const CScript genesisOutputScript = CScript()
      << "04678afdb0fe55482719..."_hex
      << OP_CHECKSIG;

    return CreateGenesisBlock(pszTimestamp,
      genesisOutputScript, nTime, nNonce,
      nBits, nVersion, genesisReward);
}

On 3 January 2009 the pseudonymous Satoshi Nakamoto produced Bitcoin's genesis block, and the client's source carries the routine that reconstructs it. Embedded in the coinbase is a line of text: that morning's Times of London headline about a second bank bailout — proof the block was not premined earlier, and a statement of motive that has never needed a footnote.

The genesis block is the hardcoded root of trust: every node builds it locally from these constants rather than receiving it from the network, and every subsequent block must trace its ancestry here. The headline text lives in the input of the block's only transaction, doing double duty as timestamp beacon and editorial.

Whatever one's judgment of what followed — currency, commodity, casino — the artifact is the rare piece of code that is also a founding document, its politics embedded at byte level. The 50-coin reward of block zero is unspendable by quirk of the original code: the first money of the system is, fittingly, ornamental.


Heartbleed

C — 2014

Heartbleed: a heartbeat that echoed back whatever length the sender claimed, leaking secrets from half a million servers' memory.

int dtls1_process_heartbeat(SSL *s)
{
    unsigned char *p = &s->s3->rrec.data[0], *pl;
    unsigned short hbtype;
    unsigned int payload;
    unsigned int padding = 16;

    hbtype = *p++;
    n2s(p, payload);               // attacker-controlled length
    pl = p;

    if (hbtype == TLS1_HB_REQUEST) {
        unsigned char *buffer, *bp;
        buffer = OPENSSL_malloc(1 + 2 + payload + padding);
        bp = buffer;
        *bp++ = TLS1_HB_RESPONSE;
        s2n(payload, bp);
        memcpy(bp, pl, payload);   // missing record bounds check
        ...
    }
}

The defect entered OpenSSL on the last day of 2011 inside an implementation of the TLS heartbeat extension, and sat in the world's most widely deployed cryptographic library until April 2014, when researchers at Codenomicon and Google independently found it and disclosure day gave a vulnerability a name, a logo, and a website for the first time.

A heartbeat message says: here is a payload, echo it back, and here is its length. The code believed the stated length without checking it against the message actually received, then copied that many bytes from adjacent memory into the reply. Up to 64 kilobytes per request of whatever lay nearby — session keys, passwords, private keys — walked out the front door, leaving no trace in any log.

Heartbleed rewrote the economics of open-source infrastructure: the discovery that OpenSSL's maintenance budget bore no relation to its importance created the Core Infrastructure Initiative and a decade of reckoning about who pays for the commons. The missing bounds check became the era's standard argument for memory-safe languages.


BURN, BABY, BURN

AGC ASSEMBLY — 1969

The Apollo Guidance Computer's master ignition routine, filed under a name borrowed from the radio DJs of 1965 Los Angeles: BURN, BABY, BURN.

# BURN, BABY, BURN -- MASTER IGNITION ROUTINE
# DESIGNED FOR P12, P40, P42, P61, P63.
# PERFORMS FUNCTIONS ASSOCIATED WITH APS OR DPS IGNITION.
# ... MAINTAINED BY ADLER AND EYLES.

BURNBABY      TC         PHASCHNG            # GROUP 4 RESTARTS HERE
              OCT        04024
              CAF        ZERO                # EXTIRPATE JUNK LEFT
              TS         DVTOTAL             # IN DVTOTAL
              TS         DVTOTAL +1
              TC         BANKCALL
              CADR       P40AUTO

IGNITION      CS         FLAGWRD5            # ENSURE ENGONFLG IS SET
              MASK       ENGONBIT
              ADS        FLAGWRD5
              CS         PRIO30              # TURN ON THE ENGINE

Don Eyles and Peter Adler wrote the lunar module's ignition sequencing at MIT's Instrumentation Laboratory, and the source they filed it under says what the program does with perfect economy. The name repurposed a slogan from the Watts riots era — borrowed, by the programmers' own account, with the wit of young men naming rocket software after the radio.

The routine coordinates the moment a descent or ascent burn begins: counting down, commanding engine-on, and handing control to the guidance equations that will steer the burn. It ran in a machine with roughly the memory of a modern calculator watch, woven from core rope, sharing its cycles with everything else the landing required.

When the Eagle's computer overloaded during the 1969 descent, the executive's priority scheduling shed low-priority work and kept exactly these functions alive — the design decision that saved the landing and became the founding legend of real-time systems engineering. The comment-rich source, released decades later, showed the style a moonshot was written in: exact, droll, human.


Full provenance for every piece — chronology, attribution, reproduction status, rights, and correction history — is maintained in the SOURCE MATERIAL archive, one canonical record per artifact.

SOURCE MATERIAL is a recurring series about historically significant code and the systems it ran on. Each piece is fact-checked against primary sources where they survive; reproduction status (verbatim, abridged, reconstructed) is declared per artifact, and corrections are recorded in a versioned archive.

Set in Helvetica and DejaVu Sans Mono on US Letter. Body pages follow a fixed plate: title band, deck, specimen panel, three untitled prose blocks, and a footer of fragments. The palette is cream, ink, and one accent per issue; no. 001 wears burnt orange.

curated, written, compiled, and typeset by Steven Delpercio · delpercio.dev