56
|
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 |
|
57
|
11 |
char *duffcopy (char *to, char *from, int len)
|
56
|
12 |
{
|
|
13 |
int n, pos = 0;
|
|
14 |
|
57
|
15 |
n = (len + 7) / 8;
|
56
|
16 |
|
57
|
17 |
switch (len % 8) {
|
56
|
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 |
{
|
57
|
51 |
char *to, *from;
|
|
52 |
int len;
|
56
|
53 |
|
|
54 |
if (argc != 2) {
|
|
55 |
printf ("Usage: %s <string>\n", argv[0]);
|
|
56 |
return EXIT_FAILURE;
|
|
57 |
}
|
|
58 |
|
|
59 |
from = argv[1];
|
57
|
60 |
len = strlen (from) + 1;
|
56
|
61 |
|
57
|
62 |
if ((to = malloc (len)) == NULL) {
|
|
63 |
perror ("MALLOC");
|
|
64 |
return EXIT_FAILURE;
|
|
65 |
}
|
|
66 |
|
|
67 |
printf ("DUFF: %s\n", duffcopy (to, from, len));
|
|
68 |
|
|
69 |
if (to != NULL) {
|
|
70 |
free (to);
|
|
71 |
}
|
|
72 |
|
56
|
73 |
return EXIT_SUCCESS;
|
|
74 |
}
|