duff.c
changeset 56 966ad681f25d
child 57 7739518acafb
equal deleted inserted replaced
55:2a20d0184041 56:966ad681f25d
       
     1 /**
       
     2  * Duff's Device
       
     3  * fast copy algorithm
       
     4  * performs 8 times faster on long strings.
       
     5  */
       
     6 
       
     7 #include <stdio.h>
       
     8 #include <stdlib.h>
       
     9 #include <string.h>
       
    10 
       
    11 char *duffcopy (char *to, char *from, int num)
       
    12 {
       
    13     int n, pos = 0;
       
    14 
       
    15     n = (num + 7) / 8;
       
    16 
       
    17     switch (num % 8) {
       
    18     case 0:
       
    19         do {
       
    20             to[pos] = from[pos];
       
    21             pos++;
       
    22     case 7:
       
    23             to[pos] = from[pos];
       
    24             pos++;
       
    25     case 6:
       
    26             to[pos] = from[pos];
       
    27             pos++;
       
    28     case 5:
       
    29             to[pos] = from[pos];
       
    30             pos++;
       
    31     case 4:
       
    32             to[pos] = from[pos];
       
    33             pos++;
       
    34     case 3:
       
    35             to[pos] = from[pos];
       
    36             pos++;
       
    37     case 2:
       
    38             to[pos] = from[pos];
       
    39             pos++;
       
    40     case 1:
       
    41             to[pos] = from[pos];
       
    42             pos++;
       
    43         } while (--n > 0);
       
    44     }
       
    45 
       
    46     return to;
       
    47 }
       
    48 
       
    49 int main (int argc, char **argv)
       
    50 {
       
    51     char to[80], *from;
       
    52 
       
    53     if (argc != 2) {
       
    54         printf ("Usage: %s <string>\n", argv[0]);
       
    55         return EXIT_FAILURE;
       
    56     }
       
    57 
       
    58     from = argv[1];
       
    59 
       
    60     printf ("DUFF: %s\n", duffcopy (to, from, strlen (from)));
       
    61     return EXIT_SUCCESS;
       
    62 }