forked from dlang/phobos
/
util.d
118 lines (97 loc) · 2.75 KB
/
util.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
module std.container.util;
import std.algorithm;
/**
Returns an initialized object. This function is mainly for eliminating
construction differences between structs and classes. It allows code to not
worry about whether the type it's constructing is a struct or a class.
*/
template make(T)
if (is(T == struct) || is(T == class))
{
T make(Args...)(Args arguments)
if (is(T == struct) && __traits(compiles, T(arguments)))
{
return T(arguments);
}
T make(Args...)(Args arguments)
if (is(T == class) && __traits(compiles, new T(arguments)))
{
return new T(arguments);
}
}
///
unittest
{
import std.container;
auto arr = make!(Array!int)([4, 2, 3, 1]);
assert(equal(arr[], [4, 2, 3, 1]));
auto rbt = make!(RedBlackTree!(int, "a > b"))([4, 2, 3, 1]);
assert(equal(rbt[], [4, 3, 2, 1]));
alias makeList = make!(SList!int);
auto slist = makeList(1, 2, 3);
assert(equal(slist[], [1, 2, 3]));
}
unittest
{
import std.container;
auto arr1 = make!(Array!dchar)();
assert(arr1.empty);
auto arr2 = make!(Array!dchar)("hello"d);
assert(equal(arr2[], "hello"d));
auto rtb1 = make!(RedBlackTree!dchar)();
assert(rtb1.empty);
auto rtb2 = make!(RedBlackTree!dchar)('h', 'e', 'l', 'l', 'o');
assert(equal(rtb2[], "ehlo"d));
}
// Issue 8895
unittest
{
import std.container;
auto a = make!(DList!int)(1,2,3,4);
auto b = make!(DList!int)(1,2,3,4);
auto c = make!(DList!int)(1,2,3,5);
auto d = make!(DList!int)(1,2,3,4,5);
assert(a == b); // this better terminate!
assert(a != c);
assert(a != d);
}
/**
* Convenience function for constructing a generic container.
*/
template make(alias Container, Args...)
if(!is(Container))
{
import std.range : isInputRange;
import std.traits : isDynamicArray;
auto make(Range)(Range range)
if(!isDynamicArray!Range && isInputRange!Range)
{
import std.range : ElementType;
return .make!(Container!(ElementType!Range, Args))(range);
}
auto make(T)(T[] items...)
{
return .make!(Container!(T, Args))(items);
}
}
///
unittest
{
import std.container.array, std.container.rbtree, std.container.slist;
import std.range : iota;
auto arr = make!Array(iota(5));
assert(equal(arr[], [0, 1, 2, 3, 4]));
auto rbtmax = make!(RedBlackTree, "a > b")(iota(5));
assert(equal(rbtmax[], [4, 3, 2, 1, 0]));
auto rbtmin = make!RedBlackTree(4, 1, 3, 2);
assert(equal(rbtmin[], [1, 2, 3, 4]));
alias makeList = make!SList;
auto list = makeList(1, 7, 42);
assert(equal(list[], [1, 7, 42]));
}
unittest
{
import std.container.rbtree;
auto rbtmin = make!(RedBlackTree, "a < b", false)(3, 2, 2, 1);
assert(equal(rbtmin[], [1, 2, 3]));
}