| 1 |
// https://github.com/dlang/druntime/pull/1781 |
| 2 |
|
| 3 |
struct S |
| 4 |
{ |
| 5 |
int i; |
| 6 |
static int comparisons; |
| 7 |
int opCmp(const S s) const { comparisons++; return i - s.i; } |
| 8 |
} |
| 9 |
|
| 10 |
void testStructs() |
| 11 |
{ |
| 12 |
auto s1 = S(1); |
| 13 |
auto s2 = S(2); |
| 14 |
auto s3 = S(3); |
| 15 |
auto s4 = S(4); |
| 16 |
|
| 17 |
// Test lexicographical order |
| 18 |
|
| 19 |
assert(s1 < s2 && s2 < s3); |
| 20 |
assert([s1, s2, s3] < [s1, s3]); |
| 21 |
assert([s1, s2] < [s1, s2, s3]); |
| 22 |
|
| 23 |
// Test number of comparisons for nested types |
| 24 |
|
| 25 |
S.comparisons = 0; |
| 26 |
assert(s1 < s2); |
| 27 |
assert(S.comparisons == 1); |
| 28 |
|
| 29 |
S.comparisons = 0; |
| 30 |
assert([s1, s2] < [s3, s4]); |
| 31 |
assert(S.comparisons == 1); |
| 32 |
|
| 33 |
S.comparisons = 0; |
| 34 |
assert([[s1, s2]] < [[s3, s4]]); |
| 35 |
assert(S.comparisons == 1); |
| 36 |
} |
| 37 |
|
| 38 |
class C |
| 39 |
{ |
| 40 |
this(int i) { this.i = i; } |
| 41 |
int i; |
| 42 |
static int comparisons; |
| 43 |
override int opCmp(Object c) const { comparisons++; return i - (cast(C)c).i; } |
| 44 |
} |
| 45 |
|
| 46 |
void testClasses() |
| 47 |
{ |
| 48 |
auto c1 = new C(1); |
| 49 |
auto c2 = new C(2); |
| 50 |
auto c3 = new C(3); |
| 51 |
auto c4 = new C(4); |
| 52 |
|
| 53 |
// Test lexicographical order |
| 54 |
|
| 55 |
assert(c1 < c2 && c2 < c3); |
| 56 |
assert([c1, c2, c3] < [c1, c3]); |
| 57 |
assert([c1, c2] < [c1, c2, c3]); |
| 58 |
|
| 59 |
// Test number of comparisons for nested types |
| 60 |
|
| 61 |
C.comparisons = 0; |
| 62 |
assert(c1 < c2); |
| 63 |
assert(C.comparisons == 1); |
| 64 |
|
| 65 |
C.comparisons = 0; |
| 66 |
assert([c1, c2] < [c3, c4]); |
| 67 |
assert(C.comparisons == 1); |
| 68 |
|
| 69 |
C.comparisons = 0; |
| 70 |
assert([[c1, c2]] < [[c3, c4]]); |
| 71 |
assert(C.comparisons == 1); |
| 72 |
} |
| 73 |
|
| 74 |
void main() |
| 75 |
{ |
| 76 |
testStructs(); |
| 77 |
testClasses(); |
| 78 |
} |