-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathconv.d
More file actions
410 lines (341 loc) · 10.3 KB
/
conv.d
File metadata and controls
410 lines (341 loc) · 10.3 KB
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
/++
A simplified version of `std.conv` with better error messages and faster compiles for supported types.
History:
Added May 22, 2025
+/
module arsd.conv;
static import arsd.core;
// FIXME: thousands separator for int to string (and float to string)
// FIXME: intToStringArgs
// FIXME: floatToStringArgs
/++
Converts a string into the other given type. Throws on failure.
+/
T to(T)(scope const(char)[] str) {
static if(is(T == enum)) {
switch(str) {
default:
throw new EnumConvException(T.stringof, str.idup);
foreach(memberName; __traits(allMembers, T))
case memberName:
return __traits(getMember, T, memberName);
}
}
else
static if(is(T : long)) {
// FIXME: unsigned? overflowing? radix? keep reading or stop on invalid char?
StringToIntArgs args;
args.unsigned = __traits(isUnsigned, T);
long v = stringToInt(str, args);
T ret = cast(T) v;
if(ret != v)
throw new StringToIntConvException("overflow", 0, str.idup, 0);
return ret;
}
else
static if(is(T : double)) {
import core.stdc.stdlib;
import core.stdc.errno;
arsd.core.CharzBuffer z = str;
char* end;
errno = 0;
double res = strtod(z.ptr, &end);
if(end !is (z.ptr + z.length) || errno) {
string msg = errno == ERANGE ? "Over/underflow" : "Invalid input";
throw new StringToIntConvException(msg, 10, str.idup, end - z.ptr);
}
return res;
}
else
{
static assert(0, "Unsupported type: " ~ T.stringof);
}
}
/++
Converts any given value to a string. The format of the string is unspecified; it is meant for a human reader and might be overridden by types.
+/
string to(T:string, From)(From value) {
static if(is(From == enum))
return arsd.core.enumNameForValue(value);
else
return arsd.core.toStringInternal(value);
}
/++
Converts ints to other types of ints or enums
+/
T to(T)(long value) {
static if(is(T == enum))
return cast(T) value; // FIXME check if the value is actually in range
else
return checkedConversion!T(value);
}
/+
T to(T, F)(F value) if(!is(F : const(char)[])) {
// if the language allows implicit conversion, let it do its thing
static if(is(T : F)) {
return value;
}
else
// integral type conversions do checked things
static if(is(T : long) && is(F : long)) {
return checkedConversion!T(value);
}
else
// array to array conversion: try to convert the individual elements, allocating a new return value.
static if(is(T : TE[], TE) && is(F : FE[], FE)) {
F ret = new F(value.length);
foreach(i, e; value)
ret[i] = to!TE(e);
return ret;
}
else
static assert(0, "Unsupported conversion types");
}
+/
unittest {
assert(to!int("5") == 5);
assert(to!int("35") == 35);
assert(to!string(35) == "35");
assert(to!int("0xA35d") == 0xA35d);
assert(to!int("0b11001001") == 0b11001001);
assert(to!int("0o777") == 511 /*0o777*/);
assert(to!ubyte("255") == 255);
assert(to!ulong("18446744073709551615") == ulong.max);
void expectedToThrow(T...)(lazy T items) {
int count;
string messages;
static foreach(idx, item; items) {
try {
auto result = item;
if(messages.length)
messages ~= ",";
messages ~= idx.stringof[0..$-2];
} catch(StringToIntConvException e) {
// passed the test; it was supposed to throw.
// arsd.core.writeln(e);
count++;
}
}
assert(count == T.length, "Arg(s) " ~ messages ~ " did not throw");
}
expectedToThrow(
to!uint("-44"), // negative number to unsigned reuslt
to!int("add"), // invalid base 10 chars
to!byte("129"), // wrapped to negative
to!int("0p4a0"), // invalid radix prefix
to!int("5000000000"), // doesn't fit in int
to!ulong("6000000000000000000900"), // overflow when reading into the ulong buffer
);
}
/++
+/
class ConvException : arsd.core.ArsdExceptionBase {
this(string msg, string file, size_t line) {
super(msg, file, line);
}
}
/++
+/
class ValueOutOfRangeException : ConvException {
this(string type, long userSuppliedValue, long minimumAcceptableValue, long maximumAcceptableValue, string file = __FILE__, size_t line = __LINE__) {
this.type = type;
this.userSuppliedValue = userSuppliedValue;
this.minimumAcceptableValue = minimumAcceptableValue;
this.maximumAcceptableValue = maximumAcceptableValue;
super("Value was out of range", file, line);
}
string type;
long userSuppliedValue;
long minimumAcceptableValue;
long maximumAcceptableValue;
override void getAdditionalPrintableInformation(scope void delegate(string name, in char[] value) sink) const {
sink("type", type);
sink("userSuppliedValue", arsd.core.toStringInternal(userSuppliedValue));
sink("minimumAcceptableValue", arsd.core.toStringInternal(minimumAcceptableValue));
sink("maximumAcceptableValue", arsd.core.toStringInternal(maximumAcceptableValue));
}
}
/++
+/
class EnumConvException : ConvException {
this(string type, string userSuppliedValue, string file = __FILE__, size_t line = __LINE__) {
this.type = type;
this.userSuppliedValue = userSuppliedValue;
super("No such enum value", file, line);
}
string type;
string userSuppliedValue;
override void getAdditionalPrintableInformation(scope void delegate(string name, in char[] value) sink) const {
sink("type", type);
sink("userSuppliedValue", userSuppliedValue);
}
}
unittest {
enum A { a, b, c }
// to!A("d");
}
/++
+/
class StringToIntConvException : arsd.core.ArsdExceptionBase /*InvalidDataException*/ {
this(string msg, int radix, string userInput, size_t offset, string file = __FILE__, size_t line = __LINE__) {
this.radix = radix;
this.userInput = userInput;
this.offset = offset;
super(msg, file, line);
}
override void getAdditionalPrintableInformation(scope void delegate(string name, in char[] value) sink) const {
sink("radix", arsd.core.toStringInternal(radix));
sink("userInput", arsd.core.toStringInternal(userInput));
if(offset < userInput.length)
sink("offset", arsd.core.toStringInternal(offset) ~ " ('" ~ userInput[offset] ~ "')");
}
///
int radix;
///
string userInput;
///
size_t offset;
}
/++
if radix is 0, guess from 0o, 0x, 0b prefixes.
+/
long stringToInt(scope const(char)[] str, StringToIntArgs args = StringToIntArgs.init) {
long accumulator;
auto original = str;
Exception exception(string msg, size_t loopOffset = 0, string file = __FILE__, size_t line = __LINE__) {
return new StringToIntConvException(msg, args.radix, original.dup, loopOffset + str.ptr - original.ptr, file, line);
}
if(str.length == 0)
throw exception("empty string");
bool isNegative;
if(str[0] == '-') {
if(args.unsigned)
throw exception("negative number given, but unsigned result desired");
isNegative = true;
str = str[1 .. $];
}
if(str.length == 0)
throw exception("just a dash");
if(str[0] == '0') {
if(str.length > 1 && (str[1] == 'b' || str[1] == 'x' || str[1] == 'o')) {
if(args.radix != 0) {
throw exception("string had specified base, but the radix arg was already supplied");
}
switch(str[1]) {
case 'b':
args.radix = 2;
break;
case 'o':
args.radix = 8;
break;
case 'x':
args.radix = 16;
break;
default:
assert(0);
}
str = str[2 .. $];
if(str.length == 0)
throw exception("just a prefix");
}
}
if(args.radix == 0)
args.radix = 10;
foreach(idx, char ch; str) {
if(ch && ch == args.ignoredSeparator)
continue;
auto before = accumulator;
accumulator *= args.radix;
int value = -1;
if(ch >= '0' && ch <= '9') {
value = ch - '0';
} else {
ch |= 32;
if(ch >= 'a' && ch <= 'z')
value = ch - 'a' + 10;
}
if(value < 0)
throw exception("invalid char", idx);
if(value >= args.radix)
throw exception("invalid char for given radix", idx);
accumulator += value;
if(args.unsigned) {
auto b = cast(ulong) before;
auto a = cast(ulong) accumulator;
if(a < b)
throw exception("value too big to fit in unsigned buffer", idx);
} else {
if(accumulator < before && !args.unsigned)
throw exception("value too big to fit in signed buffer", idx);
}
}
if(isNegative)
accumulator = -accumulator;
return accumulator;
}
/// ditto
struct StringToIntArgs {
int radix;
bool unsigned;
char ignoredSeparator = 0;
}
/++
Converts two integer types, returning the min/max of the desired type if the given value is out of range for it.
+/
T saturatingConversion(T)(long value) {
static assert(is(T : long), "Only works on integer types");
static if(is(T == ulong)) // the special case to try to handle the full range there
ulong mv = cast(ulong) value;
else
long mv = value;
if(mv > T.max)
return T.max;
else if(value < T.min)
return T.min;
else
return cast(T) value;
}
unittest {
assert(saturatingConversion!ubyte(256) == 255);
assert(saturatingConversion!byte(256) == 127);
assert(saturatingConversion!byte(-256) == -128);
assert(saturatingConversion!ulong(0) == 0);
assert(saturatingConversion!long(-5) == -5);
assert(saturatingConversion!uint(-5) == 0);
// assert(saturatingConversion!ulong(-5) == 0); // it can't catch this since the -5 is indistinguishable from the large ulong value here
}
/++
Truncates off bits that won't fit; equivalent to a built-in cast operation (you can just use a cast instead if you want).
+/
T truncatingConversion(T)(long value) {
static assert(is(T : long), "Only works on integer types");
return cast(T) value;
}
/++
Converts two integer types, throwing an exception if the given value is out of range for it.
+/
T checkedConversion(T)(long value, long minimumAcceptableValue = T.min, long maximumAcceptableValue = T.max) {
static assert(is(T : long), "Only works on integer types");
if(value > maximumAcceptableValue)
throw new ValueOutOfRangeException(T.stringof, value, minimumAcceptableValue, maximumAcceptableValue);
else if(value < minimumAcceptableValue)
throw new ValueOutOfRangeException(T.stringof, value, minimumAcceptableValue, maximumAcceptableValue);
else
return cast(T) value;
}
/// ditto
T checkedConversion(T:ulong)(ulong value, ulong minimumAcceptableValue = T.min, ulong maximumAcceptableValue = T.max) {
if(value > maximumAcceptableValue)
throw new ValueOutOfRangeException(T.stringof, value, minimumAcceptableValue, maximumAcceptableValue);
else if(value < minimumAcceptableValue)
throw new ValueOutOfRangeException(T.stringof, value, minimumAcceptableValue, maximumAcceptableValue);
else
return cast(T) value;
}
unittest {
try {
assert(checkedConversion!byte(155));
assert(0);
} catch(ValueOutOfRangeException e) {
}
}