Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 2d87bb9

Browse files
authored
Merge pull request #2095 from schveiguy/improveswitch
Improve string switch code, removing extra test for -1. merged-on-behalf-of: Sebastian Wilzbach <sebi.wilzbach@gmail.com>
2 parents b2c8058 + bb4b95e commit 2d87bb9

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

src/object.d

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3921,45 +3921,45 @@ template _arrayOp(Args...)
39213921
strings are sorted by length first, and then lexicographically.
39223922
* condition = string to look up in table
39233923
* Returns:
3924-
* index of match in caseLabels, -1 if not found
3924+
* index of match in caseLabels, a negative integer if not found
39253925
*/
39263926
int __switch(T, caseLabels...)(/*in*/ const scope T[] condition) pure nothrow @safe @nogc
39273927
{
39283928
// This closes recursion for other cases.
39293929
static if (caseLabels.length == 0)
39303930
{
3931-
return -1;
3931+
return int.min;
39323932
}
39333933
else static if (caseLabels.length == 1)
39343934
{
3935-
return __cmp(condition, caseLabels[0]) == 0 ? 0 : -1;
3935+
return __cmp(condition, caseLabels[0]) == 0 ? 0 : int.min;
39363936
}
39373937
// To be adjusted after measurements
39383938
// Compile-time inlined binary search.
39393939
else static if (caseLabels.length < 7)
39403940
{
39413941
int r = void;
3942-
if (condition.length == caseLabels[$ / 2].length)
3942+
enum mid = cast(int)caseLabels.length / 2;
3943+
if (condition.length == caseLabels[mid].length)
39433944
{
3944-
r = __cmp(condition, caseLabels[$ / 2]);
3945-
if (r == 0) return cast(int) caseLabels.length / 2;
3945+
r = __cmp(condition, caseLabels[mid]);
3946+
if (r == 0) return mid;
39463947
}
39473948
else
39483949
{
39493950
// Equivalent to (but faster than) condition.length > caseLabels[$ / 2].length ? 1 : -1
3950-
r = ((condition.length > caseLabels[$ / 2].length) << 1) - 1;
3951+
r = ((condition.length > caseLabels[mid].length) << 1) - 1;
39513952
}
39523953

39533954
if (r < 0)
39543955
{
39553956
// Search the left side
3956-
return __switch!(T, caseLabels[0 .. $ / 2])(condition);
3957+
return __switch!(T, caseLabels[0 .. mid])(condition);
39573958
}
39583959
else
39593960
{
39603961
// Search the right side
3961-
r = __switch!(T, caseLabels[$ / 2 + 1 .. $])(condition);
3962-
return r != -1 ? cast(int) (caseLabels.length / 2 + 1 + r) : -1;
3962+
return __switch!(T, caseLabels[mid + 1 .. $])(condition) + mid + 1;
39633963
}
39643964
}
39653965
else

0 commit comments

Comments
 (0)