duff.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 28 May 2009 17:41:18 +0200
changeset 97 f883331a1bf2
parent 63 5a82f89d607e
permissions -rw-r--r--
alpha_beta ui: removed a redundant line The original print routine was from an open book by galileo computing and the redundant line was introduced there. 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, size_t len)
{
    size_t n, pos = 0;

    n = (len + 7) / 8;

    switch (len % 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, *from;
    size_t len;

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

    from = argv[1];
    len = strlen (from) + 1;

    if ((to = malloc (len)) == NULL) {
        perror ("MALLOC");
        return EXIT_FAILURE;
    }

    printf ("DUFF: %s\n", duffcopy (to, from, len));

    if (to != NULL) {
        free (to);
    }

    return EXIT_SUCCESS;
}