author | Markus Bröker <mbroeker@largo.dyndns.tv> |
Fri, 05 Mar 2010 22:03:25 +0100 | |
changeset 113 | 397270b5d21a |
parent 63 | 5a82f89d607e |
permissions | -rw-r--r-- |
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 |
||
63
5a82f89d607e
uint vs size_t and two bugfixes in fak and unicode
Markus Bröker <mbroeker@largo.dyndns.tv>
parents:
57
diff
changeset
|
11 |
char *duffcopy (char *to, char *from, size_t len) |
56 | 12 |
{ |
63
5a82f89d607e
uint vs size_t and two bugfixes in fak and unicode
Markus Bröker <mbroeker@largo.dyndns.tv>
parents:
57
diff
changeset
|
13 |
size_t n, pos = 0; |
56 | 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; |
63
5a82f89d607e
uint vs size_t and two bugfixes in fak and unicode
Markus Bröker <mbroeker@largo.dyndns.tv>
parents:
57
diff
changeset
|
52 |
size_t 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 |
} |