forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
switch.d
119 lines (107 loc) · 1.99 KB
/
switch.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import stdio;
import string;
/******************************************************
* Support for switch statements switching on strings.
* Input:
* table[] sorted array of strings generated by compiler
* ca string to look up in table
* Output:
* result index of match in table[]
* -1 if not in table
*/
extern (C):
int _d_switch_string(char[][] table, char[] ca)
in
{
//printf("in _d_switch_string()\n");
assert(table.length >= 0);
assert(ca.length >= 0);
// Make sure table[] is sorted correctly
int i;
for (i = 1; i < table.length; i++)
{
int len1 = table[i - 1].length;
int len2 = table[i].length;
assert(len1 <= len2);
if (len1 == len2)
{
int c;
c = memcmp(table[i - 1], table[i], len1);
assert(c < 0); // c==0 means a duplicate
}
}
}
out (result)
{
int i;
int c;
//printf("out _d_switch_string()\n");
if (result == -1)
{
// Not found
for (i = 0; i < table.length; i++)
{
c = memcmp(table[i], ca, ca.length);
assert(c != 0);
}
}
else
{
assert(0 <= result && result < table.length);
for (i = 0; 1; i++)
{
assert(i < table.length);
c = memcmp(table[i], ca, ca.length);
if (c == 0)
{
assert(i == result);
break;
}
}
}
}
body
{
//printf("body _d_switch_string()\n");
int low;
int high;
int mid;
int c;
char[] pca;
low = 0;
high = table.length;
/*
// Print table
printf("ca[] = '%s'\n", (char *)ca);
for (mid = 0; mid < high; mid++)
{
pca = table[mid];
printf("table[%d] = %d, '%s'\n", mid, pca.length, (char *)pca);
}
*/
// Do binary search
while (low < high)
{
mid = (low + high) >> 1;
pca = table[mid];
c = ca.length - pca.length;
if (c == 0)
{
c = memcmp(ca, pca, ca.length);
if (c == 0)
{ //printf("found %d\n", mid);
return mid;
}
}
if (c < 0)
{
high = mid;
}
else
{
low = mid + 1;
}
}
//printf("not found\n");
return -1; // not found
}