/
switchstmt.d
85 lines (71 loc) · 1.95 KB
/
switchstmt.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
/*
* switchstmt.d
*
* This module implements the runtime functions that are responsible
* for handling switch statements.
*
*/
module runtime.switchstmt;
private template _switch_string(T) {
int _switch_string(T[][] table, T[] compare) {
if (table.length == 0) {
return -1;
}
// Optimization for empty string, it must be first in sorted table
if (compare.length == 0) {
if (table[0] == compare) {
return 0;
}
return -1;
}
TypeInfo ti = typeid(T[]);
// Binary search the table
size_t min = 0;
size_t max = table.length;
// Current comparing position
size_t cur; // midpoint
// Temp for compare value
int cmp;
while(max > min) {
cur = (max + min) / 2;
if (table[cur].length == compare.length) {
cmp = ti.compare(&table[cur], &compare);
}
else {
cmp = table[cur].length - compare.length;
}
if (cmp == 0) {
return cur;
}
else if (cmp > 0) {
max = cur;
}
else {
min = cur + 1;
}
}
return -1;
}
}
extern(C):
// Description: This runtime function will search the given sorted list of
// UTF8 strings and locate the string given.
// Returns: The index into table where the given string was located and -1
// if it was not found.
int _d_switch_string(char[][] table, char[] compare) {
return _switch_string(table, compare);
}
// Description: This runtime function will search the given sorted list of
// UTF16 strings and locate the string given.
// Returns: The index into table where the given string was located and -1
// if it was not found.
int _d_switch_ustring(wchar[][] table, wchar[] compare) {
return _switch_string(table, compare);
}
// Description: This runtime function will search the given sorted list of
// UTF32 strings and locate the string given.
// Returns: The index into table where the given string was located and -1
// if it was not found.
int _d_switch_dstring(dchar[][] table, dchar[] compare) {
return _switch_string(table, compare);
}