-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.d
157 lines (102 loc) · 2.48 KB
/
utils.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
module utils;
import std.exception : assumeUnique;
import std.stdio, std.conv;
@safe nothrow:
@trusted R dontThrow (R) (lazy R fn)
{
try
return fn();
catch (Exception ex)
assert (false, ex.toString());
}
@trusted dstring toDString (T) (const T a)
if (is (T == enum) || is (T == string) ||is (T == long) || is (T == size_t))
{
try
return a.to!dstring();
catch (Exception ex)
assert (false, ex.toString());
}
@trusted string toString (const dstring s)
{
try
return s.to!string();
catch (Exception ex)
assert (false, ex.toString());
}
@trusted string toString (const size_t s)
{
try
return s.to!string();
catch (Exception ex)
assert (false, ex.toString());
}
@trusted pure B sureCast (B, A) (A a)
{
debug
{
auto res = cast(B)a;
if (a)
assert(res);
return res;
}
else
{
return cast(B)cast(void*)a;
}
}
debug @trusted void dbg (Args...) (Args args)
{
try
writeln(args);
catch (Exception ex)
assert (ex.msg);
}
pure size_t lastIndexOf (const string items, char item)
{
foreach_reverse (ix, i; items)
if (i == item)
return ix;
assert (false, "item '" ~ item ~ "' not found.");
}
pure string lastItemInList (const string list, char separator)
{
return list[list.lastIndexOf(separator) + 1 .. $];
}
pure size_t count (T, U) (const T[] items, const U item)
{
size_t c;
foreach (i; items)
if (i == item)
++c;
return c;
}
pure size_t countUntil (T, U) (const T[] items, const U item)
{
foreach (ix, i; items)
if (i == item)
return ix;
return items.length;
}
pure inout(T)[] sliceBefore (T, U) (inout(T)[] items, const U item)
{
return items[0 .. items.countUntil(item)];
}
pure inout(T)[] sliceAfter (T, U) (inout(T)[] items, const U item)
{
auto cu = items.countUntil(item);
if (cu < items.length)
return items[cu + 1 .. $];
return null;
}
pure @trusted dstring toLowerAscii (const dstring s)
{
auto res = new dchar[s.length];
foreach (ix, dchar ch; s)
{
if (ch >= 65 && ch <= 90) // check for [A-Z]
ch = ch + 32; // change [A-Z] to [a-z]
res[ix] = ch;
}
return res.assumeUnique();
}