/
conv.d
563 lines (474 loc) · 13.9 KB
/
conv.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/++
This module contains functions that in one way or another converts its
arguments into something else.
Credit for [Enum] goes to Stephan Koch (https://github.com/UplinkCoder).
Example:
---
enum SomeEnum { one, two, three };
SomeEnum foo = Enum!SomeEnum.fromString("one");
SomeEnum bar = Enum!SomeEnum.fromString("three");
assert(foo == SomeEnum.one);
assert(bar == SomeEnum.three);
---
+/
module lu.conv;
private:
import std.range.primitives : isOutputRange;
import std.traits : isIntegral;
import std.typecons : Flag, No, Yes;
public:
@safe:
// Enum
/++
Template housing optimised functions to get the string name of an enum
member, or the enum member of a name string.
[std.conv.to] is typically the go-to for this job; however it quickly bloats
the binary and is not performant on larger enums.
Params:
E = enum to base this template on.
+/
template Enum(E)
if (is(E == enum))
{
// fromString
/++
Takes the member of an enum by string and returns that enum member.
It lowers to a big switch of the enum member strings. It is faster than
[std.conv.to] and generates less template bloat. However, it does not work
with enums where multiple members share the same values, as the big switch
ends up getting duplicate cases.
Taken from: https://forum.dlang.org/post/bfnwstkafhfgihavtzsz@forum.dlang.org
written by Stephan Koch (https://github.com/UplinkCoder).
Used with permission.
Example:
---
enum SomeEnum { one, two, three };
SomeEnum foo = Enum!SomeEnum.fromString("one");
SomeEnum bar = Enum!SomeEnum.fromString("three");
assert(foo == SomeEnum.one);
assert(bar == SomeEnum.three);
---
Params:
enumstring = the string name of an enum member.
Returns:
The enum member whose name matches the enumstring string (not whose
*value* matches the string).
Throws: [std.conv.ConvException|ConvException] if no matching enum member with the
passed name could be found.
Bugs:
Does not work with enums that have members with duplicate values.
+/
E fromString(const string enumstring) pure
{
enum enumSwitch = ()
{
string enumSwitch = "import std.conv : ConvException;\n" ~
"with (E) switch (enumstring)\n{\n";
foreach (immutable memberstring; __traits(allMembers, E))
{
enumSwitch ~= `case "` ~ memberstring ~ `": return ` ~ memberstring ~ ";\n";
}
enumSwitch ~= "default:\n" ~
" //import std.traits : fullyQualifiedName;\n" ~
` throw new ConvException("No such " ~ E.stringof ~ ": " ~ enumstring);` ~ "\n}";
return enumSwitch;
}();
mixin(enumSwitch);
}
// toString
/++
The inverse of [fromString], this function takes an enum member value
and returns its string identifier.
It lowers to a big switch of the enum members. It is faster than
[std.conv.to] and generates less template bloat.
Taken from: https://forum.dlang.org/post/bfnwstkafhfgihavtzsz@forum.dlang.org
written by Stephan Koch (https://github.com/UplinkCoder).
Used with permission.
Example:
---
enum SomeEnum { one, two, three };
string foo = Enum!SomeEnum.toString(one);
assert(foo == "one");
---
Params:
value = Enum member whose string name we want.
Returns:
The string name of the passed enum member.
+/
string toString(E value) pure nothrow
{
switch (value)
{
foreach (immutable m; __traits(allMembers, E))
{
case mixin("E." ~ m) : return m;
}
default:
string result = "cast(" ~ E.stringof ~ ")";
uint val = value;
enum headLength = E.stringof.length + "cast()".length;
immutable log10Val =
(val < 10) ? 0 :
(val < 100) ? 1 :
(val < 1_000) ? 2 :
(val < 10_000) ? 3 :
(val < 100_000) ? 4 :
(val < 1_000_000) ? 5 :
(val < 10_000_000) ? 6 :
(val < 100_000_000) ? 7 :
(val < 1_000_000_000) ? 8 : 9;
result.length += log10Val + 1;
for (uint i; i != log10Val + 1; ++i)
{
cast(char)result[headLength + log10Val - i] = cast(char)('0' + (val % 10));
val /= 10;
}
return result;
}
}
}
///
@system
unittest
{
import std.conv : ConvException;
import std.exception : assertThrown;
enum T
{
UNSET,
QUERY,
PRIVMSG,
RPL_ENDOFMOTD
}
with (T)
{
static assert(Enum!T.fromString("QUERY") == QUERY);
static assert(Enum!T.fromString("PRIVMSG") == PRIVMSG);
static assert(Enum!T.fromString("RPL_ENDOFMOTD") == RPL_ENDOFMOTD);
static assert(Enum!T.fromString("UNSET") == UNSET);
assertThrown!ConvException(Enum!T.fromString("DOESNTEXIST")); // needs @system
}
with (T)
{
static assert(Enum!T.toString(QUERY) == "QUERY");
static assert(Enum!T.toString(PRIVMSG) == "PRIVMSG");
static assert(Enum!T.toString(RPL_ENDOFMOTD) == "RPL_ENDOFMOTD");
}
}
// numFromHex
/++
Returns the decimal value of a hex number in string form.
Example:
---
int fifteen = numFromHex("F");
int twofiftyfive = numFromHex("FF");
---
Params:
hex = Hexadecimal number in string form.
acceptLowercase = Flag of whether or not to accept `rrggbb` in lowercase form.
Returns:
An integer equalling the value of the passed hexadecimal string.
Throws: [std.conv.ConvException|ConvException] if the hex string was malformed.
+/
auto numFromHex(
const string hex,
const Flag!"acceptLowercase" acceptLowercase = Yes.acceptLowercase) pure
out (total; (total < 16^^hex.length), "`numFromHex` output is too large")
{
import std.string : representation;
int val = -1;
int total;
foreach (immutable c; hex.representation)
{
switch (c)
{
case '0':
..
case '9':
val = (c - 48);
goto case 'F';
case 'a':
..
case 'f':
if (acceptLowercase)
{
val = (c - (55+32));
goto case 'F';
}
else
{
goto default;
}
case 'A':
..
case 'F':
if (val < 0) val = (c - 55);
total *= 16;
total += val;
val = -1;
break;
default:
import std.conv : ConvException;
throw new ConvException("Invalid hex string: " ~ hex);
}
}
return total;
}
// rgbFromHex
/++
Convenience wrapper that takes a hex string and populates a Voldemort
struct with its RR, GG and BB components.
This is to be used when mapping a `#RRGGBB` colour to their decimal
red/green/blue equivalents.
Params:
hexString = Hexadecimal number (colour) in string form.
acceptLowercase = Whether or not to accept the `rrggbb` string in
lowercase letters.
Returns:
A Voldemort struct with `r`, `g` and `b` members,
+/
auto rgbFromHex(
const string hexString,
const Flag!"acceptLowercase" acceptLowercase = No.acceptLowercase)
{
struct RGB
{
int r;
int g;
int b;
}
RGB rgb;
immutable hex = (hexString[0] == '#') ? hexString[1..$] : hexString;
rgb.r = numFromHex(hex[0..2], acceptLowercase);
rgb.g = numFromHex(hex[2..4], acceptLowercase);
rgb.b = numFromHex(hex[4..$], acceptLowercase);
return rgb;
}
///
unittest
{
import std.conv : text;
{
auto rgb = rgbFromHex("000102");
assert((rgb.r == 0), rgb.r.text);
assert((rgb.g == 1), rgb.g.text);
assert((rgb.b == 2), rgb.b.text);
}
{
auto rgb = rgbFromHex("#FFFFFF");
assert((rgb.r == 255), rgb.r.text);
assert((rgb.g == 255), rgb.g.text);
assert((rgb.b == 255), rgb.b.text);
}
{
auto rgb = rgbFromHex("#3C507D");
assert((rgb.r == 60), rgb.r.text);
assert((rgb.g == 80), rgb.b.text);
assert((rgb.b == 125), rgb.b.text);
}
{
auto rgb = rgbFromHex("9a4B7c", Yes.acceptLowercase);
assert((rgb.r == 154), rgb.r.text);
assert((rgb.g == 75), rgb.g.text);
assert((rgb.b == 124), rgb.b.text);
}
}
// toAlphaInto
/++
Translates an integer into an alphanumeric string. Assumes ASCII.
Overload that takes an output range sink.
Example:
---
Appender!(char[]) sink;
int num = 12345;
num.toAlphaInto(sink);
assert(sink.data == "12345");
assert(sink.data == num.to!string);
---
Params:
maxDigits = The maximum number of digits to expect input of.
leadingZeroes = The minimum amount of leading zeroes to include in the
output, mirroring the format specifier "`%0nd`".
num = Integer to translate into string.
sink = Output range sink.
+/
void toAlphaInto(size_t maxDigits = 19, uint leadingZeroes = 0, Num, Sink)
(const Num num, auto ref Sink sink)
if (isIntegral!Num && isOutputRange!(Sink, char[]))
{
static assert((maxDigits >= leadingZeroes), "Cannot pass more leading zeroes " ~
"than max digits to `toAlphaInto`");
if (num == 0)
{
static if (leadingZeroes > 0)
{
foreach (immutable i; 0..leadingZeroes)
{
sink.put('0');
}
}
else
{
sink.put('0');
}
return;
}
else if (num < 0)
{
sink.put('-');
}
static if (leadingZeroes > 0)
{
// Need default-initialised fields to be zeroes
ubyte[maxDigits] digits;
}
else
{
ubyte[maxDigits] digits = void;
}
size_t pos;
for (Num window = num; window != 0; window /= 10)
{
import std.math : abs;
digits[pos++] = cast(ubyte)abs(window % 10);
}
static if (leadingZeroes > 0)
{
import std.algorithm.comparison : max;
size_t startingPos = max(leadingZeroes, pos);
}
else
{
alias startingPos = pos;
}
foreach_reverse (immutable digit; digits[0..startingPos])
{
sink.put(cast(char)(digit + '0'));
}
}
///
unittest
{
import std.array : Appender;
Appender!(char[]) sink;
{
enum num = 123_456;
num.toAlphaInto(sink);
assert((sink.data == "123456"), sink.data);
sink.clear();
}
{
enum num = 0;
num.toAlphaInto(sink);
assert((sink.data == "0"), sink.data);
sink.clear();
}
{
enum num = 999;
num.toAlphaInto(sink);
assert((sink.data == "999"), sink.data);
sink.clear();
}
{
enum num = -987;
num.toAlphaInto(sink);
assert((sink.data == "-987"), sink.data);
sink.clear();
}
{
enum num = 123;
num.toAlphaInto!(12, 6)(sink);
assert((sink.data == "000123"), sink.data);
sink.clear();
}
{
enum num = -1;
num.toAlphaInto!(3, 3)(sink);
assert((sink.data == "-001"), sink.data);
sink.clear();
}
{
enum num = -123_456_789_012_345L;
num.toAlphaInto!15(sink);
assert((sink.data == "-123456789012345"), sink.data);
sink.clear();
}
{
enum num = long.min;
num.toAlphaInto(sink);
assert((sink.data == "-9223372036854775808"), sink.data);
//sink.clear();
}
}
// toAlpha
/++
Translates an integer into an alphanumeric string. Assumes ASCII.
Overload that returns the string.
Merely leverages [toAlphaInto].
Example:
---
int num = 12345;
string asString = num.toAlpha;
assert(asString == "12345");
assert(asString == num.to!string);
---
Params:
maxDigits = The maximum number of digits to expect input of.
leadingZeroes = The minimum amount of leading zeroes to include in the
output, mirroring the format specifier "`%0nd`".
num = Integer to translate into string.
Returns:
The passed integer `num` in string form.
+/
string toAlpha(size_t maxDigits = 19, uint leadingZeroes = 0, Num)(const Num num) pure
{
import std.array : Appender;
Appender!(char[]) sink;
sink.reserve((num >= 0) ? maxDigits : maxDigits+1);
num.toAlphaInto!(maxDigits, leadingZeroes, Num)(sink);
return sink.data;
}
///
unittest
{
{
enum num = 123_456;
immutable translated = num.toAlpha;
assert((translated == "123456"), translated);
}
{
enum num = 0;
immutable translated = num.toAlpha;
assert((translated == "0"), translated);
}
{
enum num = 999;
immutable translated = num.toAlpha;
assert((translated == "999"), translated);
}
{
enum num = -987;
immutable translated = num.toAlpha;
assert((translated == "-987"), translated);
}
{
enum num = 123;
immutable translated = num.toAlpha!(12, 6);
assert((translated == "000123"), translated);
}
{
enum num = -1;
immutable translated = num.toAlpha!(3, 3);
assert((translated == "-001"), translated);
}
{
enum num = -123_456_789_012_345L;
immutable translated = num.toAlpha!15;
assert((translated == "-123456789012345"), translated);
}
{
enum num = long.min;
immutable translated = num.toAlpha;
assert((translated == "-9223372036854775808"), translated);
}
}