duff.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 16 Apr 2009 12:49:13 +0200
changeset 56 966ad681f25d
child 57 7739518acafb
permissions -rw-r--r--
Short Description * duff.c Duffs Device, a fast copy algorithm * crypt.c the Salt was to short. * files.c massive directory creation * fork.c a small fork demo committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * Duff's Device
 * fast copy algorithm
 * performs 8 times faster on long strings.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *duffcopy (char *to, char *from, int num)
{
    int n, pos = 0;

    n = (num + 7) / 8;

    switch (num % 8) {
    case 0:
        do {
            to[pos] = from[pos];
            pos++;
    case 7:
            to[pos] = from[pos];
            pos++;
    case 6:
            to[pos] = from[pos];
            pos++;
    case 5:
            to[pos] = from[pos];
            pos++;
    case 4:
            to[pos] = from[pos];
            pos++;
    case 3:
            to[pos] = from[pos];
            pos++;
    case 2:
            to[pos] = from[pos];
            pos++;
    case 1:
            to[pos] = from[pos];
            pos++;
        } while (--n > 0);
    }

    return to;
}

int main (int argc, char **argv)
{
    char to[80], *from;

    if (argc != 2) {
        printf ("Usage: %s <string>\n", argv[0]);
        return EXIT_FAILURE;
    }

    from = argv[1];

    printf ("DUFF: %s\n", duffcopy (to, from, strlen (from)));
    return EXIT_SUCCESS;
}