Debian Codegraph @

libphobos/src/std/conv.d

raw
1 // Written in the D programming language.
2
3 /**
4 A one-stop shop for converting values from one type to another.
5
6 $(SCRIPT inhibitQuickIndex = 1;)
7 $(DIVC quickindex,
8 $(BOOKTABLE,
9 $(TR $(TH Category) $(TH Functions))
10 $(TR $(TD Generic) $(TD
11 $(LREF asOriginalType)
12 $(LREF castFrom)
13 $(LREF parse)
14 $(LREF to)
15 $(LREF toChars)
16 $(LREF bitCast)
17 ))
18 $(TR $(TD Strings) $(TD
19 $(LREF text)
20 $(LREF wtext)
21 $(LREF dtext)
22 $(LREF hexString)
23 ))
24 $(TR $(TD Numeric) $(TD
25 $(LREF octal)
26 $(LREF roundTo)
27 $(LREF signed)
28 $(LREF unsigned)
29 ))
30 $(TR $(TD Exceptions) $(TD
31 $(LREF ConvException)
32 $(LREF ConvOverflowException)
33 ))
34 ))
35
36 Copyright: Copyright The D Language Foundation 2007-.
37
38 License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
39
40 Authors: $(HTTP digitalmars.com, Walter Bright),
41 $(HTTP erdani.org, Andrei Alexandrescu),
42 Shin Fujishiro,
43 Adam D. Ruppe,
44 Kenji Hara
45
46 Source: $(PHOBOSSRC std/conv.d)
47
48 */
49 module std.conv;
50
51 public import std.ascii : LetterCase;
52
53 import std.meta;
54 import std.range;
55 import std.traits;
56 import std.typecons : Flag, Yes, No, tuple, isTuple;
57
58 // Same as std.string.format, but "self-importing".
59 // Helps reduce code and imports, particularly in static asserts.
60 // Also helps with missing imports errors.
61 package template convFormat()
62 {
63 import std.format : format;
64 alias convFormat = format;
65 }
66
67 /* ************* Exceptions *************** */
68
69 /**
70 * Thrown on conversion errors.
71 */
72 class ConvException : Exception
73 {
74 import std.exception : basicExceptionCtors;
75 ///
76 mixin basicExceptionCtors;
77 }
78
79 ///
80 @safe unittest
81 {
82 import std.exception : assertThrown;
83 assertThrown!ConvException(to!int("abc"));
84 }
85
86 private auto convError(S, T)(S source, string fn = __FILE__, size_t ln = __LINE__)
87 {
88 string msg;
89
90 if (source.empty)
91 msg = "Unexpected end of input when converting from type " ~ S.stringof ~ " to type " ~ T.stringof;
92 else
93 {
94 ElementType!S el = source.front;
95
96 if (el == '\n')
97 msg = text("Unexpected '\\n' when converting from type " ~ S.stringof ~ " to type " ~ T.stringof);
98 else
99 msg = text("Unexpected '", el,
100 "' when converting from type " ~ S.stringof ~ " to type " ~ T.stringof);
101 }
102
103 return new ConvException(msg, fn, ln);
104 }
105
106 @safe pure/* nothrow*/ // lazy parameter bug
107 private auto parseError(lazy string msg, string fn = __FILE__, size_t ln = __LINE__)
108 {
109 return new ConvException(text("Can't parse string: ", msg), fn, ln);
110 }
111
112 private void parseCheck(alias source)(dchar c, string fn = __FILE__, size_t ln = __LINE__)
113 {
114 if (source.empty)
115 throw parseError(text("unexpected end of input when expecting \"", c, "\""));
116 if (source.front != c)
117 throw parseError(text("\"", c, "\" is missing"), fn, ln);
118 source.popFront();
119 }
120
121 private
122 {
123 T toStr(T, S)(S src)
124 if (isSomeString!T)
125 {
126 // workaround for https://issues.dlang.org/show_bug.cgi?id=14198
127 static if (is(S == bool) && is(typeof({ T s = "string"; })))
128 {
129 return src ? "true" : "false";
130 }
131 else
132 {
133 import std.array : appender;
134 import std.format.spec : FormatSpec;
135 import std.format.write : formatValue;
136
137 auto w = appender!T();
138 FormatSpec!(ElementEncodingType!T) f;
139 formatValue(w, src, f);
140 return w.data;
141 }
142 }
143
144 template isExactSomeString(T)
145 {
146 enum isExactSomeString = isSomeString!T && !is(T == enum);
147 }
148
149 template isEnumStrToStr(S, T)
150 {
151 enum isEnumStrToStr = is(S : T) &&
152 is(S == enum) && isExactSomeString!T;
153 }
154 template isNullToStr(S, T)
155 {
156 enum isNullToStr = is(S : T) &&
157 (is(immutable S == immutable typeof(null))) && isExactSomeString!T;
158 }
159 }
160
161 /**
162 * Thrown on conversion overflow errors.
163 */
164 class ConvOverflowException : ConvException
165 {
166 @safe pure nothrow
167 this(string s, string fn = __FILE__, size_t ln = __LINE__)
168 {
169 super(s, fn, ln);
170 }
171 }
172
173 ///
174 @safe unittest
175 {
176 import std.exception : assertThrown;
177 assertThrown!ConvOverflowException(to!ubyte(1_000_000));
178 }
179
180 /**
181 The `to` template converts a value from one type _to another.
182 The source type is deduced and the target type must be specified, for example the
183 expression `to!int(42.0)` converts the number 42 from
184 `double` _to `int`. The conversion is "safe", i.e.,
185 it checks for overflow; `to!int(4.2e10)` would throw the
186 `ConvOverflowException` exception. Overflow checks are only
187 inserted when necessary, e.g., `to!double(42)` does not do
188 any checking because any `int` fits in a `double`.
189
190 Conversions from string _to numeric types differ from the C equivalents
191 `atoi()` and `atol()` by checking for overflow and not allowing whitespace.
192
193 For conversion of strings _to signed types, the grammar recognized is:
194 $(PRE $(I Integer):
195 $(I Sign UnsignedInteger)
196 $(I UnsignedInteger)
197 $(I Sign):
198 $(B +)
199 $(B -))
200
201 For conversion _to unsigned types, the grammar recognized is:
202 $(PRE $(I UnsignedInteger):
203 $(I DecimalDigit)
204 $(I DecimalDigit) $(I UnsignedInteger))
205 */
206 template to(T)
207 {
208 T to(A...)(A args)
209 if (A.length > 0)
210 {
211 return toImpl!T(args);
212 }
213
214 // Fix https://issues.dlang.org/show_bug.cgi?id=6175
215 T to(S)(ref S arg)
216 if (isStaticArray!S)
217 {
218 return toImpl!T(arg);
219 }
220
221 // Fix https://issues.dlang.org/show_bug.cgi?id=16108
222 T to(S)(ref S arg)
223 if (isAggregateType!S && !isCopyable!S)
224 {
225 return toImpl!T(arg);
226 }
227 }
228
229 /**
230 * Converting a value _to its own type (useful mostly for generic code)
231 * simply returns its argument.
232 */
233 @safe pure unittest
234 {
235 int a = 42;
236 int b = to!int(a);
237 double c = to!double(3.14); // c is double with value 3.14
238 }
239
240 /**
241 * Converting among numeric types is a safe way _to cast them around.
242 *
243 * Conversions from floating-point types _to integral types allow loss of
244 * precision (the fractional part of a floating-point number). The
245 * conversion is truncating towards zero, the same way a cast would
246 * truncate. (_To round a floating point value when casting _to an
247 * integral, use `roundTo`.)
248 */
249 @safe pure unittest
250 {
251 import std.exception : assertThrown;
252
253 int a = 420;
254 assert(to!long(a) == a);
255 assertThrown!ConvOverflowException(to!byte(a));
256
257 assert(to!int(4.2e6) == 4200000);
258 assertThrown!ConvOverflowException(to!uint(-3.14));
259 assert(to!uint(3.14) == 3);
260 assert(to!uint(3.99) == 3);
261 assert(to!int(-3.99) == -3);
262 }
263
264 /**
265 * When converting strings _to numeric types, note that D hexadecimal and binary
266 * literals are not handled. Neither the prefixes that indicate the base, nor the
267 * horizontal bar used _to separate groups of digits are recognized. This also
268 * applies to the suffixes that indicate the type.
269 *
270 * _To work around this, you can specify a radix for conversions involving numbers.
271 */
272 @safe pure unittest
273 {
274 auto str = to!string(42, 16);
275 assert(str == "2A");
276 auto i = to!int(str, 16);
277 assert(i == 42);
278 }
279
280 /**
281 * Conversions from integral types _to floating-point types always
282 * succeed, but might lose accuracy. The largest integers with a
283 * predecessor representable in floating-point format are `2^24-1` for
284 * `float`, `2^53-1` for `double`, and `2^64-1` for `real` (when
285 * `real` is 80-bit, e.g. on Intel machines).
286 */
287 @safe pure unittest
288 {
289 // 2^24 - 1, largest proper integer representable as float
290 int a = 16_777_215;
291 assert(to!int(to!float(a)) == a);
292 assert(to!int(to!float(-a)) == -a);
293 }
294
295 /**
296 Conversion from string types to char types enforces the input
297 to consist of a single code point, and said code point must
298 fit in the target type. Otherwise, $(LREF ConvException) is thrown.
299 */
300 @safe pure unittest
301 {
302 import std.exception : assertThrown;
303
304 assert(to!char("a") == 'a');
305 assertThrown(to!char("ñ")); // 'ñ' does not fit into a char
306 assert(to!wchar("ñ") == 'ñ');
307 assertThrown(to!wchar("😃")); // '😃' does not fit into a wchar
308 assert(to!dchar("😃") == '😃');
309
310 // Using wstring or dstring as source type does not affect the result
311 assert(to!char("a"w) == 'a');
312 assert(to!char("a"d) == 'a');
313
314 // Two code points cannot be converted to a single one
315 assertThrown(to!char("ab"));
316 }
317
318 /**
319 * Converting an array _to another array type works by converting each
320 * element in turn. Associative arrays can be converted _to associative
321 * arrays as long as keys and values can in turn be converted.
322 */
323 @safe pure unittest
324 {
325 import std.string : split;
326
327 int[] a = [1, 2, 3];
328 auto b = to!(float[])(a);
329 assert(b == [1.0f, 2, 3]);
330 string str = "1 2 3 4 5 6";
331 auto numbers = to!(double[])(split(str));
332 assert(numbers == [1.0, 2, 3, 4, 5, 6]);
333 int[string] c;
334 c["a"] = 1;
335 c["b"] = 2;
336 auto d = to!(double[wstring])(c);
337 assert(d["a"w] == 1 && d["b"w] == 2);
338 }
339
340 /**
341 * Conversions operate transitively, meaning that they work on arrays and
342 * associative arrays of any complexity.
343 *
344 * This conversion works because `to!short` applies _to an `int`, `to!wstring`
345 * applies _to a `string`, `to!string` applies _to a `double`, and
346 * `to!(double[])` applies _to an `int[]`. The conversion might throw an
347 * exception because `to!short` might fail the range check.
348 */
349 @safe unittest
350 {
351 int[string][double[int[]]] a;
352 auto b = to!(short[wstring][string[double[]]])(a);
353 }
354
355 /**
356 * Object-to-object conversions by dynamic casting throw exception when
357 * the source is non-null and the target is null.
358 */
359 @safe pure unittest
360 {
361 import std.exception : assertThrown;
362 // Testing object conversions
363 class A {}
364 class B : A {}
365 class C : A {}
366 A a1 = new A, a2 = new B, a3 = new C;
367 assert(to!B(a2) is a2);
368 assert(to!C(a3) is a3);
369 assertThrown!ConvException(to!B(a3));
370 }
371
372 /**
373 * Stringize conversion from all types is supported.
374 * $(UL
375 * $(LI String _to string conversion works for any two string types having
376 * (`char`, `wchar`, `dchar`) character widths and any
377 * combination of qualifiers (mutable, `const`, or `immutable`).)
378 * $(LI Converts array (other than strings) _to string.
379 * Each element is converted by calling `to!T`.)
380 * $(LI Associative array _to string conversion.
381 * Each element is converted by calling `to!T`.)
382 * $(LI Object _to string conversion calls `toString` against the object or
383 * returns `"null"` if the object is null.)
384 * $(LI Struct _to string conversion calls `toString` against the struct if
385 * it is defined.)
386 * $(LI For structs that do not define `toString`, the conversion _to string
387 * produces the list of fields.)
388 * $(LI Enumerated types are converted _to strings as their symbolic names.)
389 * $(LI Boolean values are converted to `"true"` or `"false"`.)
390 * $(LI `char`, `wchar`, `dchar` _to a string type.)
391 * $(LI Unsigned or signed integers _to strings.
392 * $(DL $(DT [special case])
393 * $(DD Convert integral value _to string in $(D_PARAM radix) radix.
394 * radix must be a value from 2 to 36.
395 * value is treated as a signed value only if radix is 10.
396 * The characters A through Z are used to represent values 10 through 36
397 * and their case is determined by the $(D_PARAM letterCase) parameter.)))
398 * $(LI All floating point types _to all string types.)
399 * $(LI Pointer to string conversions convert the pointer to a `size_t` value.
400 * If pointer is `char*`, treat it as C-style strings.
401 * In that case, this function is `@system`.))
402 * See $(REF formatValue, std,format) on how `toString` should be defined.
403 */
404 @system pure unittest // @system due to cast and ptr
405 {
406 // Conversion representing dynamic/static array with string
407 long[] a = [ 1, 3, 5 ];
408 assert(to!string(a) == "[1, 3, 5]");
409
410 // Conversion representing associative array with string
411 int[string] associativeArray = ["0":1, "1":2];
412 assert(to!string(associativeArray) == `["0":1, "1":2]` ||
413 to!string(associativeArray) == `["1":2, "0":1]`);
414
415 // char* to string conversion
416 assert(to!string(cast(char*) null) == "");
417 assert(to!string("foo\0".ptr) == "foo");
418
419 // Conversion reinterpreting void array to string
420 auto w = "abcx"w;
421 const(void)[] b = w;
422 assert(b.length == 8);
423
424 auto c = to!(wchar[])(b);
425 assert(c == "abcx");
426 }
427
428 /**
429 * Strings can be converted to enum types. The enum member with the same name as the
430 * input string is returned. The comparison is case-sensitive.
431 *
432 * A $(LREF ConvException) is thrown if the enum does not have the specified member.
433 */
434 @safe pure unittest
435 {
436 import std.exception : assertThrown;
437
438 enum E { a, b, c }
439 assert(to!E("a") == E.a);
440 assert(to!E("b") == E.b);
441 assertThrown!ConvException(to!E("A"));
442 }
443
444 // Tests for https://issues.dlang.org/show_bug.cgi?id=6175
445 @safe pure nothrow unittest
446 {
447 char[9] sarr = "blablabla";
448 auto darr = to!(char[])(sarr);
449 assert(sarr.ptr == darr.ptr);
450 assert(sarr.length == darr.length);
451 }
452
453 // Tests for https://issues.dlang.org/show_bug.cgi?id=7348
454 @safe pure /+nothrow+/ unittest
455 {
456 assert(to!string(null) == "null");
457 assert(text(null) == "null");
458 }
459
460 // Test `scope` inference of parameters of `text`
461 @safe unittest
462 {
463 static struct S
464 {
465 int* x; // make S a type with pointers
466 string toString() const scope
467 {
468 return "S";
469 }
470 }
471 scope S s;
472 assert(text("a", s) == "aS");
473 }
474
475 // Tests for https://issues.dlang.org/show_bug.cgi?id=11390
476 @safe pure /+nothrow+/ unittest
477 {
478 const(typeof(null)) ctn;
479 immutable(typeof(null)) itn;
480 assert(to!string(ctn) == "null");
481 assert(to!string(itn) == "null");
482 }
483
484 // Tests for https://issues.dlang.org/show_bug.cgi?id=8729: do NOT skip leading WS
485 @safe pure unittest
486 {
487 import std.exception;
488 static foreach (T; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
489 {
490 assertThrown!ConvException(to!T(" 0"));
491 assertThrown!ConvException(to!T(" 0", 8));
492 }
493 static foreach (T; AliasSeq!(float, double, real))
494 {
495 assertThrown!ConvException(to!T(" 0"));
496 }
497
498 assertThrown!ConvException(to!bool(" true"));
499
500 alias NullType = typeof(null);
501 assertThrown!ConvException(to!NullType(" null"));
502
503 alias ARR = int[];
504 assertThrown!ConvException(to!ARR(" [1]"));
505
506 alias AA = int[int];
507 assertThrown!ConvException(to!AA(" [1:1]"));
508 }
509
510 // https://issues.dlang.org/show_bug.cgi?id=20623
511 @safe pure nothrow unittest
512 {
513 // static class C
514 // {
515 // override string toString() const
516 // {
517 // return "C()";
518 // }
519 // }
520
521 static struct S
522 {
523 bool b;
524 int i;
525 float f;
526 int[] a;
527 int[int] aa;
528 S* p;
529 // C c; // TODO: Fails because of hasToString
530
531 void fun() inout
532 {
533 static foreach (const idx; 0 .. this.tupleof.length)
534 {
535 {
536 const _ = this.tupleof[idx].to!string();
537 }
538 }
539 }
540 }
541 }
542
543 /**
544 If the source type is implicitly convertible to the target type, $(D
545 to) simply performs the implicit conversion.
546 */
547 private T toImpl(T, S)(S value)
548 if (is(S : T) &&
549 !isEnumStrToStr!(S, T) && !isNullToStr!(S, T))
550 {
551 template isSignedInt(T)
552 {
553 enum isSignedInt = isIntegral!T && isSigned!T;
554 }
555 alias isUnsignedInt = isUnsigned;
556
557 // Conversion from integer to integer, and changing its sign
558 static if (isUnsignedInt!S && isSignedInt!T && S.sizeof == T.sizeof)
559 { // unsigned to signed & same size
560 import std.exception : enforce;
561 enforce(value <= cast(S) T.max,
562 new ConvOverflowException("Conversion positive overflow"));
563 }
564 else static if (isSignedInt!S && isUnsignedInt!T)
565 { // signed to unsigned
566 import std.exception : enforce;
567 enforce(0 <= value,
568 new ConvOverflowException("Conversion negative overflow"));
569 }
570
571 return value;
572 }
573
574 // https://issues.dlang.org/show_bug.cgi?id=9523: Allow identity enum conversion
575 @safe pure nothrow unittest
576 {
577 enum E { a }
578 auto e = to!E(E.a);
579 assert(e == E.a);
580 }
581
582 @safe pure nothrow unittest
583 {
584 int a = 42;
585 auto b = to!long(a);
586 assert(a == b);
587 }
588
589 // https://issues.dlang.org/show_bug.cgi?id=6377
590 @safe pure unittest
591 {
592 import std.exception;
593 // Conversion between same size
594 static foreach (S; AliasSeq!(byte, short, int, long))
595 {{
596 alias U = Unsigned!S;
597
598 static foreach (Sint; AliasSeq!(S, const S, immutable S))
599 static foreach (Uint; AliasSeq!(U, const U, immutable U))
600 {{
601 // positive overflow
602 Uint un = Uint.max;
603 assertThrown!ConvOverflowException(to!Sint(un),
604 text(Sint.stringof, ' ', Uint.stringof, ' ', un));
605
606 // negative overflow
607 Sint sn = -1;
608 assertThrown!ConvOverflowException(to!Uint(sn),
609 text(Sint.stringof, ' ', Uint.stringof, ' ', un));
610 }}
611 }}
612
613 // Conversion between different size
614 static foreach (i, S1; AliasSeq!(byte, short, int, long))
615 static foreach ( S2; AliasSeq!(byte, short, int, long)[i+1..$])
616 {{
617 alias U1 = Unsigned!S1;
618 alias U2 = Unsigned!S2;
619
620 static assert(U1.sizeof < S2.sizeof);
621
622 // small unsigned to big signed
623 static foreach (Uint; AliasSeq!(U1, const U1, immutable U1))
624 static foreach (Sint; AliasSeq!(S2, const S2, immutable S2))
625 {{
626 Uint un = Uint.max;
627 assertNotThrown(to!Sint(un));
628 assert(to!Sint(un) == un);
629 }}
630
631 // big unsigned to small signed
632 static foreach (Uint; AliasSeq!(U2, const U2, immutable U2))
633 static foreach (Sint; AliasSeq!(S1, const S1, immutable S1))
634 {{
635 Uint un = Uint.max;
636 assertThrown(to!Sint(un));
637 }}
638
639 static assert(S1.sizeof < U2.sizeof);
640
641 // small signed to big unsigned
642 static foreach (Sint; AliasSeq!(S1, const S1, immutable S1))
643 static foreach (Uint; AliasSeq!(U2, const U2, immutable U2))
644 {{
645 Sint sn = -1;
646 assertThrown!ConvOverflowException(to!Uint(sn));
647 }}
648
649 // big signed to small unsigned
650 static foreach (Sint; AliasSeq!(S2, const S2, immutable S2))
651 static foreach (Uint; AliasSeq!(U1, const U1, immutable U1))
652 {{
653 Sint sn = -1;
654 assertThrown!ConvOverflowException(to!Uint(sn));
655 }}
656 }}
657 }
658
659 // https://issues.dlang.org/show_bug.cgi?id=13551
660 private T toImpl(T, S)(S value)
661 if (isTuple!T)
662 {
663 T t;
664 static foreach (i; 0 .. T.length)
665 {
666 t[i] = value[i].to!(typeof(T[i]));
667 }
668 return t;
669 }
670
671 @safe unittest
672 {
673 import std.typecons : Tuple;
674
675 auto test = ["10", "20", "30"];
676 assert(test.to!(Tuple!(int, int, int)) == Tuple!(int, int, int)(10, 20, 30));
677
678 auto test1 = [1, 2];
679 assert(test1.to!(Tuple!(int, int)) == Tuple!(int, int)(1, 2));
680
681 auto test2 = [1.0, 2.0, 3.0];
682 assert(test2.to!(Tuple!(int, int, int)) == Tuple!(int, int, int)(1, 2, 3));
683 }
684
685 /*
686 Converting static arrays forwards to their dynamic counterparts.
687 */
688 private T toImpl(T, S)(ref S s)
689 if (isStaticArray!S)
690 {
691 return toImpl!(T, typeof(s[0])[])(s);
692 }
693
694 @safe pure nothrow unittest
695 {
696 char[4] test = ['a', 'b', 'c', 'd'];
697 static assert(!isInputRange!(Unqual!(char[4])));
698 assert(to!string(test) == test);
699 }
700
701 /**
702 When source type supports member template function opCast, it is used.
703 */
704 private T toImpl(T, S)(S value)
705 if (!is(S : T) &&
706 is(typeof(S.init.opCast!T()) : T) &&
707 !isExactSomeString!T &&
708 !is(typeof(T(value))))
709 {
710 return value.opCast!T();
711 }
712
713 @safe pure unittest
714 {
715 static struct Test
716 {
717 struct T
718 {
719 this(S s) @safe pure { }
720 }
721 struct S
722 {
723 T opCast(U)() @safe pure { assert(false); }
724 }
725 }
726 cast(void) to!(Test.T)(Test.S());
727
728 // make sure std.conv.to is doing the same thing as initialization
729 Test.S s;
730 Test.T t = s;
731 }
732
733 @safe pure unittest
734 {
735 class B
736 {
737 T opCast(T)() { return 43; }
738 }
739 auto b = new B;
740 assert(to!int(b) == 43);
741
742 struct S
743 {
744 T opCast(T)() { return 43; }
745 }
746 auto s = S();
747 assert(to!int(s) == 43);
748 }
749
750 /**
751 When target type supports 'converting construction', it is used.
752 $(UL $(LI If target type is struct, `T(value)` is used.)
753 $(LI If target type is class, $(D new T(value)) is used.))
754 */
755 private T toImpl(T, S)(S value)
756 if (!is(S : T) &&
757 is(T == struct) && is(typeof(T(value))))
758 {
759 return T(value);
760 }
761
762 // https://issues.dlang.org/show_bug.cgi?id=3961
763 @safe pure unittest
764 {
765 struct Int
766 {
767 int x;
768 }
769 Int i = to!Int(1);
770
771 static struct Int2
772 {
773 int x;
774 this(int x) @safe pure { this.x = x; }
775 }
776 Int2 i2 = to!Int2(1);
777
778 static struct Int3
779 {
780 int x;
781 static Int3 opCall(int x) @safe pure
782 {
783 Int3 i;
784 i.x = x;
785 return i;
786 }
787 }
788 Int3 i3 = to!Int3(1);
789 }
790
791 // https://issues.dlang.org/show_bug.cgi?id=6808
792 @safe pure unittest
793 {
794 static struct FakeBigInt
795 {
796 this(string s) @safe pure {}
797 }
798
799 string s = "101";
800 auto i3 = to!FakeBigInt(s);
801 }
802
803 /// ditto
804 private T toImpl(T, S)(S value)
805 if (!is(S : T) &&
806 is(T == class) && is(typeof(new T(value))))
807 {
808 return new T(value);
809 }
810
811 @safe pure unittest
812 {
813 static struct S
814 {
815 int x;
816 }
817 static class C
818 {
819 int x;
820 this(int x) @safe pure { this.x = x; }
821 }
822
823 static class B
824 {
825 int value;
826 this(S src) @safe pure { value = src.x; }
827 this(C src) @safe pure { value = src.x; }
828 }
829
830 S s = S(1);
831 auto b1 = to!B(s); // == new B(s)
832 assert(b1.value == 1);
833
834 C c = new C(2);
835 auto b2 = to!B(c); // == new B(c)
836 assert(b2.value == 2);
837
838 auto c2 = to!C(3); // == new C(3)
839 assert(c2.x == 3);
840 }
841
842 @safe pure unittest
843 {
844 struct S
845 {
846 class A
847 {
848 this(B b) @safe pure {}
849 }
850 class B : A
851 {
852 this() @safe pure { super(this); }
853 }
854 }
855
856 S.B b = new S.B();
857 S.A a = to!(S.A)(b); // == cast(S.A) b
858 // (do not run construction conversion like new S.A(b))
859 assert(b is a);
860
861 static class C : Object
862 {
863 this() @safe pure {}
864 this(Object o) @safe pure {}
865 }
866
867 Object oc = new C();
868 C a2 = to!C(oc); // == new C(a)
869 // Construction conversion overrides down-casting conversion
870 assert(a2 !is a); //
871 }
872
873 /**
874 Object-to-object conversions by dynamic casting throw exception when the source is
875 non-null and the target is null.
876 */
877 private T toImpl(T, S)(S value)
878 if (!is(S : T) &&
879 (is(S == class) || is(S == interface)) && !is(typeof(value.opCast!T()) : T) &&
880 (is(T == class) || is(T == interface)) && !is(typeof(new T(value))))
881 {
882 static if (is(T == immutable))
883 {
884 // immutable <- immutable
885 enum isModConvertible = is(S == immutable);
886 }
887 else static if (is(T == const))
888 {
889 static if (is(T == shared))
890 {
891 // shared const <- shared
892 // shared const <- shared const
893 // shared const <- immutable
894 enum isModConvertible = is(S == shared) || is(S == immutable);
895 }
896 else
897 {
898 // const <- mutable
899 // const <- immutable
900 enum isModConvertible = !is(S == shared);
901 }
902 }
903 else
904 {
905 static if (is(T == shared))
906 {
907 // shared <- shared mutable
908 enum isModConvertible = is(S == shared) && !is(S == const);
909 }
910 else
911 {
912 // (mutable) <- (mutable)
913 enum isModConvertible = is(Unqual!S == S);
914 }
915 }
916 static assert(isModConvertible, "Bad modifier conversion: "~S.stringof~" to "~T.stringof);
917
918 auto result = ()@trusted{ return cast(T) value; }();
919 if (!result && value)
920 {
921 string name(TypeInfo ti) @trusted
922 {
923 while (auto tc = (cast(TypeInfo_Const) ti))
924 {
925 ti = tc.base;
926 }
927 if (auto tinf = cast(TypeInfo_Interface) ti)
928 {
929 ti = tinf.info;
930 }
931 TypeInfo_Class tc = cast(TypeInfo_Class) ti;
932 assert(tc);
933 return tc.name;
934 }
935 throw new ConvException("Cannot convert object of static type " ~
936 name(typeid(S)) ~ " and dynamic type " ~ name(typeid(value)) ~ " to type " ~ name(typeid(T)));
937 }
938 return result;
939 }
940
941 // Unittest for 6288
942 @safe pure unittest
943 {
944 import std.exception;
945
946 alias Identity(T) = T;
947 alias toConst(T) = const T;
948 alias toShared(T) = shared T;
949 alias toSharedConst(T) = shared const T;
950 alias toImmutable(T) = immutable T;
951 template AddModifier(int n)
952 if (0 <= n && n < 5)
953 {
954 static if (n == 0) alias AddModifier = Identity;
955 else static if (n == 1) alias AddModifier = toConst;
956 else static if (n == 2) alias AddModifier = toShared;
957 else static if (n == 3) alias AddModifier = toSharedConst;
958 else static if (n == 4) alias AddModifier = toImmutable;
959 }
960
961 interface I {}
962 interface J {}
963
964 class A {}
965 class B : A {}
966 class C : B, I, J {}
967 class D : I {}
968
969 static foreach (m1; 0 .. 5) // enumerate modifiers
970 static foreach (m2; 0 .. 5) // ditto
971 {{
972 alias srcmod = AddModifier!m1;
973 alias tgtmod = AddModifier!m2;
974
975 // Compile time convertible equals to modifier convertible.
976 static if (is(srcmod!Object : tgtmod!Object))
977 {
978 // Test runtime conversions: class to class, class to interface,
979 // interface to class, and interface to interface
980
981 // Check that the runtime conversion to succeed
982 srcmod!A ac = new srcmod!C();
983 srcmod!I ic = new srcmod!C();
984 assert(to!(tgtmod!C)(ac) !is null); // A(c) to C
985 assert(to!(tgtmod!I)(ac) !is null); // A(c) to I
986 assert(to!(tgtmod!C)(ic) !is null); // I(c) to C
987 assert(to!(tgtmod!J)(ic) !is null); // I(c) to J
988
989 // Check that the runtime conversion fails
990 srcmod!A ab = new srcmod!B();
991 srcmod!I id = new srcmod!D();
992 assertThrown(to!(tgtmod!C)(ab)); // A(b) to C
993 assertThrown(to!(tgtmod!I)(ab)); // A(b) to I
994 assertThrown(to!(tgtmod!C)(id)); // I(d) to C
995 assertThrown(to!(tgtmod!J)(id)); // I(d) to J
996 }
997 else
998 {
999 // Check that the conversion is rejected statically
1000 static assert(!is(typeof(to!(tgtmod!C)(srcmod!A.init)))); // A to C
1001 static assert(!is(typeof(to!(tgtmod!I)(srcmod!A.init)))); // A to I
1002 static assert(!is(typeof(to!(tgtmod!C)(srcmod!I.init)))); // I to C
1003 static assert(!is(typeof(to!(tgtmod!J)(srcmod!I.init)))); // I to J
1004 }
1005 }}
1006 }
1007
1008 /**
1009 Handles type _to string conversions
1010 */
1011 private T toImpl(T, S)(S value)
1012 if (!(is(S : T) &&
1013 !isEnumStrToStr!(S, T) && !isNullToStr!(S, T)) &&
1014 !isInfinite!S && isExactSomeString!T)
1015 {
1016 static if (isExactSomeString!S && value[0].sizeof == ElementEncodingType!T.sizeof)
1017 {
1018 // string-to-string with incompatible qualifier conversion
1019 static if (is(ElementEncodingType!T == immutable))
1020 {
1021 // conversion (mutable|const) -> immutable
1022 return value.idup;
1023 }
1024 else
1025 {
1026 // conversion (immutable|const) -> mutable
1027 return value.dup;
1028 }
1029 }
1030 else static if (isExactSomeString!S)
1031 {
1032 import std.array : appender;
1033 // other string-to-string
1034 //Use Appender directly instead of toStr, which also uses a formatedWrite
1035 auto w = appender!T();
1036 w.put(value);
1037 return w.data;
1038 }
1039 else static if (isIntegral!S && !is(S == enum))
1040 {
1041 // other integral-to-string conversions with default radix
1042
1043 import core.internal.string : signedToTempString, unsignedToTempString;
1044
1045 alias EEType = Unqual!(ElementEncodingType!T);
1046 EEType[long.sizeof * 3 + 1] buf = void;
1047 EEType[] t = isSigned!S
1048 ? signedToTempString!(10, false, EEType)(value, buf)
1049 : unsignedToTempString!(10, false, EEType)(value, buf);
1050 return t.dup;
1051 }
1052 else static if (is(S == void[]) || is(S == const(void)[]) || is(S == immutable(void)[]))
1053 {
1054 import core.stdc.string : memcpy;
1055 import std.exception : enforce;
1056 // Converting void array to string
1057 alias Char = Unqual!(ElementEncodingType!T);
1058 auto raw = cast(const(ubyte)[]) value;
1059 enforce(raw.length % Char.sizeof == 0,
1060 new ConvException("Alignment mismatch in converting a "
1061 ~ S.stringof ~ " to a "
1062 ~ T.stringof));
1063 auto result = new Char[raw.length / Char.sizeof];
1064 ()@trusted{ memcpy(result.ptr, value.ptr, value.length); }();
1065 return cast(T) result;
1066 }
1067 else static if (isPointer!S && isSomeChar!(PointerTarget!S))
1068 {
1069 // This is unsafe because we cannot guarantee that the pointer is null terminated.
1070 return () @system {
1071 static if (is(S : const(char)*))
1072 import core.stdc.string : strlen;
1073 else
1074 size_t strlen(S s) nothrow
1075 {
1076 S p = s;
1077 while (*p++) {}
1078 return p-s-1;
1079 }
1080 return toImpl!T(value ? value[0 .. strlen(value)].dup : null);
1081 }();
1082 }
1083 else static if (isSomeString!T && is(S == enum))
1084 {
1085 static if (isSwitchable!(OriginalType!S) && EnumMembers!S.length <= 50)
1086 {
1087 switch (value)
1088 {
1089 foreach (member; NoDuplicates!(EnumMembers!S))
1090 {
1091 case member:
1092 return to!T(enumRep!(immutable(T), S, member));
1093 }
1094 default:
1095 }
1096 }
1097 else
1098 {
1099 foreach (member; EnumMembers!S)
1100 {
1101 if (value == member)
1102 return to!T(enumRep!(immutable(T), S, member));
1103 }
1104 }
1105
1106 import std.array : appender;
1107 import std.format.spec : FormatSpec;
1108 import std.format.write : formatValue;
1109
1110 //Default case, delegate to format
1111 //Note: we don't call toStr directly, to avoid duplicate work.
1112 auto app = appender!T();
1113 app.put("cast(" ~ S.stringof ~ ")");
1114 FormatSpec!char f;
1115 formatValue(app, cast(OriginalType!S) value, f);
1116 return app.data;
1117 }
1118 else
1119 {
1120 // other non-string values runs formatting
1121 return toStr!T(value);
1122 }
1123 }
1124
1125 // https://issues.dlang.org/show_bug.cgi?id=14042
1126 @system unittest
1127 {
1128 immutable(char)* ptr = "hello".ptr;
1129 auto result = ptr.to!(char[]);
1130 }
1131 // https://issues.dlang.org/show_bug.cgi?id=8384
1132 @system unittest
1133 {
1134 void test1(T)(T lp, string cmp)
1135 {
1136 static foreach (e; AliasSeq!(char, wchar, dchar))
1137 {
1138 test2!(e[])(lp, cmp);
1139 test2!(const(e)[])(lp, cmp);
1140 test2!(immutable(e)[])(lp, cmp);
1141 }
1142 }
1143
1144 void test2(D, S)(S lp, string cmp)
1145 {
1146 assert(to!string(to!D(lp)) == cmp);
1147 }
1148
1149 static foreach (e; AliasSeq!("Hello, world!", "Hello, world!"w, "Hello, world!"d))
1150 {
1151 test1(e, "Hello, world!");
1152 test1(e.ptr, "Hello, world!");
1153 }
1154 static foreach (e; AliasSeq!("", ""w, ""d))
1155 {
1156 test1(e, "");
1157 test1(e.ptr, "");
1158 }
1159 }
1160
1161 /*
1162 To string conversion for non copy-able structs
1163 */
1164 private T toImpl(T, S)(ref S value)
1165 if (!(is(S : T) &&
1166 !isEnumStrToStr!(S, T) && !isNullToStr!(S, T)) &&
1167 !isInfinite!S && isExactSomeString!T && !isCopyable!S && !isStaticArray!S)
1168 {
1169 import std.array : appender;
1170 import std.format.spec : FormatSpec;
1171 import std.format.write : formatValue;
1172
1173 auto w = appender!T();
1174 FormatSpec!(ElementEncodingType!T) f;
1175 formatValue(w, value, f);
1176 return w.data;
1177 }
1178
1179 // https://issues.dlang.org/show_bug.cgi?id=16108
1180 @safe unittest
1181 {
1182 static struct A
1183 {
1184 int val;
1185 bool flag;
1186
1187 string toString() { return text(val, ":", flag); }
1188
1189 @disable this(this);
1190 }
1191
1192 auto a = A();
1193 assert(to!string(a) == "0:false");
1194
1195 static struct B
1196 {
1197 int val;
1198 bool flag;
1199
1200 @disable this(this);
1201 }
1202
1203 auto b = B();
1204 assert(to!string(b) == "B(0, false)");
1205 }
1206
1207 // https://issues.dlang.org/show_bug.cgi?id=20070
1208 @safe unittest
1209 {
1210 void writeThem(T)(ref inout(T) them)
1211 {
1212 assert(them.to!string == "[1, 2, 3, 4]");
1213 }
1214
1215 const(uint)[4] vals = [ 1, 2, 3, 4 ];
1216 writeThem(vals);
1217 }
1218
1219 /*
1220 Check whether type `T` can be used in a switch statement.
1221 This is useful for compile-time generation of switch case statements.
1222 */
1223 private template isSwitchable(E)
1224 {
1225 enum bool isSwitchable = is(typeof({
1226 switch (E.init) { default: }
1227 }));
1228 }
1229
1230 //
1231 @safe unittest
1232 {
1233 static assert(isSwitchable!int);
1234 static assert(!isSwitchable!double);
1235 static assert(!isSwitchable!real);
1236 }
1237
1238 //Static representation of the index I of the enum S,
1239 //In representation T.
1240 //T must be an immutable string (avoids un-necessary initializations).
1241 private template enumRep(T, S, S value)
1242 if (is (T == immutable) && isExactSomeString!T && is(S == enum))
1243 {
1244 static T enumRep = toStr!T(value);
1245 }
1246
1247 @safe pure unittest
1248 {
1249 import std.exception;
1250 void dg()
1251 {
1252 // string to string conversion
1253 alias Chars = AliasSeq!(char, wchar, dchar);
1254 foreach (LhsC; Chars)
1255 {
1256 alias LhStrings = AliasSeq!(LhsC[], const(LhsC)[], immutable(LhsC)[]);
1257 foreach (Lhs; LhStrings)
1258 {
1259 foreach (RhsC; Chars)
1260 {
1261 alias RhStrings = AliasSeq!(RhsC[], const(RhsC)[], immutable(RhsC)[]);
1262 foreach (Rhs; RhStrings)
1263 {
1264 Lhs s1 = to!Lhs("wyda");
1265 Rhs s2 = to!Rhs(s1);
1266 //writeln(Lhs.stringof, " -> ", Rhs.stringof);
1267 assert(s1 == to!Lhs(s2));
1268 }
1269 }
1270 }
1271 }
1272
1273 foreach (T; Chars)
1274 {
1275 foreach (U; Chars)
1276 {
1277 T[] s1 = to!(T[])("Hello, world!");
1278 auto s2 = to!(U[])(s1);
1279 assert(s1 == to!(T[])(s2));
1280 auto s3 = to!(const(U)[])(s1);
1281 assert(s1 == to!(T[])(s3));
1282 auto s4 = to!(immutable(U)[])(s1);
1283 assert(s1 == to!(T[])(s4));
1284 }
1285 }
1286 }
1287 dg();
1288 assertCTFEable!dg;
1289 }
1290
1291 @safe pure unittest
1292 {
1293 // Conversion representing bool value with string
1294 bool b;
1295 assert(to!string(b) == "false");
1296 b = true;
1297 assert(to!string(b) == "true");
1298 }
1299
1300 @safe pure unittest
1301 {
1302 // Conversion representing character value with string
1303 alias AllChars =
1304 AliasSeq!( char, const( char), immutable( char),
1305 wchar, const(wchar), immutable(wchar),
1306 dchar, const(dchar), immutable(dchar));
1307 foreach (Char1; AllChars)
1308 {
1309 foreach (Char2; AllChars)
1310 {
1311 Char1 c = 'a';
1312 assert(to!(Char2[])(c)[0] == c);
1313 }
1314 uint x = 4;
1315 assert(to!(Char1[])(x) == "4");
1316 }
1317
1318 string s = "foo";
1319 string s2;
1320 foreach (char c; s)
1321 {
1322 s2 ~= to!string(c);
1323 }
1324 assert(s2 == "foo");
1325 }
1326
1327 @safe pure nothrow unittest
1328 {
1329 import std.exception;
1330 // Conversion representing integer values with string
1331
1332 static foreach (Int; AliasSeq!(ubyte, ushort, uint, ulong))
1333 {
1334 assert(to!string(Int(0)) == "0");
1335 assert(to!string(Int(9)) == "9");
1336 assert(to!string(Int(123)) == "123");
1337 }
1338
1339 static foreach (Int; AliasSeq!(byte, short, int, long))
1340 {
1341 assert(to!string(Int(0)) == "0");
1342 assert(to!string(Int(9)) == "9");
1343 assert(to!string(Int(123)) == "123");
1344 assert(to!string(Int(-0)) == "0");
1345 assert(to!string(Int(-9)) == "-9");
1346 assert(to!string(Int(-123)) == "-123");
1347 assert(to!string(const(Int)(6)) == "6");
1348 }
1349
1350 assert(wtext(int.max) == "2147483647"w);
1351 assert(wtext(int.min) == "-2147483648"w);
1352 assert(to!string(0L) == "0");
1353
1354 assertCTFEable!(
1355 {
1356 assert(to!string(1uL << 62) == "4611686018427387904");
1357 assert(to!string(0x100000000) == "4294967296");
1358 assert(to!string(-138L) == "-138");
1359 });
1360 }
1361
1362 @safe unittest // sprintf issue
1363 {
1364 double[2] a = [ 1.5, 2.5 ];
1365 assert(to!string(a) == "[1.5, 2.5]");
1366 }
1367
1368 @safe unittest
1369 {
1370 // Conversion representing class object with string
1371 class A
1372 {
1373 override string toString() @safe const { return "an A"; }
1374 }
1375 A a;
1376 assert(to!string(a) == "null");
1377 a = new A;
1378 assert(to!string(a) == "an A");
1379
1380 // https://issues.dlang.org/show_bug.cgi?id=7660
1381 class C { override string toString() @safe const { return "C"; } }
1382 struct S { C c; alias c this; }
1383 S s; s.c = new C();
1384 assert(to!string(s) == "C");
1385 }
1386
1387 @safe unittest
1388 {
1389 // Conversion representing struct object with string
1390 struct S1
1391 {
1392 string toString() { return "wyda"; }
1393 }
1394 assert(to!string(S1()) == "wyda");
1395
1396 struct S2
1397 {
1398 int a = 42;
1399 float b = 43.5;
1400 }
1401 S2 s2;
1402 assert(to!string(s2) == "S2(42, 43.5)");
1403
1404 // Test for https://issues.dlang.org/show_bug.cgi?id=8080
1405 struct S8080
1406 {
1407 short[4] data;
1408 alias data this;
1409 string toString() { return "<S>"; }
1410 }
1411 S8080 s8080;
1412 assert(to!string(s8080) == "<S>");
1413 }
1414
1415 @safe unittest
1416 {
1417 // Conversion representing enum value with string
1418 enum EB : bool { a = true }
1419 enum EU : uint { a = 0, b = 1, c = 2 } // base type is unsigned
1420 // base type is signed (https://issues.dlang.org/show_bug.cgi?id=7909)
1421 enum EI : int { a = -1, b = 0, c = 1 }
1422 enum EF : real { a = 1.414, b = 1.732, c = 2.236 }
1423 enum EC : char { a = 'x', b = 'y' }
1424 enum ES : string { a = "aaa", b = "bbb" }
1425
1426 static foreach (E; AliasSeq!(EB, EU, EI, EF, EC, ES))
1427 {
1428 assert(to! string(E.a) == "a"c);
1429 assert(to!wstring(E.a) == "a"w);
1430 assert(to!dstring(E.a) == "a"d);
1431 }
1432
1433 // Test an value not corresponding to an enum member.
1434 auto o = cast(EU) 5;
1435 assert(to! string(o) == "cast(EU)5"c);
1436 assert(to!wstring(o) == "cast(EU)5"w);
1437 assert(to!dstring(o) == "cast(EU)5"d);
1438 }
1439
1440 @safe unittest
1441 {
1442 enum E
1443 {
1444 foo,
1445 doo = foo, // check duplicate switch statements
1446 bar,
1447 }
1448
1449 //Test regression 12494
1450 assert(to!string(E.foo) == "foo");
1451 assert(to!string(E.doo) == "foo");
1452 assert(to!string(E.bar) == "bar");
1453
1454 static foreach (S; AliasSeq!(string, wstring, dstring, const(char[]), const(wchar[]), const(dchar[])))
1455 {{
1456 auto s1 = to!S(E.foo);
1457 auto s2 = to!S(E.foo);
1458 assert(s1 == s2);
1459 // ensure we don't allocate when it's unnecessary
1460 assert(s1 is s2);
1461 }}
1462
1463 static foreach (S; AliasSeq!(char[], wchar[], dchar[]))
1464 {{
1465 auto s1 = to!S(E.foo);
1466 auto s2 = to!S(E.foo);
1467 assert(s1 == s2);
1468 // ensure each mutable array is unique
1469 assert(s1 !is s2);
1470 }}
1471 }
1472
1473 // ditto
1474 @trusted pure private T toImpl(T, S)(S value, uint radix, LetterCase letterCase = LetterCase.upper)
1475 if (isIntegral!S &&
1476 isExactSomeString!T)
1477 in
1478 {
1479 assert(radix >= 2 && radix <= 36, "radix must be in range [2,36]");
1480 }
1481 do
1482 {
1483 alias EEType = Unqual!(ElementEncodingType!T);
1484
1485 T toStringRadixConvert(size_t bufLen)(uint runtimeRadix = 0)
1486 {
1487 Unsigned!(Unqual!S) div = void, mValue = unsigned(value);
1488
1489 size_t index = bufLen;
1490 EEType[bufLen] buffer = void;
1491 char baseChar = letterCase == LetterCase.lower ? 'a' : 'A';
1492 char mod = void;
1493
1494 do
1495 {
1496 div = cast(S)(mValue / runtimeRadix );
1497 mod = cast(ubyte)(mValue % runtimeRadix);
1498 mod += mod < 10 ? '0' : baseChar - 10;
1499 buffer[--index] = cast(char) mod;
1500 mValue = div;
1501 } while (mValue);
1502
1503 return cast(T) buffer[index .. $].dup;
1504 }
1505
1506 import std.array : array;
1507 switch (radix)
1508 {
1509 case 10:
1510 // The (value+0) is so integral promotions happen to the type
1511 return toChars!(10, EEType)(value + 0).array;
1512 case 16:
1513 // The unsigned(unsigned(value)+0) is so unsigned integral promotions happen to the type
1514 if (letterCase == letterCase.upper)
1515 return toChars!(16, EEType, LetterCase.upper)(unsigned(unsigned(value) + 0)).array;
1516 else
1517 return toChars!(16, EEType, LetterCase.lower)(unsigned(unsigned(value) + 0)).array;
1518 case 2:
1519 return toChars!(2, EEType)(unsigned(unsigned(value) + 0)).array;
1520 case 8:
1521 return toChars!(8, EEType)(unsigned(unsigned(value) + 0)).array;
1522
1523 default:
1524 return toStringRadixConvert!(S.sizeof * 6)(radix);
1525 }
1526 }
1527
1528 @safe pure nothrow unittest
1529 {
1530 static foreach (Int; AliasSeq!(uint, ulong))
1531 {
1532 assert(to!string(Int(16), 16) == "10");
1533 assert(to!string(Int(15), 2u) == "1111");
1534 assert(to!string(Int(1), 2u) == "1");
1535 assert(to!string(Int(0x1234AF), 16u) == "1234AF");
1536 assert(to!string(Int(0x1234BCD), 16u, LetterCase.upper) == "1234BCD");
1537 assert(to!string(Int(0x1234AF), 16u, LetterCase.lower) == "1234af");
1538 }
1539
1540 static foreach (Int; AliasSeq!(int, long))
1541 {
1542 assert(to!string(Int(-10), 10u) == "-10");
1543 }
1544
1545 assert(to!string(byte(-10), 16) == "F6");
1546 assert(to!string(long.min) == "-9223372036854775808");
1547 assert(to!string(long.max) == "9223372036854775807");
1548 }
1549
1550 /**
1551 Narrowing numeric-numeric conversions throw when the value does not
1552 fit in the narrower type.
1553 */
1554 private T toImpl(T, S)(S value)
1555 if (!is(S : T) &&
1556 (isNumeric!S || isSomeChar!S || isBoolean!S) &&
1557 (isNumeric!T || isSomeChar!T || isBoolean!T) && !is(T == enum))
1558 {
1559 static if (isFloatingPoint!S && isIntegral!T)
1560 {
1561 import std.math.traits : isNaN;
1562 if (value.isNaN) throw new ConvException("Input was NaN");
1563 }
1564
1565 enum sSmallest = mostNegative!S;
1566 enum tSmallest = mostNegative!T;
1567 static if (sSmallest < 0)
1568 {
1569 // possible underflow converting from a signed
1570 static if (tSmallest == 0)
1571 {
1572 immutable good = value >= 0;
1573 }
1574 else
1575 {
1576 static assert(tSmallest < 0,
1577 "minimum value of T must be smaller than 0");
1578 immutable good = value >= tSmallest;
1579 }
1580 if (!good)
1581 throw new ConvOverflowException("Conversion negative overflow");
1582 }
1583 static if (S.max > T.max)
1584 {
1585 // possible overflow
1586 if (value > T.max)
1587 throw new ConvOverflowException("Conversion positive overflow");
1588 }
1589 return (ref value)@trusted{ return cast(T) value; }(value);
1590 }
1591
1592 @safe pure unittest
1593 {
1594 import std.exception;
1595
1596 dchar a = ' ';
1597 assert(to!char(a) == ' ');
1598 a = 300;
1599 assert(collectException(to!char(a)));
1600
1601 dchar from0 = 'A';
1602 char to0 = to!char(from0);
1603
1604 wchar from1 = 'A';
1605 char to1 = to!char(from1);
1606
1607 char from2 = 'A';
1608 char to2 = to!char(from2);
1609
1610 char from3 = 'A';
1611 wchar to3 = to!wchar(from3);
1612
1613 char from4 = 'A';
1614 dchar to4 = to!dchar(from4);
1615 }
1616
1617 @safe unittest
1618 {
1619 import std.exception;
1620
1621 // Narrowing conversions from enum -> integral should be allowed, but they
1622 // should throw at runtime if the enum value doesn't fit in the target
1623 // type.
1624 enum E1 : ulong { A = 1, B = 1UL << 48, C = 0 }
1625 assert(to!int(E1.A) == 1);
1626 assert(to!bool(E1.A) == true);
1627 assertThrown!ConvOverflowException(to!int(E1.B)); // E1.B overflows int
1628 assertThrown!ConvOverflowException(to!bool(E1.B)); // E1.B overflows bool
1629 assert(to!bool(E1.C) == false);
1630
1631 enum E2 : long { A = -1L << 48, B = -1 << 31, C = 1 << 31 }
1632 assertThrown!ConvOverflowException(to!int(E2.A)); // E2.A overflows int
1633 assertThrown!ConvOverflowException(to!uint(E2.B)); // E2.B overflows uint
1634 assert(to!int(E2.B) == -1 << 31); // but does not overflow int
1635 assert(to!int(E2.C) == 1 << 31); // E2.C does not overflow int
1636
1637 enum E3 : int { A = -1, B = 1, C = 255, D = 0 }
1638 assertThrown!ConvOverflowException(to!ubyte(E3.A));
1639 assertThrown!ConvOverflowException(to!bool(E3.A));
1640 assert(to!byte(E3.A) == -1);
1641 assert(to!byte(E3.B) == 1);
1642 assert(to!ubyte(E3.C) == 255);
1643 assert(to!bool(E3.B) == true);
1644 assertThrown!ConvOverflowException(to!byte(E3.C));
1645 assertThrown!ConvOverflowException(to!bool(E3.C));
1646 assert(to!bool(E3.D) == false);
1647
1648 }
1649
1650 @safe unittest
1651 {
1652 import std.exception;
1653 import std.math.traits : isNaN;
1654
1655 double d = double.nan;
1656 float f = to!float(d);
1657 assert(f.isNaN);
1658 assert(to!double(f).isNaN);
1659 assertThrown!ConvException(to!int(d));
1660 assertThrown!ConvException(to!int(f));
1661 auto ex = collectException(d.to!int);
1662 assert(ex.msg == "Input was NaN");
1663 }
1664
1665 /**
1666 Array-to-array conversion (except when target is a string type)
1667 converts each element in turn by using `to`.
1668 */
1669 private T toImpl(T, S)(scope S value)
1670 if (!is(S : T) &&
1671 !isSomeString!S && isDynamicArray!S &&
1672 !isExactSomeString!T && isArray!T)
1673 {
1674 alias E = typeof(T.init[0]);
1675
1676 static if (isStaticArray!T)
1677 {
1678 import std.exception : enforce;
1679 auto res = to!(E[])(value);
1680 enforce!ConvException(T.length == res.length,
1681 convFormat("Length mismatch when converting to static array: %s vs %s", T.length, res.length));
1682 return res[0 .. T.length];
1683 }
1684 else
1685 {
1686 import std.array : appender;
1687 auto w = appender!(E[])();
1688 w.reserve(value.length);
1689 foreach (ref e; value)
1690 {
1691 w.put(to!E(e));
1692 }
1693 return w.data;
1694 }
1695 }
1696
1697 @safe pure unittest
1698 {
1699 import std.exception;
1700
1701 // array to array conversions
1702 uint[] a = [ 1u, 2, 3 ];
1703 auto b = to!(float[])(a);
1704 assert(b == [ 1.0f, 2, 3 ]);
1705
1706 immutable(int)[3] d = [ 1, 2, 3 ];
1707 b = to!(float[])(d);
1708 assert(b == [ 1.0f, 2, 3 ]);
1709
1710 uint[][] e = [ a, a ];
1711 auto f = to!(float[][])(e);
1712 assert(f[0] == b && f[1] == b);
1713
1714 // Test for https://issues.dlang.org/show_bug.cgi?id=8264
1715 struct Wrap
1716 {
1717 string wrap;
1718 alias wrap this;
1719 }
1720 Wrap[] warr = to!(Wrap[])(["foo", "bar"]); // should work
1721
1722 // https://issues.dlang.org/show_bug.cgi?id=12633
1723 import std.conv : to;
1724 const s2 = ["10", "20"];
1725
1726 immutable int[2] a3 = s2.to!(int[2]);
1727 assert(a3 == [10, 20]);
1728
1729 // verify length mismatches are caught
1730 immutable s4 = [1, 2, 3, 4];
1731 foreach (i; [1, 4])
1732 {
1733 auto ex = collectException(s4[0 .. i].to!(int[2]));
1734 assert(ex && ex.msg == "Length mismatch when converting to static array: 2 vs " ~ [cast(char)(i + '0')],
1735 ex ? ex.msg : "Exception was not thrown!");
1736 }
1737 }
1738
1739 @safe unittest
1740 {
1741 auto b = [ 1.0f, 2, 3 ];
1742
1743 auto c = to!(string[])(b);
1744 assert(c[0] == "1" && c[1] == "2" && c[2] == "3");
1745 }
1746
1747 /**
1748 Associative array to associative array conversion converts each key
1749 and each value in turn.
1750 */
1751 private T toImpl(T, S)(S value)
1752 if (!is(S : T) && isAssociativeArray!S &&
1753 isAssociativeArray!T && !is(T == enum))
1754 {
1755 /* This code is potentially unsafe.
1756 */
1757 alias K2 = KeyType!T;
1758 alias V2 = ValueType!T;
1759
1760 // While we are "building" the AA, we need to unqualify its values, and only re-qualify at the end
1761 Unqual!V2[K2] result;
1762
1763 foreach (k1, v1; value)
1764 {
1765 // Cast values temporarily to Unqual!V2 to store them to result variable
1766 result[to!K2(k1)] = to!(Unqual!V2)(v1);
1767 }
1768 // Cast back to original type
1769 return () @trusted { return cast(T) result; }();
1770 }
1771
1772 @safe unittest
1773 {
1774 // hash to hash conversions
1775 int[string] a;
1776 a["0"] = 1;
1777 a["1"] = 2;
1778 auto b = to!(double[dstring])(a);
1779 assert(b["0"d] == 1 && b["1"d] == 2);
1780 }
1781
1782 // https://issues.dlang.org/show_bug.cgi?id=8705, from doc
1783 @safe unittest
1784 {
1785 import std.exception;
1786 int[string][double[int[]]] a;
1787 auto b = to!(short[wstring][string[double[]]])(a);
1788 a = [null:["hello":int.max]];
1789 assertThrown!ConvOverflowException(to!(short[wstring][string[double[]]])(a));
1790 }
1791 @system unittest // Extra cases for AA with qualifiers conversion
1792 {
1793 int[][int[]] a;// = [[], []];
1794 auto b = to!(immutable(short[])[immutable short[]])(a);
1795
1796 double[dstring][int[long[]]] c;
1797 auto d = to!(immutable(short[immutable wstring])[immutable string[double[]]])(c);
1798 }
1799
1800 @safe unittest
1801 {
1802 import std.algorithm.comparison : equal;
1803 import std.array : byPair;
1804
1805 int[int] a;
1806 assert(a.to!(int[int]) == a);
1807 assert(a.to!(const(int)[int]).byPair.equal(a.byPair));
1808 }
1809
1810 @safe pure unittest
1811 {
1812 static void testIntegralToFloating(Integral, Floating)()
1813 {
1814 Integral a = 42;
1815 auto b = to!Floating(a);
1816 assert(a == b);
1817 assert(a == to!Integral(b));
1818 }
1819 static void testFloatingToIntegral(Floating, Integral)()
1820 {
1821 import std.math.traits : floatTraits, RealFormat;
1822
1823 bool convFails(Source, Target, E)(Source src)
1824 {
1825 try
1826 cast(void) to!Target(src);
1827 catch (E)
1828 return true;
1829 return false;
1830 }
1831
1832 // convert some value
1833 Floating a = 4.2e1;
1834 auto b = to!Integral(a);
1835 assert(is(typeof(b) == Integral) && b == 42);
1836 // convert some negative value (if applicable)
1837 a = -4.2e1;
1838 static if (Integral.min < 0)
1839 {
1840 b = to!Integral(a);
1841 assert(is(typeof(b) == Integral) && b == -42);
1842 }
1843 else
1844 {
1845 // no go for unsigned types
1846 assert(convFails!(Floating, Integral, ConvOverflowException)(a));
1847 }
1848 // convert to the smallest integral value
1849 a = 0.0 + Integral.min;
1850 static if (Integral.min < 0)
1851 {
1852 a = -a; // -Integral.min not representable as an Integral
1853 assert(convFails!(Floating, Integral, ConvOverflowException)(a)
1854 || Floating.sizeof <= Integral.sizeof
1855 || floatTraits!Floating.realFormat == RealFormat.ieeeExtended53);
1856 }
1857 a = 0.0 + Integral.min;
1858 assert(to!Integral(a) == Integral.min);
1859 --a; // no more representable as an Integral
1860 assert(convFails!(Floating, Integral, ConvOverflowException)(a)
1861 || Floating.sizeof <= Integral.sizeof
1862 || floatTraits!Floating.realFormat == RealFormat.ieeeExtended53);
1863 a = 0.0 + Integral.max;
1864 assert(to!Integral(a) == Integral.max
1865 || Floating.sizeof <= Integral.sizeof
1866 || floatTraits!Floating.realFormat == RealFormat.ieeeExtended53);
1867 ++a; // no more representable as an Integral
1868 assert(convFails!(Floating, Integral, ConvOverflowException)(a)
1869 || Floating.sizeof <= Integral.sizeof
1870 || floatTraits!Floating.realFormat == RealFormat.ieeeExtended53);
1871 // convert a value with a fractional part
1872 a = 3.14;
1873 assert(to!Integral(a) == 3);
1874 a = 3.99;
1875 assert(to!Integral(a) == 3);
1876 static if (Integral.min < 0)
1877 {
1878 a = -3.14;
1879 assert(to!Integral(a) == -3);
1880 a = -3.99;
1881 assert(to!Integral(a) == -3);
1882 }
1883 }
1884
1885 alias AllInts = AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong);
1886 alias AllFloats = AliasSeq!(float, double, real);
1887 alias AllNumerics = AliasSeq!(AllInts, AllFloats);
1888 // test with same type
1889 {
1890 foreach (T; AllNumerics)
1891 {
1892 T a = 42;
1893 auto b = to!T(a);
1894 assert(is(typeof(a) == typeof(b)) && a == b);
1895 }
1896 }
1897 // test that floating-point numbers convert properly to largest ints
1898 // see http://oregonstate.edu/~peterseb/mth351/docs/351s2001_fp80x87.html
1899 // look for "largest fp integer with a predecessor"
1900 {
1901 // float
1902 int a = 16_777_215; // 2^24 - 1
1903 assert(to!int(to!float(a)) == a);
1904 assert(to!int(to!float(-a)) == -a);
1905 // double
1906 long b = 9_007_199_254_740_991; // 2^53 - 1
1907 assert(to!long(to!double(b)) == b);
1908 assert(to!long(to!double(-b)) == -b);
1909 // real
1910 static if (real.mant_dig >= 64)
1911 {
1912 ulong c = 18_446_744_073_709_551_615UL; // 2^64 - 1
1913 assert(to!ulong(to!real(c)) == c);
1914 }
1915 }
1916 // test conversions floating => integral
1917 {
1918 foreach (Integral; AllInts)
1919 {
1920 foreach (Floating; AllFloats)
1921 {
1922 testFloatingToIntegral!(Floating, Integral)();
1923 }
1924 }
1925 }
1926 // test conversion integral => floating
1927 {
1928 foreach (Integral; AllInts)
1929 {
1930 foreach (Floating; AllFloats)
1931 {
1932 testIntegralToFloating!(Integral, Floating)();
1933 }
1934 }
1935 }
1936 // test parsing
1937 {
1938 foreach (T; AllNumerics)
1939 {
1940 // from type immutable(char)[2]
1941 auto a = to!T("42");
1942 assert(a == 42);
1943 // from type char[]
1944 char[] s1 = "42".dup;
1945 a = to!T(s1);
1946 assert(a == 42);
1947 // from type char[2]
1948 char[2] s2;
1949 s2[] = "42";
1950 a = to!T(s2);
1951 assert(a == 42);
1952 // from type immutable(wchar)[2]
1953 a = to!T("42"w);
1954 assert(a == 42);
1955 }
1956 }
1957 }
1958
1959 @safe unittest
1960 {
1961 alias AllInts = AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong);
1962 alias AllFloats = AliasSeq!(float, double, real);
1963 alias AllNumerics = AliasSeq!(AllInts, AllFloats);
1964 // test conversions to string
1965 {
1966 foreach (T; AllNumerics)
1967 {
1968 T a = 42;
1969 string s = to!string(a);
1970 assert(s == "42", s);
1971 wstring ws = to!wstring(a);
1972 assert(ws == "42"w, to!string(ws));
1973 dstring ds = to!dstring(a);
1974 assert(ds == "42"d, to!string(ds));
1975 // array test
1976 T[] b = new T[2];
1977 b[0] = 42;
1978 b[1] = 33;
1979 assert(to!string(b) == "[42, 33]");
1980 }
1981 }
1982 // test array to string conversion
1983 foreach (T ; AllNumerics)
1984 {
1985 auto a = [to!T(1), 2, 3];
1986 assert(to!string(a) == "[1, 2, 3]");
1987 }
1988 // test enum to int conversion
1989 enum Testing { Test1, Test2 }
1990 Testing t;
1991 auto a = to!string(t);
1992 assert(a == "Test1");
1993 }
1994
1995
1996 /**
1997 String, or string-like input range, to non-string conversion runs parsing.
1998 $(UL
1999 $(LI When the source is a wide string, it is first converted to a narrow
2000 string and then parsed.)
2001 $(LI When the source is a narrow string, normal text parsing occurs.))
2002 */
2003 private T toImpl(T, S)(S value)
2004 if (isInputRange!S && isSomeChar!(ElementEncodingType!S) &&
2005 !isExactSomeString!T && is(typeof(parse!T(value))) &&
2006 // https://issues.dlang.org/show_bug.cgi?id=20539
2007 !(is(T == enum) && is(typeof(value == OriginalType!T.init)) && !isSomeString!(OriginalType!T)))
2008 {
2009 scope(success)
2010 {
2011 if (!value.empty)
2012 {
2013 throw convError!(S, T)(value);
2014 }
2015 }
2016 return parse!T(value);
2017 }
2018
2019 /// ditto
2020 private T toImpl(T, S)(S value, uint radix)
2021 if (isSomeFiniteCharInputRange!S &&
2022 isIntegral!T && is(typeof(parse!T(value, radix))))
2023 {
2024 scope(success)
2025 {
2026 if (!value.empty)
2027 {
2028 throw convError!(S, T)(value);
2029 }
2030 }
2031 return parse!T(value, radix);
2032 }
2033
2034 @safe pure unittest
2035 {
2036 // https://issues.dlang.org/show_bug.cgi?id=6668
2037 // ensure no collaterals thrown
2038 try { to!uint("-1"); }
2039 catch (ConvException e) { assert(e.next is null); }
2040 }
2041
2042 @safe pure unittest
2043 {
2044 static foreach (Str; AliasSeq!(string, wstring, dstring))
2045 {{
2046 Str a = "123";
2047 assert(to!int(a) == 123);
2048 assert(to!double(a) == 123);
2049 }}
2050
2051 // https://issues.dlang.org/show_bug.cgi?id=6255
2052 auto n = to!int("FF", 16);
2053 assert(n == 255);
2054 }
2055
2056 // https://issues.dlang.org/show_bug.cgi?id=15800
2057 @safe unittest
2058 {
2059 import std.utf : byCodeUnit, byChar, byWchar, byDchar;
2060
2061 assert(to!int(byCodeUnit("10")) == 10);
2062 assert(to!int(byCodeUnit("10"), 10) == 10);
2063 assert(to!int(byCodeUnit("10"w)) == 10);
2064 assert(to!int(byCodeUnit("10"w), 10) == 10);
2065
2066 assert(to!int(byChar("10")) == 10);
2067 assert(to!int(byChar("10"), 10) == 10);
2068 assert(to!int(byWchar("10")) == 10);
2069 assert(to!int(byWchar("10"), 10) == 10);
2070 assert(to!int(byDchar("10")) == 10);
2071 assert(to!int(byDchar("10"), 10) == 10);
2072 }
2073
2074 /**
2075 String, or string-like input range, to char type not directly
2076 supported by parse parses the first dchar of the source.
2077
2078 Returns: the first code point of the input range, converted
2079 to type T.
2080
2081 Throws: ConvException if the input range contains more than
2082 a single code point, or if the code point does not
2083 fit into a code unit of type T.
2084 */
2085 private T toImpl(T, S)(S value)
2086 if (isSomeChar!T && !is(typeof(parse!T(value))) &&
2087 is(typeof(parse!dchar(value))))
2088 {
2089 import std.utf : encode;
2090
2091 immutable dchar codepoint = parse!dchar(value);
2092 if (!value.empty)
2093 throw new ConvException(convFormat("Cannot convert \"%s\" to %s because it " ~
2094 "contains more than a single code point.",
2095 value, T.stringof));
2096 T[dchar.sizeof / T.sizeof] decodedCodepoint;
2097 if (encode(decodedCodepoint, codepoint) != 1)
2098 throw new ConvException(convFormat("First code point '%s' of \"%s\" does not fit into a " ~
2099 "single %s code unit", codepoint, value, T.stringof));
2100 return decodedCodepoint[0];
2101 }
2102
2103 @safe pure unittest
2104 {
2105 import std.exception : assertThrown;
2106
2107 assert(toImpl!wchar("a") == 'a');
2108
2109 assert(toImpl!char("a"d) == 'a');
2110 assert(toImpl!char("a"w) == 'a');
2111 assert(toImpl!wchar("a"d) == 'a');
2112
2113 assertThrown!ConvException(toImpl!wchar("ab"));
2114 assertThrown!ConvException(toImpl!char("😃"d));
2115 }
2116
2117 /**
2118 Convert a value that is implicitly convertible to the enum base type
2119 into an Enum value. If the value does not match any enum member values
2120 a ConvException is thrown.
2121 Enums with floating-point or string base types are not supported.
2122 */
2123 private T toImpl(T, S)(S value)
2124 if (is(T == enum) && !is(S == enum)
2125 && is(typeof(value == OriginalType!T.init))
2126 && !isFloatingPoint!(OriginalType!T) && !isSomeString!(OriginalType!T))
2127 {
2128 foreach (Member; EnumMembers!T)
2129 {
2130 if (Member == value)
2131 return Member;
2132 }
2133 throw new ConvException(convFormat("Value (%s) does not match any member value of enum '%s'", value, T.stringof));
2134 }
2135
2136 @safe pure unittest
2137 {
2138 import std.exception;
2139 enum En8143 : int { A = 10, B = 20, C = 30, D = 20 }
2140 enum En8143[][] m3 = to!(En8143[][])([[10, 30], [30, 10]]);
2141 static assert(m3 == [[En8143.A, En8143.C], [En8143.C, En8143.A]]);
2142
2143 En8143 en1 = to!En8143(10);
2144 assert(en1 == En8143.A);
2145 assertThrown!ConvException(to!En8143(5)); // matches none
2146 En8143[][] m1 = to!(En8143[][])([[10, 30], [30, 10]]);
2147 assert(m1 == [[En8143.A, En8143.C], [En8143.C, En8143.A]]);
2148 }
2149
2150 // https://issues.dlang.org/show_bug.cgi?id=20539
2151 @safe pure unittest
2152 {
2153 import std.exception : assertNotThrown;
2154
2155 // To test that the bug is fixed it is required that the struct is static,
2156 // otherwise, the frame pointer makes the test pass even if the bug is not
2157 // fixed.
2158
2159 static struct A
2160 {
2161 auto opEquals(U)(U)
2162 {
2163 return true;
2164 }
2165 }
2166
2167 enum ColorA
2168 {
2169 red = A()
2170 }
2171
2172 assertNotThrown("xxx".to!ColorA);
2173
2174 // This is a guard for the future.
2175
2176 struct B
2177 {
2178 auto opEquals(U)(U)
2179 {
2180 return true;
2181 }
2182 }
2183
2184 enum ColorB
2185 {
2186 red = B()
2187 }
2188
2189 assertNotThrown("xxx".to!ColorB);
2190 }
2191
2192 /***************************************************************
2193 Rounded conversion from floating point to integral.
2194
2195 Rounded conversions do not work with non-integral target types.
2196 */
2197
2198 template roundTo(Target)
2199 {
2200 Target roundTo(Source)(Source value)
2201 {
2202 import core.math : abs = fabs;
2203 import std.math.exponential : log2;
2204 import std.math.rounding : trunc;
2205
2206 static assert(isFloatingPoint!Source);
2207 static assert(isIntegral!Target);
2208
2209 // If value >= 2 ^^ (real.mant_dig - 1), the number is an integer
2210 // and adding 0.5 won't work, but we allready know, that we do
2211 // not have to round anything.
2212 if (log2(abs(value)) >= real.mant_dig - 1)
2213 return to!Target(value);
2214
2215 return to!Target(trunc(value + (value < 0 ? -0.5L : 0.5L)));
2216 }
2217 }
2218
2219 ///
2220 @safe unittest
2221 {
2222 assert(roundTo!int(3.14) == 3);
2223 assert(roundTo!int(3.49) == 3);
2224 assert(roundTo!int(3.5) == 4);
2225 assert(roundTo!int(3.999) == 4);
2226 assert(roundTo!int(-3.14) == -3);
2227 assert(roundTo!int(-3.49) == -3);
2228 assert(roundTo!int(-3.5) == -4);
2229 assert(roundTo!int(-3.999) == -4);
2230 assert(roundTo!(const int)(to!(const double)(-3.999)) == -4);
2231 }
2232
2233 @safe unittest
2234 {
2235 import std.exception;
2236 // boundary values
2237 static foreach (Int; AliasSeq!(byte, ubyte, short, ushort, int, uint))
2238 {
2239 assert(roundTo!Int(Int.min - 0.4L) == Int.min);
2240 assert(roundTo!Int(Int.max + 0.4L) == Int.max);
2241 assertThrown!ConvOverflowException(roundTo!Int(Int.min - 0.5L));
2242 assertThrown!ConvOverflowException(roundTo!Int(Int.max + 0.5L));
2243 }
2244 }
2245
2246 @safe unittest
2247 {
2248 import std.exception;
2249 assertThrown!ConvException(roundTo!int(float.init));
2250 auto ex = collectException(roundTo!int(float.init));
2251 assert(ex.msg == "Input was NaN");
2252 }
2253
2254 // https://issues.dlang.org/show_bug.cgi?id=5232
2255 @safe pure unittest
2256 {
2257 static if (real.mant_dig >= 64)
2258 ulong maxOdd = ulong.max;
2259 else
2260 ulong maxOdd = (1UL << real.mant_dig) - 1;
2261
2262 real r1 = maxOdd;
2263 assert(roundTo!ulong(r1) == maxOdd);
2264
2265 real r2 = maxOdd - 1;
2266 assert(roundTo!ulong(r2) == maxOdd - 1);
2267
2268 real r3 = maxOdd / 2;
2269 assert(roundTo!ulong(r3) == maxOdd / 2);
2270
2271 real r4 = maxOdd / 2 + 1;
2272 assert(roundTo!ulong(r4) == maxOdd / 2 + 1);
2273
2274 // this is only an issue on computers where real == double
2275 long l = -((1L << double.mant_dig) - 1);
2276 double r5 = l;
2277 assert(roundTo!long(r5) == l);
2278 }
2279
2280 /**
2281 $(PANEL
2282 The `parse` family of functions works quite like the $(LREF to)
2283 family, except that:
2284 $(OL
2285 $(LI It only works with character ranges as input.)
2286 $(LI It takes the input by reference. This means that rvalues (such
2287 as string literals) are not accepted: use `to` instead.)
2288 $(LI It advances the input to the position following the conversion.)
2289 $(LI It does not throw if it could not convert the entire input.))
2290 )
2291
2292 This overload parses a `bool` from a character input range.
2293
2294 Params:
2295 Target = the boolean type to convert to
2296 source = the lvalue of an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
2297 doCount = the flag for deciding to report the number of consumed characters
2298
2299 Returns:
2300 $(UL
2301 $(LI A `bool` if `doCount` is set to `No.doCount`)
2302 $(LI A `tuple` containing a `bool` and a `size_t` if `doCount` is set to `Yes.doCount`))
2303
2304 Throws:
2305 A $(LREF ConvException) if the range does not represent a `bool`.
2306
2307 Note:
2308 All character input range conversions using $(LREF to) are forwarded
2309 to `parse` and do not require lvalues.
2310 */
2311 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source)
2312 if (is(immutable Target == immutable bool) &&
2313 isInputRange!Source &&
2314 isSomeChar!(ElementType!Source))
2315 {
2316 import std.ascii : toLower;
2317
2318 static if (isNarrowString!Source)
2319 {
2320 import std.string : representation;
2321 auto s = source.representation;
2322 }
2323 else
2324 {
2325 alias s = source;
2326 }
2327
2328 if (!s.empty)
2329 {
2330 auto c1 = toLower(s.front);
2331 bool result = c1 == 't';
2332 if (result || c1 == 'f')
2333 {
2334 s.popFront();
2335 foreach (c; result ? "rue" : "alse")
2336 {
2337 if (s.empty || toLower(s.front) != c)
2338 goto Lerr;
2339 s.popFront();
2340 }
2341
2342 static if (isNarrowString!Source)
2343 source = cast(Source) s;
2344
2345 static if (doCount)
2346 {
2347 if (result)
2348 return tuple!("data", "count")(result, 4);
2349 return tuple!("data", "count")(result, 5);
2350 }
2351 else
2352 {
2353 return result;
2354 }
2355 }
2356 }
2357 Lerr:
2358 throw parseError("bool should be case-insensitive 'true' or 'false'");
2359 }
2360
2361 ///
2362 @safe unittest
2363 {
2364 import std.typecons : Flag, Yes, No;
2365 auto s = "true";
2366 bool b = parse!bool(s);
2367 assert(b);
2368 auto s2 = "true";
2369 bool b2 = parse!(bool, string, No.doCount)(s2);
2370 assert(b2);
2371 auto s3 = "true";
2372 auto b3 = parse!(bool, string, Yes.doCount)(s3);
2373 assert(b3.data && b3.count == 4);
2374 auto s4 = "falSE";
2375 auto b4 = parse!(bool, string, Yes.doCount)(s4);
2376 assert(!b4.data && b4.count == 5);
2377 }
2378
2379 @safe unittest
2380 {
2381 import std.algorithm.comparison : equal;
2382 import std.exception;
2383 struct InputString
2384 {
2385 string _s;
2386 @property auto front() { return _s.front; }
2387 @property bool empty() { return _s.empty; }
2388 void popFront() { _s.popFront(); }
2389 }
2390
2391 auto s = InputString("trueFALSETrueFalsetRUEfALSE");
2392 assert(parse!bool(s) == true);
2393 assert(s.equal("FALSETrueFalsetRUEfALSE"));
2394 assert(parse!bool(s) == false);
2395 assert(s.equal("TrueFalsetRUEfALSE"));
2396 assert(parse!bool(s) == true);
2397 assert(s.equal("FalsetRUEfALSE"));
2398 assert(parse!bool(s) == false);
2399 assert(s.equal("tRUEfALSE"));
2400 assert(parse!bool(s) == true);
2401 assert(s.equal("fALSE"));
2402 assert(parse!bool(s) == false);
2403 assert(s.empty);
2404
2405 foreach (ss; ["tfalse", "ftrue", "t", "f", "tru", "fals", ""])
2406 {
2407 s = InputString(ss);
2408 assertThrown!ConvException(parse!bool(s));
2409 }
2410 }
2411
2412 /**
2413 Parses an integer from a character $(REF_ALTTEXT input range, isInputRange, std,range,primitives).
2414
2415 Params:
2416 Target = the integral type to convert to
2417 s = the lvalue of an input range
2418 doCount = the flag for deciding to report the number of consumed characters
2419
2420 Returns:
2421 $(UL
2422 $(LI A number of type `Target` if `doCount` is set to `No.doCount`)
2423 $(LI A `tuple` containing a number of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`))
2424
2425 Throws:
2426 A $(LREF ConvException) If an overflow occurred during conversion or
2427 if no character of the input was meaningfully converted.
2428 */
2429 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref scope Source s)
2430 if (isIntegral!Target && !is(Target == enum) &&
2431 isSomeChar!(ElementType!Source))
2432 {
2433 static if (Target.sizeof < int.sizeof)
2434 {
2435 // smaller types are handled like integers
2436 auto v = .parse!(Select!(Target.min < 0, int, uint), Source, Yes.doCount)(s);
2437 auto result = (() @trusted => cast (Target) v.data)();
2438 if (result == v.data)
2439 {
2440 static if (doCount)
2441 {
2442 return tuple!("data", "count")(result, v.count);
2443 }
2444 else
2445 {
2446 return result;
2447 }
2448 }
2449 throw new ConvOverflowException("Overflow in integral conversion");
2450 }
2451 else
2452 {
2453 // int or larger types
2454
2455 static if (Target.min < 0)
2456 bool sign = false;
2457 else
2458 enum bool sign = false;
2459
2460 enum char maxLastDigit = Target.min < 0 ? 7 : 5;
2461 uint c;
2462
2463 static if (isNarrowString!Source)
2464 {
2465 import std.string : representation;
2466 auto source = s.representation;
2467 }
2468 else
2469 {
2470 alias source = s;
2471 }
2472
2473 size_t count = 0;
2474
2475 if (source.empty)
2476 goto Lerr;
2477
2478 c = source.front;
2479
2480 static if (Target.min < 0)
2481 {
2482 switch (c)
2483 {
2484 case '-':
2485 sign = true;
2486 goto case '+';
2487 case '+':
2488 ++count;
2489 source.popFront();
2490
2491 if (source.empty)
2492 goto Lerr;
2493
2494 c = source.front;
2495
2496 break;
2497
2498 default:
2499 break;
2500 }
2501 }
2502 c -= '0';
2503 if (c <= 9)
2504 {
2505 Target v = cast(Target) c;
2506
2507 ++count;
2508 source.popFront();
2509
2510 while (!source.empty)
2511 {
2512 c = cast(typeof(c)) (source.front - '0');
2513
2514 if (c > 9)
2515 break;
2516
2517 if (v >= 0 && (v < Target.max/10 ||
2518 (v == Target.max/10 && c <= maxLastDigit + sign)))
2519 {
2520 // Note: `v` can become negative here in case of parsing
2521 // the most negative value:
2522 v = cast(Target) (v * 10 + c);
2523 ++count;
2524 source.popFront();
2525 }
2526 else
2527 throw new ConvOverflowException("Overflow in integral conversion");
2528 }
2529
2530 if (sign)
2531 v = -v;
2532
2533 static if (isNarrowString!Source)
2534 s = s[$-source.length..$];
2535
2536 static if (doCount)
2537 {
2538 return tuple!("data", "count")(v, count);
2539 }
2540 else
2541 {
2542 return v;
2543 }
2544 }
2545 Lerr:
2546 static if (isNarrowString!Source)
2547 throw convError!(Source, Target)(cast(Source) source);
2548 else
2549 throw convError!(Source, Target)(source);
2550 }
2551 }
2552
2553 ///
2554 @safe pure unittest
2555 {
2556 import std.typecons : Flag, Yes, No;
2557 string s = "123";
2558 auto a = parse!int(s);
2559 assert(a == 123);
2560
2561 string s1 = "123";
2562 auto a1 = parse!(int, string, Yes.doCount)(s1);
2563 assert(a1.data == 123 && a1.count == 3);
2564 }
2565
2566 ///
2567 @safe pure unittest
2568 {
2569 import std.string : tr;
2570 import std.typecons : Flag, Yes, No;
2571 string test = "123 \t 76.14";
2572 auto a = parse!uint(test);
2573 assert(a == 123);
2574 assert(test == " \t 76.14"); // parse bumps string
2575 test = tr(test, " \t\n\r", "", "d"); // skip ws
2576 assert(test == "76.14");
2577 auto b = parse!double(test);
2578 assert(b == 76.14);
2579 assert(test == "");
2580
2581 string test2 = "123 \t 76.14";
2582 auto a2 = parse!(uint, string, Yes.doCount)(test2);
2583 assert(a2.data == 123 && a2.count == 3);
2584 assert(test2 == " \t 76.14");// parse bumps string
2585 test2 = tr(test2, " \t\n\r", "", "d"); // skip ws
2586 assert(test2 == "76.14");
2587 auto b2 = parse!(double, string, Yes.doCount)(test2);
2588 assert(b2.data == 76.14 && b2.count == 5);
2589 assert(test2 == "");
2590
2591 }
2592
2593 @safe pure unittest
2594 {
2595 static foreach (Int; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
2596 {
2597 {
2598 assert(to!Int("0") == 0);
2599
2600 static if (isSigned!Int)
2601 {
2602 assert(to!Int("+0") == 0);
2603 assert(to!Int("-0") == 0);
2604 }
2605 }
2606
2607 static if (Int.sizeof >= byte.sizeof)
2608 {
2609 assert(to!Int("6") == 6);
2610 assert(to!Int("23") == 23);
2611 assert(to!Int("68") == 68);
2612 assert(to!Int("127") == 0x7F);
2613
2614 static if (isUnsigned!Int)
2615 {
2616 assert(to!Int("255") == 0xFF);
2617 }
2618 static if (isSigned!Int)
2619 {
2620 assert(to!Int("+6") == 6);
2621 assert(to!Int("+23") == 23);
2622 assert(to!Int("+68") == 68);
2623 assert(to!Int("+127") == 0x7F);
2624
2625 assert(to!Int("-6") == -6);
2626 assert(to!Int("-23") == -23);
2627 assert(to!Int("-68") == -68);
2628 assert(to!Int("-128") == -128);
2629 }
2630 }
2631
2632 static if (Int.sizeof >= short.sizeof)
2633 {
2634 assert(to!Int("468") == 468);
2635 assert(to!Int("32767") == 0x7FFF);
2636
2637 static if (isUnsigned!Int)
2638 {
2639 assert(to!Int("65535") == 0xFFFF);
2640 }
2641 static if (isSigned!Int)
2642 {
2643 assert(to!Int("+468") == 468);
2644 assert(to!Int("+32767") == 0x7FFF);
2645
2646 assert(to!Int("-468") == -468);
2647 assert(to!Int("-32768") == -32768);
2648 }
2649 }
2650
2651 static if (Int.sizeof >= int.sizeof)
2652 {
2653 assert(to!Int("2147483647") == 0x7FFFFFFF);
2654
2655 static if (isUnsigned!Int)
2656 {
2657 assert(to!Int("4294967295") == 0xFFFFFFFF);
2658 }
2659
2660 static if (isSigned!Int)
2661 {
2662 assert(to!Int("+2147483647") == 0x7FFFFFFF);
2663
2664 assert(to!Int("-2147483648") == -2147483648);
2665 }
2666 }
2667
2668 static if (Int.sizeof >= long.sizeof)
2669 {
2670 assert(to!Int("9223372036854775807") == 0x7FFFFFFFFFFFFFFF);
2671
2672 static if (isUnsigned!Int)
2673 {
2674 assert(to!Int("18446744073709551615") == 0xFFFFFFFFFFFFFFFF);
2675 }
2676
2677 static if (isSigned!Int)
2678 {
2679 assert(to!Int("+9223372036854775807") == 0x7FFFFFFFFFFFFFFF);
2680
2681 assert(to!Int("-9223372036854775808") == 0x8000000000000000);
2682 }
2683 }
2684 }
2685 }
2686
2687 @safe pure unittest
2688 {
2689 import std.exception;
2690
2691 immutable string[] errors =
2692 [
2693 "",
2694 "-",
2695 "+",
2696 "-+",
2697 " ",
2698 " 0",
2699 "0 ",
2700 "- 0",
2701 "1-",
2702 "xx",
2703 "123h",
2704 "-+1",
2705 "--1",
2706 "+-1",
2707 "++1",
2708 ];
2709
2710 immutable string[] unsignedErrors =
2711 [
2712 "+5",
2713 "-78",
2714 ];
2715
2716 // parsing error check
2717 static foreach (Int; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
2718 {
2719 foreach (j, s; errors)
2720 assertThrown!ConvException(to!Int(s));
2721
2722 // parse!SomeUnsigned cannot parse head sign.
2723 static if (isUnsigned!Int)
2724 {
2725 foreach (j, s; unsignedErrors)
2726 assertThrown!ConvException(to!Int(s));
2727 }
2728 }
2729
2730 immutable string[] positiveOverflowErrors =
2731 [
2732 "128", // > byte.max
2733 "256", // > ubyte.max
2734 "32768", // > short.max
2735 "65536", // > ushort.max
2736 "2147483648", // > int.max
2737 "4294967296", // > uint.max
2738 "9223372036854775808", // > long.max
2739 "18446744073709551616", // > ulong.max
2740 ];
2741 // positive overflow check
2742 static foreach (i, Int; AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong))
2743 {
2744 foreach (j, s; positiveOverflowErrors[i..$])
2745 assertThrown!ConvOverflowException(to!Int(s));
2746 }
2747
2748 immutable string[] negativeOverflowErrors =
2749 [
2750 "-129", // < byte.min
2751 "-32769", // < short.min
2752 "-2147483649", // < int.min
2753 "-9223372036854775809", // < long.min
2754 ];
2755 // negative overflow check
2756 static foreach (i, Int; AliasSeq!(byte, short, int, long))
2757 {
2758 foreach (j, s; negativeOverflowErrors[i..$])
2759 assertThrown!ConvOverflowException(to!Int(s));
2760 }
2761 }
2762
2763 @safe pure unittest
2764 {
2765 void checkErrMsg(string input, dchar charInMsg, dchar charNotInMsg)
2766 {
2767 try
2768 {
2769 int x = input.to!int();
2770 assert(false, "Invalid conversion did not throw");
2771 }
2772 catch (ConvException e)
2773 {
2774 // Ensure error message contains failing character, not the character
2775 // beyond.
2776 import std.algorithm.searching : canFind;
2777 assert( e.msg.canFind(charInMsg) &&
2778 !e.msg.canFind(charNotInMsg));
2779 }
2780 catch (Exception e)
2781 {
2782 assert(false, "Did not throw ConvException");
2783 }
2784 }
2785 checkErrMsg("@$", '@', '$');
2786 checkErrMsg("@$123", '@', '$');
2787 checkErrMsg("1@$23", '@', '$');
2788 checkErrMsg("1@$", '@', '$');
2789 checkErrMsg("1@$2", '@', '$');
2790 checkErrMsg("12@$", '@', '$');
2791 }
2792
2793 @safe pure unittest
2794 {
2795 import std.exception;
2796 assertCTFEable!({ string s = "1234abc"; assert(parse! int(s) == 1234 && s == "abc"); });
2797 assertCTFEable!({ string s = "-1234abc"; assert(parse! int(s) == -1234 && s == "abc"); });
2798 assertCTFEable!({ string s = "1234abc"; assert(parse!uint(s) == 1234 && s == "abc"); });
2799
2800 assertCTFEable!({ string s = "1234abc"; assert(parse!( int, string, Yes.doCount)(s) ==
2801 tuple( 1234, 4) && s == "abc"); });
2802 assertCTFEable!({ string s = "-1234abc"; assert(parse!( int, string, Yes.doCount)(s) ==
2803 tuple(-1234, 5) && s == "abc"); });
2804 assertCTFEable!({ string s = "1234abc"; assert(parse!(uint, string, Yes.doCount)(s) ==
2805 tuple( 1234 ,4) && s == "abc"); });
2806 }
2807
2808 // https://issues.dlang.org/show_bug.cgi?id=13931
2809 @safe pure unittest
2810 {
2811 import std.exception;
2812
2813 assertThrown!ConvOverflowException("-21474836480".to!int());
2814 assertThrown!ConvOverflowException("-92233720368547758080".to!long());
2815 }
2816
2817 // https://issues.dlang.org/show_bug.cgi?id=14396
2818 @safe pure unittest
2819 {
2820 struct StrInputRange
2821 {
2822 this (string s) { str = s; }
2823 char front() const @property { return str[front_index]; }
2824 char popFront() { return str[front_index++]; }
2825 bool empty() const @property { return str.length <= front_index; }
2826 string str;
2827 size_t front_index = 0;
2828 }
2829 auto input = StrInputRange("777");
2830 assert(parse!int(input) == 777);
2831
2832 auto input2 = StrInputRange("777");
2833 assert(parse!(int, StrInputRange, Yes.doCount)(input2) == tuple(777, 3));
2834 }
2835
2836 // https://issues.dlang.org/show_bug.cgi?id=9621
2837 @safe pure unittest
2838 {
2839 string s1 = "[ \"\\141\", \"\\0\", \"\\41\", \"\\418\" ]";
2840 assert(parse!(string[])(s1) == ["a", "\0", "!", "!8"]);
2841
2842 s1 = "[ \"\\141\", \"\\0\", \"\\41\", \"\\418\" ]";
2843 auto len = s1.length;
2844 assert(parse!(string[], string, Yes.doCount)(s1) == tuple(["a", "\0", "!", "!8"], len));
2845 }
2846
2847 /// ditto
2848 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source, uint radix)
2849 if (isIntegral!Target && !is(Target == enum) &&
2850 isSomeChar!(ElementType!Source))
2851 in
2852 {
2853 assert(radix >= 2 && radix <= 36, "radix must be in range [2,36]");
2854 }
2855 do
2856 {
2857 import core.checkedint : mulu, addu;
2858 import std.exception : enforce;
2859
2860 if (radix == 10)
2861 {
2862 return parse!(Target, Source, doCount)(source);
2863 }
2864
2865 enforce!ConvException(!source.empty, "s must not be empty in integral parse");
2866
2867 immutable uint beyond = (radix < 10 ? '0' : 'a'-10) + radix;
2868 Target v = 0;
2869
2870 static if (isNarrowString!Source)
2871 {
2872 import std.string : representation;
2873 scope s = source.representation;
2874 }
2875 else
2876 {
2877 alias s = source;
2878 }
2879
2880 size_t count = 0;
2881 auto found = false;
2882 do
2883 {
2884 uint c = s.front;
2885 if (c < '0')
2886 break;
2887 if (radix < 10)
2888 {
2889 if (c >= beyond)
2890 break;
2891 }
2892 else
2893 {
2894 if (c > '9')
2895 {
2896 c |= 0x20;//poorman's tolower
2897 if (c < 'a' || c >= beyond)
2898 break;
2899 c -= 'a'-10-'0';
2900 }
2901 }
2902
2903 bool overflow = false;
2904 auto nextv = v.mulu(radix, overflow).addu(c - '0', overflow);
2905 enforce!ConvOverflowException(!overflow && nextv <= Target.max, "Overflow in integral conversion");
2906 v = cast(Target) nextv;
2907 ++count;
2908 s.popFront();
2909 found = true;
2910 } while (!s.empty);
2911
2912 if (!found)
2913 {
2914 static if (isNarrowString!Source)
2915 throw convError!(Source, Target)(cast(Source) source);
2916 else
2917 throw convError!(Source, Target)(source);
2918 }
2919
2920 static if (isNarrowString!Source)
2921 source = source[$ - s.length .. $];
2922
2923 static if (doCount)
2924 {
2925 return tuple!("data", "count")(v, count);
2926 }
2927 else
2928 {
2929 return v;
2930 }
2931 }
2932
2933 @safe pure unittest
2934 {
2935 string s; // parse doesn't accept rvalues
2936 foreach (i; 2 .. 37)
2937 {
2938 assert(parse!int(s = "0", i) == 0);
2939 assert(parse!int(s = "1", i) == 1);
2940 assert(parse!byte(s = "10", i) == i);
2941 assert(parse!(int, string, Yes.doCount)(s = "0", i) == tuple(0, 1));
2942 assert(parse!(int, string, Yes.doCount)(s = "1", i) == tuple(1, 1));
2943 assert(parse!(byte, string, Yes.doCount)(s = "10", i) == tuple(i, 2));
2944 }
2945
2946 assert(parse!int(s = "0011001101101", 2) == 0b0011001101101);
2947 assert(parse!int(s = "765", 8) == octal!765);
2948 assert(parse!int(s = "000135", 8) == octal!"135");
2949 assert(parse!int(s = "fCDe", 16) == 0xfcde);
2950
2951 // https://issues.dlang.org/show_bug.cgi?id=6609
2952 assert(parse!int(s = "-42", 10) == -42);
2953
2954 assert(parse!ubyte(s = "ff", 16) == 0xFF);
2955 }
2956
2957 // https://issues.dlang.org/show_bug.cgi?id=7302
2958 @safe pure unittest
2959 {
2960 import std.range : cycle;
2961 auto r = cycle("2A!");
2962 auto u = parse!uint(r, 16);
2963 assert(u == 42);
2964 assert(r.front == '!');
2965
2966 auto r2 = cycle("2A!");
2967 auto u2 = parse!(uint, typeof(r2), Yes.doCount)(r2, 16);
2968 assert(u2.data == 42 && u2.count == 2);
2969 assert(r2.front == '!');
2970 }
2971
2972 // https://issues.dlang.org/show_bug.cgi?id=13163
2973 @safe pure unittest
2974 {
2975 import std.exception;
2976 foreach (s; ["fff", "123"])
2977 assertThrown!ConvOverflowException(s.parse!ubyte(16));
2978 }
2979
2980 // https://issues.dlang.org/show_bug.cgi?id=17282
2981 @safe pure unittest
2982 {
2983 auto str = "0=\x00\x02\x55\x40&\xff\xf0\n\x00\x04\x55\x40\xff\xf0~4+10\n";
2984 assert(parse!uint(str) == 0);
2985
2986 str = "0=\x00\x02\x55\x40&\xff\xf0\n\x00\x04\x55\x40\xff\xf0~4+10\n";
2987 assert(parse!(uint, string, Yes.doCount)(str) == tuple(0, 1));
2988 }
2989
2990 // https://issues.dlang.org/show_bug.cgi?id=18248
2991 @safe pure unittest
2992 {
2993 import std.exception : assertThrown;
2994
2995 auto str = ";";
2996 assertThrown(str.parse!uint(16));
2997 assertThrown(str.parse!(uint, string, Yes.doCount)(16));
2998 }
2999
3000 /**
3001 * Parses an `enum` type from a string representing an enum member name.
3002 *
3003 * Params:
3004 * Target = the `enum` type to convert to
3005 * s = the lvalue of the range to _parse
3006 * doCount = the flag for deciding to report the number of consumed characters
3007 *
3008 * Returns:
3009 $(UL
3010 * $(LI An `enum` of type `Target` if `doCount` is set to `No.doCount`)
3011 * $(LI A `tuple` containing an `enum` of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`))
3012 *
3013 * Throws:
3014 * A $(LREF ConvException) if type `Target` does not have a member
3015 * represented by `s`.
3016 */
3017 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
3018 if (is(Target == enum) && isSomeString!Source && !is(Source == enum))
3019 {
3020 import std.algorithm.searching : startsWith;
3021 import std.traits : Unqual, EnumMembers;
3022
3023 Unqual!Target result;
3024 size_t longest_match = 0;
3025
3026 foreach (i, e; EnumMembers!Target)
3027 {
3028 auto ident = __traits(allMembers, Target)[i];
3029 if (longest_match < ident.length && s.startsWith(ident))
3030 {
3031 result = e;
3032 longest_match = ident.length ;
3033 }
3034 }
3035
3036 if (longest_match > 0)
3037 {
3038 s = s[longest_match .. $];
3039 static if (doCount)
3040 {
3041 return tuple!("data", "count")(result, longest_match);
3042 }
3043 else
3044 {
3045 return result;
3046 }
3047 }
3048
3049 throw new ConvException(
3050 Target.stringof ~ " does not have a member named '"
3051 ~ to!string(s) ~ "'");
3052 }
3053
3054 ///
3055 @safe unittest
3056 {
3057 import std.typecons : Flag, Yes, No, tuple;
3058 enum EnumType : bool { a = true, b = false, c = a }
3059
3060 auto str = "a";
3061 assert(parse!EnumType(str) == EnumType.a);
3062 auto str2 = "a";
3063 assert(parse!(EnumType, string, No.doCount)(str2) == EnumType.a);
3064 auto str3 = "a";
3065 assert(parse!(EnumType, string, Yes.doCount)(str3) == tuple(EnumType.a, 1));
3066
3067 }
3068
3069 @safe unittest
3070 {
3071 import std.exception;
3072
3073 enum EB : bool { a = true, b = false, c = a }
3074 enum EU { a, b, c }
3075 enum EI { a = -1, b = 0, c = 1 }
3076 enum EF : real { a = 1.414, b = 1.732, c = 2.236 }
3077 enum EC : char { a = 'a', b = 'b', c = 'c' }
3078 enum ES : string { a = "aaa", b = "bbb", c = "ccc" }
3079
3080 static foreach (E; AliasSeq!(EB, EU, EI, EF, EC, ES))
3081 {
3082 assert(to!E("a"c) == E.a);
3083 assert(to!E("b"w) == E.b);
3084 assert(to!E("c"d) == E.c);
3085
3086 assert(to!(const E)("a") == E.a);
3087 assert(to!(immutable E)("a") == E.a);
3088 assert(to!(shared E)("a") == E.a);
3089
3090 assertThrown!ConvException(to!E("d"));
3091 }
3092 }
3093
3094 // https://issues.dlang.org/show_bug.cgi?id=4744
3095 @safe pure unittest
3096 {
3097 enum A { member1, member11, member111 }
3098 assert(to!A("member1" ) == A.member1 );
3099 assert(to!A("member11" ) == A.member11 );
3100 assert(to!A("member111") == A.member111);
3101 auto s = "member1111";
3102 assert(parse!A(s) == A.member111 && s == "1");
3103 auto s2 = "member1111";
3104 assert(parse!(A, string, No.doCount)(s2) == A.member111 && s2 == "1");
3105 auto s3 = "member1111";
3106 assert(parse!(A, string, Yes.doCount)(s3) == tuple(A.member111, 9) && s3 == "1");
3107 }
3108
3109 /**
3110 * Parses a floating point number from a character range.
3111 *
3112 * Params:
3113 * Target = a floating point type
3114 * source = the lvalue of the range to _parse
3115 * doCount = the flag for deciding to report the number of consumed characters
3116 *
3117 * Returns:
3118 $(UL
3119 * $(LI A floating point number of type `Target` if `doCount` is set to `No.doCount`)
3120 * $(LI A `tuple` containing a floating point number of·type `Target` and a `size_t`
3121 * if `doCount` is set to `Yes.doCount`))
3122 *
3123 * Throws:
3124 * A $(LREF ConvException) if `source` is empty, if no number could be
3125 * parsed, or if an overflow occurred.
3126 */
3127 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source source)
3128 if (isFloatingPoint!Target && !is(Target == enum) &&
3129 isInputRange!Source && isSomeChar!(ElementType!Source) && !is(Source == enum))
3130 {
3131 import std.ascii : isDigit, isAlpha, toLower, toUpper, isHexDigit;
3132 import std.exception : enforce;
3133
3134 static if (isNarrowString!Source)
3135 {
3136 import std.string : representation;
3137 scope p = source.representation;
3138 }
3139 else
3140 {
3141 alias p = source;
3142 }
3143
3144 void advanceSource()
3145 {
3146 static if (isNarrowString!Source)
3147 source = source[$ - p.length .. $];
3148 }
3149
3150 static immutable real[14] negtab =
3151 [ 1e-4096L,1e-2048L,1e-1024L,1e-512L,1e-256L,1e-128L,1e-64L,1e-32L,
3152 1e-16L,1e-8L,1e-4L,1e-2L,1e-1L,1.0L ];
3153 static immutable real[13] postab =
3154 [ 1e+4096L,1e+2048L,1e+1024L,1e+512L,1e+256L,1e+128L,1e+64L,1e+32L,
3155 1e+16L,1e+8L,1e+4L,1e+2L,1e+1L ];
3156
3157 ConvException bailOut()(string msg = null, string fn = __FILE__, size_t ln = __LINE__)
3158 {
3159 if (msg == null)
3160 msg = "Floating point conversion error";
3161 return new ConvException(text(msg, " for input \"", source, "\"."), fn, ln);
3162 }
3163
3164 enforce(!p.empty, bailOut());
3165
3166
3167 size_t count = 0;
3168 bool sign = false;
3169 switch (p.front)
3170 {
3171 case '-':
3172 sign = true;
3173 ++count;
3174 p.popFront();
3175 enforce(!p.empty, bailOut());
3176 if (toLower(p.front) == 'i')
3177 goto case 'i';
3178 break;
3179 case '+':
3180 ++count;
3181 p.popFront();
3182 enforce(!p.empty, bailOut());
3183 break;
3184 case 'i': case 'I':
3185 // inf
3186 ++count;
3187 p.popFront();
3188 enforce(!p.empty && toUpper(p.front) == 'N',
3189 bailOut("error converting input to floating point"));
3190 ++count;
3191 p.popFront();
3192 enforce(!p.empty && toUpper(p.front) == 'F',
3193 bailOut("error converting input to floating point"));
3194 // skip past the last 'f'
3195 ++count;
3196 p.popFront();
3197 advanceSource();
3198 static if (doCount)
3199 {
3200 return tuple!("data", "count")(sign ? -Target.infinity : Target.infinity, count);
3201 }
3202 else
3203 {
3204 return sign ? -Target.infinity : Target.infinity;
3205 }
3206 default: {}
3207 }
3208
3209 bool isHex = false;
3210 bool startsWithZero = p.front == '0';
3211 if (startsWithZero)
3212 {
3213 ++count;
3214 p.popFront();
3215 if (p.empty)
3216 {
3217 advanceSource();
3218 static if (doCount)
3219 {
3220 return tuple!("data", "count")(cast (Target) (sign ? -0.0 : 0.0), count);
3221 }
3222 else
3223 {
3224 return sign ? -0.0 : 0.0;
3225 }
3226 }
3227
3228 isHex = p.front == 'x' || p.front == 'X';
3229 if (isHex)
3230 {
3231 ++count;
3232 p.popFront();
3233 }
3234 }
3235 else if (toLower(p.front) == 'n')
3236 {
3237 // nan
3238 ++count;
3239 p.popFront();
3240 enforce(!p.empty && toUpper(p.front) == 'A',
3241 bailOut("error converting input to floating point"));
3242 ++count;
3243 p.popFront();
3244 enforce(!p.empty && toUpper(p.front) == 'N',
3245 bailOut("error converting input to floating point"));
3246 // skip past the last 'n'
3247 ++count;
3248 p.popFront();
3249 advanceSource();
3250 static if (doCount)
3251 {
3252 return tuple!("data", "count")(Target.nan, count);
3253 }
3254 else
3255 {
3256 return typeof(return).nan;
3257 }
3258 }
3259
3260 /*
3261 * The following algorithm consists of 2 steps:
3262 * 1) parseDigits processes the textual input into msdec and possibly
3263 * lsdec/msscale variables, followed by the exponent parser which sets
3264 * exp below.
3265 * Hex: input is 0xaaaaa...p+000... where aaaa is the mantissa in hex
3266 * and 000 is the exponent in decimal format with base 2.
3267 * Decimal: input is 0.00333...p+000... where 0.0033 is the mantissa
3268 * in decimal and 000 is the exponent in decimal format with base 10.
3269 * 2) Convert msdec/lsdec and exp into native real format
3270 */
3271
3272 real ldval = 0.0;
3273 char dot = 0; /* if decimal point has been seen */
3274 int exp = 0;
3275 ulong msdec = 0, lsdec = 0;
3276 ulong msscale = 1;
3277 bool sawDigits;
3278
3279 enum { hex, decimal }
3280
3281 // sets msdec, lsdec/msscale, and sawDigits by parsing the mantissa digits
3282 void parseDigits(alias FloatFormat)()
3283 {
3284 static if (FloatFormat == hex)
3285 {
3286 enum uint base = 16;
3287 enum ulong msscaleMax = 0x1000_0000_0000_0000UL; // largest power of 16 a ulong holds
3288 enum ubyte expIter = 4; // iterate the base-2 exponent by 4 for every hex digit
3289 alias checkDigit = isHexDigit;
3290 /*
3291 * convert letter to binary representation: First clear bit
3292 * to convert lower space chars to upperspace, then -('A'-10)
3293 * converts letter A to 10, letter B to 11, ...
3294 */
3295 alias convertDigit = (int x) => isAlpha(x) ? ((x & ~0x20) - ('A' - 10)) : x - '0';
3296 sawDigits = false;
3297 }
3298 else static if (FloatFormat == decimal)
3299 {
3300 enum uint base = 10;
3301 enum ulong msscaleMax = 10_000_000_000_000_000_000UL; // largest power of 10 a ulong holds
3302 enum ubyte expIter = 1; // iterate the base-10 exponent once for every decimal digit
3303 alias checkDigit = isDigit;
3304 alias convertDigit = (int x) => x - '0';
3305 // Used to enforce that any mantissa digits are present
3306 sawDigits = startsWithZero;
3307 }
3308 else
3309 static assert(false, "Unrecognized floating-point format used.");
3310
3311 while (!p.empty)
3312 {
3313 int i = p.front;
3314 while (checkDigit(i))
3315 {
3316 sawDigits = true; /* must have at least 1 digit */
3317
3318 i = convertDigit(i);
3319
3320 if (msdec < (ulong.max - base)/base)
3321 {
3322 // For base 16: Y = ... + y3*16^3 + y2*16^2 + y1*16^1 + y0*16^0
3323 msdec = msdec * base + i;
3324 }
3325 else if (msscale < msscaleMax)
3326 {
3327 lsdec = lsdec * base + i;
3328 msscale *= base;
3329 }
3330 else
3331 {
3332 exp += expIter;
3333 }
3334 exp -= dot;
3335 ++count;
3336 p.popFront();
3337 if (p.empty)
3338 break;
3339 i = p.front;
3340 if (i == '_')
3341 {
3342 ++count;
3343 p.popFront();
3344 if (p.empty)
3345 break;
3346 i = p.front;
3347 }
3348 }
3349 if (i == '.' && !dot)
3350 {
3351 ++count;
3352 p.popFront();
3353 dot += expIter;
3354 }
3355 else
3356 break;
3357 }
3358
3359 // Have we seen any mantissa digits so far?
3360 enforce(sawDigits, bailOut("no digits seen"));
3361 static if (FloatFormat == hex)
3362 enforce(!p.empty && (p.front == 'p' || p.front == 'P'),
3363 bailOut("Floating point parsing: exponent is required"));
3364 }
3365
3366 if (isHex)
3367 parseDigits!hex;
3368 else
3369 parseDigits!decimal;
3370
3371 if (isHex || (!p.empty && (p.front == 'e' || p.front == 'E')))
3372 {
3373 char sexp = 0;
3374 int e = 0;
3375
3376 ++count;
3377 p.popFront();
3378 enforce(!p.empty, new ConvException("Unexpected end of input"));
3379 switch (p.front)
3380 {
3381 case '-': sexp++;
3382 goto case;
3383 case '+': ++count;
3384 p.popFront();
3385 break;
3386 default: {}
3387 }
3388 sawDigits = false;
3389 while (!p.empty && isDigit(p.front))
3390 {
3391 if (e < 0x7FFFFFFF / 10 - 10) // prevent integer overflow
3392 {
3393 e = e * 10 + p.front - '0';
3394 }
3395 ++count;
3396 p.popFront();
3397 sawDigits = true;
3398 }
3399 exp += (sexp) ? -e : e;
3400 enforce(sawDigits, new ConvException("No digits seen."));
3401 }
3402
3403 ldval = msdec;
3404 if (msscale != 1) /* if stuff was accumulated in lsdec */
3405 ldval = ldval * msscale + lsdec;
3406 if (isHex)
3407 {
3408 import core.math : ldexp;
3409
3410 // Exponent is power of 2, not power of 10
3411 ldval = ldexp(ldval,exp);
3412 }
3413 else if (ldval)
3414 {
3415 uint u = 0;
3416 int pow = 4096;
3417
3418 while (exp > 0)
3419 {
3420 while (exp >= pow)
3421 {
3422 ldval *= postab[u];
3423 exp -= pow;
3424 }
3425 pow >>= 1;
3426 u++;
3427 }
3428 while (exp < 0)
3429 {
3430 while (exp <= -pow)
3431 {
3432 ldval *= negtab[u];
3433 enforce(ldval != 0, new ConvException("Range error"));
3434 exp += pow;
3435 }
3436 pow >>= 1;
3437 u++;
3438 }
3439 }
3440
3441 Target result = cast(Target) (sign ? -ldval : ldval);
3442
3443 // if overflow occurred
3444 import std.math.traits : isFinite;
3445 enforce(isFinite(result), new ConvException("Range error"));
3446
3447 advanceSource();
3448 static if (doCount)
3449 {
3450 return tuple!("data", "count")(result, count);
3451 }
3452 else
3453 {
3454 return result;
3455 }
3456 }
3457
3458
3459 ///
3460 @safe unittest
3461 {
3462 import std.math.operations : isClose;
3463 import std.math.traits : isNaN, isInfinity;
3464 import std.typecons : Flag, Yes, No;
3465 auto str = "123.456";
3466 assert(parse!double(str).isClose(123.456));
3467 auto str2 = "123.456";
3468 assert(parse!(double, string, No.doCount)(str2).isClose(123.456));
3469 auto str3 = "123.456";
3470 auto r = parse!(double, string, Yes.doCount)(str3);
3471 assert(r.data.isClose(123.456));
3472 assert(r.count == 7);
3473 auto str4 = "-123.456";
3474 r = parse!(double, string, Yes.doCount)(str4);
3475 assert(r.data.isClose(-123.456));
3476 assert(r.count == 8);
3477 auto str5 = "+123.456";
3478 r = parse!(double, string, Yes.doCount)(str5);
3479 assert(r.data.isClose(123.456));
3480 assert(r.count == 8);
3481 auto str6 = "inf0";
3482 r = parse!(double, string, Yes.doCount)(str6);
3483 assert(isInfinity(r.data) && r.count == 3 && str6 == "0");
3484 auto str7 = "-0";
3485 auto r2 = parse!(float, string, Yes.doCount)(str7);
3486 assert(r2.data.isClose(0.0) && r2.count == 2);
3487 auto str8 = "nan";
3488 auto r3 = parse!(real, string, Yes.doCount)(str8);
3489 assert(isNaN(r3.data) && r3.count == 3);
3490 }
3491
3492 @safe unittest
3493 {
3494 import std.exception;
3495 import std.math.traits : isNaN, isInfinity;
3496 import std.math.algebraic : fabs;
3497
3498 // Compare reals with given precision
3499 bool feq(in real rx, in real ry, in real precision = 0.000001L)
3500 {
3501 if (rx == ry)
3502 return 1;
3503
3504 if (isNaN(rx))
3505 return cast(bool) isNaN(ry);
3506
3507 if (isNaN(ry))
3508 return 0;
3509
3510 return cast(bool)(fabs(rx - ry) <= precision);
3511 }
3512
3513 // Make given typed literal
3514 F Literal(F)(F f)
3515 {
3516 return f;
3517 }
3518
3519 static foreach (Float; AliasSeq!(float, double, real))
3520 {
3521 assert(to!Float("123") == Literal!Float(123));
3522 assert(to!Float("+123") == Literal!Float(+123));
3523 assert(to!Float("-123") == Literal!Float(-123));
3524 assert(to!Float("123e2") == Literal!Float(123e2));
3525 assert(to!Float("123e+2") == Literal!Float(123e+2));
3526 assert(to!Float("123e-2") == Literal!Float(123e-2L));
3527 assert(to!Float("123.") == Literal!Float(123.0));
3528 assert(to!Float(".375") == Literal!Float(.375));
3529
3530 assert(to!Float("1.23375E+2") == Literal!Float(1.23375E+2));
3531
3532 assert(to!Float("0") is 0.0);
3533 assert(to!Float("-0") is -0.0);
3534
3535 assert(isNaN(to!Float("nan")));
3536
3537 assertThrown!ConvException(to!Float("\x00"));
3538 }
3539
3540 // min and max
3541 float f = to!float("1.17549e-38");
3542 assert(feq(cast(real) f, cast(real) 1.17549e-38));
3543 assert(feq(cast(real) f, cast(real) float.min_normal));
3544 f = to!float("3.40282e+38");
3545 assert(to!string(f) == to!string(3.40282e+38));
3546
3547 // min and max
3548 double d = to!double("2.22508e-308");
3549 assert(feq(cast(real) d, cast(real) 2.22508e-308));
3550 assert(feq(cast(real) d, cast(real) double.min_normal));
3551 d = to!double("1.79769e+308");
3552 assert(to!string(d) == to!string(1.79769e+308));
3553 assert(to!string(d) == to!string(double.max));
3554
3555 auto z = real.max / 2L;
3556 static assert(is(typeof(z) == real));
3557 assert(!isNaN(z));
3558 assert(!isInfinity(z));
3559 string a = to!string(z);
3560 real b = to!real(a);
3561 string c = to!string(b);
3562
3563 assert(c == a, "\n" ~ c ~ "\n" ~ a);
3564
3565 assert(to!string(to!real(to!string(real.max / 2L))) == to!string(real.max / 2L));
3566
3567 // min and max
3568 real r = to!real(to!string(real.min_normal));
3569 version (NetBSD)
3570 {
3571 // NetBSD notice
3572 // to!string returns 3.3621e-4932L. It is less than real.min_normal and it is subnormal value
3573 // Simple C code
3574 // long double rd = 3.3621e-4932L;
3575 // printf("%Le\n", rd);
3576 // has unexpected result: 1.681050e-4932
3577 //
3578 // Bug report: http://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=50937
3579 }
3580 else
3581 {
3582 assert(to!string(r) == to!string(real.min_normal));
3583 }
3584 r = to!real(to!string(real.max));
3585 assert(to!string(r) == to!string(real.max));
3586
3587 real pi = 3.1415926535897932384626433832795028841971693993751L;
3588 string fullPrecision = "3.1415926535897932384626433832795028841971693993751";
3589 assert(feq(parse!real(fullPrecision), pi, 2*real.epsilon));
3590 string fullPrecision2 = "3.1415926535897932384626433832795028841971693993751";
3591 assert(feq(parse!(real, string, No.doCount)(fullPrecision2), pi, 2*real.epsilon));
3592 string fullPrecision3= "3.1415926535897932384626433832795028841971693993751";
3593 auto len = fullPrecision3.length;
3594 auto res = parse!(real, string, Yes.doCount)(fullPrecision3);
3595 assert(feq(res.data, pi, 2*real.epsilon));
3596 assert(res.count == len);
3597
3598 real x = 0x1.FAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAAFAAFAFAFAFAFAFAFAP-252L;
3599 string full = "0x1.FAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAAFAAFAFAFAFAFAFAFAP-252";
3600 assert(parse!real(full) == x);
3601 string full2 = "0x1.FAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAAFAAFAFAFAFAFAFAFAP-252";
3602 assert(parse!(real, string, No.doCount)(full2) == x);
3603 string full3 = "0x1.FAFAFAFAFAFAFAFAFAFAFAFAFAFAFAFAAFAAFAFAFAFAFAFAFAP-252";
3604 auto len2 = full3.length;
3605 assert(parse!(real, string, Yes.doCount)(full3) == tuple(x, len2));
3606 }
3607
3608 // Tests for the double implementation
3609 @system unittest
3610 {
3611 // @system because strtod is not @safe.
3612 import std.math.traits : floatTraits, RealFormat;
3613
3614 static if (floatTraits!real.realFormat == RealFormat.ieeeDouble)
3615 {
3616 import core.stdc.stdlib, std.exception, std.math;
3617
3618 //Should be parsed exactly: 53 bit mantissa
3619 string s = "0x1A_BCDE_F012_3456p10";
3620 auto x = parse!real(s);
3621 assert(x == 0x1A_BCDE_F012_3456p10L);
3622 //1 bit is implicit
3623 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0xA_BCDE_F012_3456);
3624 assert(strtod("0x1ABCDEF0123456p10", null) == x);
3625
3626 s = "0x1A_BCDE_F012_3456p10";
3627 auto len = s.length;
3628 assert(parse!(real, string, Yes.doCount)(s) == tuple(x, len));
3629
3630 //Should be parsed exactly: 10 bit mantissa
3631 s = "0x3FFp10";
3632 x = parse!real(s);
3633 assert(x == 0x03FFp10);
3634 //1 bit is implicit
3635 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0x000F_F800_0000_0000);
3636 assert(strtod("0x3FFp10", null) == x);
3637
3638 //60 bit mantissa, round up
3639 s = "0xFFF_FFFF_FFFF_FFFFp10";
3640 x = parse!real(s);
3641 assert(isClose(x, 0xFFF_FFFF_FFFF_FFFFp10));
3642 //1 bit is implicit
3643 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0x0000_0000_0000_0000);
3644 assert(strtod("0xFFFFFFFFFFFFFFFp10", null) == x);
3645
3646 //60 bit mantissa, round down
3647 s = "0xFFF_FFFF_FFFF_FF90p10";
3648 x = parse!real(s);
3649 assert(isClose(x, 0xFFF_FFFF_FFFF_FF90p10));
3650 //1 bit is implicit
3651 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0x000F_FFFF_FFFF_FFFF);
3652 assert(strtod("0xFFFFFFFFFFFFF90p10", null) == x);
3653
3654 //61 bit mantissa, round up 2
3655 s = "0x1F0F_FFFF_FFFF_FFFFp10";
3656 x = parse!real(s);
3657 assert(isClose(x, 0x1F0F_FFFF_FFFF_FFFFp10));
3658 //1 bit is implicit
3659 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0x000F_1000_0000_0000);
3660 assert(strtod("0x1F0FFFFFFFFFFFFFp10", null) == x);
3661
3662 //61 bit mantissa, round down 2
3663 s = "0x1F0F_FFFF_FFFF_FF10p10";
3664 x = parse!real(s);
3665 assert(isClose(x, 0x1F0F_FFFF_FFFF_FF10p10));
3666 //1 bit is implicit
3667 assert(((*cast(ulong*)&x) & 0x000F_FFFF_FFFF_FFFF) == 0x000F_0FFF_FFFF_FFFF);
3668 assert(strtod("0x1F0FFFFFFFFFFF10p10", null) == x);
3669
3670 //Huge exponent
3671 s = "0x1F_FFFF_FFFF_FFFFp900";
3672 x = parse!real(s);
3673 assert(strtod("0x1FFFFFFFFFFFFFp900", null) == x);
3674
3675 //exponent too big -> converror
3676 s = "";
3677 assertThrown!ConvException(x = parse!real(s));
3678 assert(strtod("0x1FFFFFFFFFFFFFp1024", null) == real.infinity);
3679
3680 //-exponent too big -> 0
3681 s = "0x1FFFFFFFFFFFFFp-2000";
3682 x = parse!real(s);
3683 assert(x == 0);
3684 assert(strtod("0x1FFFFFFFFFFFFFp-2000", null) == x);
3685
3686 s = "0x1FFFFFFFFFFFFFp-2000";
3687 len = s.length;
3688 assert(parse!(real, string, Yes.doCount)(s) == tuple(x, len));
3689 }
3690 }
3691
3692 @system unittest
3693 {
3694 import core.stdc.errno;
3695 import core.stdc.stdlib;
3696 import std.math.traits : floatTraits, RealFormat;
3697
3698 errno = 0; // In case it was set by another unittest in a different module.
3699 struct longdouble
3700 {
3701 static if (floatTraits!real.realFormat == RealFormat.ieeeQuadruple)
3702 {
3703 ushort[8] value;
3704 }
3705 else static if (floatTraits!real.realFormat == RealFormat.ieeeExtended ||
3706 floatTraits!real.realFormat == RealFormat.ieeeExtended53)
3707 {
3708 ushort[5] value;
3709 }
3710 else static if (floatTraits!real.realFormat == RealFormat.ieeeDouble)
3711 {
3712 ushort[4] value;
3713 }
3714 else
3715 static assert(false, "Not implemented");
3716 }
3717
3718 real ld;
3719 longdouble x;
3720 real ld1;
3721 longdouble x1;
3722 int i;
3723
3724 static if (floatTraits!real.realFormat == RealFormat.ieeeQuadruple)
3725 enum s = "0x1.FFFFFFFFFFFFFFFFFFFFFFFFFFFFp-16382";
3726 else static if (floatTraits!real.realFormat == RealFormat.ieeeExtended)
3727 enum s = "0x1.FFFFFFFFFFFFFFFEp-16382";
3728 else static if (floatTraits!real.realFormat == RealFormat.ieeeExtended53)
3729 enum s = "0x1.FFFFFFFFFFFFFFFEp-16382";
3730 else static if (floatTraits!real.realFormat == RealFormat.ieeeDouble)
3731 enum s = "0x1.FFFFFFFFFFFFFFFEp-1000";
3732 else
3733 static assert(false, "Floating point format for real not supported");
3734
3735 auto s2 = s.idup;
3736 ld = parse!real(s2);
3737 assert(s2.empty);
3738 x = *cast(longdouble *)&ld;
3739
3740 static if (floatTraits!real.realFormat == RealFormat.ieeeExtended)
3741 {
3742 version (CRuntime_Microsoft)
3743 ld1 = 0x1.FFFFFFFFFFFFFFFEp-16382L; // strtold currently mapped to strtod
3744 else
3745 ld1 = strtold(s.ptr, null);
3746 }
3747 else static if (floatTraits!real.realFormat == RealFormat.ieeeExtended53)
3748 ld1 = 0x1.FFFFFFFFFFFFFFFEp-16382L; // strtold rounds to 53 bits.
3749 else
3750 ld1 = strtold(s.ptr, null);
3751
3752 x1 = *cast(longdouble *)&ld1;
3753 assert(x1 == x && ld1 == ld);
3754
3755 assert(!errno);
3756
3757 s2 = "1.0e5";
3758 ld = parse!real(s2);
3759 assert(s2.empty);
3760 x = *cast(longdouble *)&ld;
3761 ld1 = strtold("1.0e5", null);
3762 x1 = *cast(longdouble *)&ld1;
3763 }
3764
3765 @safe pure unittest
3766 {
3767 import std.exception;
3768
3769 // https://issues.dlang.org/show_bug.cgi?id=4959
3770 {
3771 auto s = "0 ";
3772 auto x = parse!double(s);
3773 assert(s == " ");
3774 assert(x == 0.0);
3775 }
3776 {
3777 auto s = "0 ";
3778 auto x = parse!(double, string, Yes.doCount)(s);
3779 assert(s == " ");
3780 assert(x == tuple(0.0, 1));
3781 }
3782
3783 // https://issues.dlang.org/show_bug.cgi?id=3369
3784 assert(to!float("inf") == float.infinity);
3785 assert(to!float("-inf") == -float.infinity);
3786
3787 // https://issues.dlang.org/show_bug.cgi?id=6160
3788 assert(6_5.536e3L == to!real("6_5.536e3")); // 2^16
3789 assert(0x1000_000_000_p10 == to!real("0x1000_000_000_p10")); // 7.03687e+13
3790
3791 // https://issues.dlang.org/show_bug.cgi?id=6258
3792 assertThrown!ConvException(to!real("-"));
3793 assertThrown!ConvException(to!real("in"));
3794
3795 // https://issues.dlang.org/show_bug.cgi?id=7055
3796 assertThrown!ConvException(to!float("INF2"));
3797
3798 //extra stress testing
3799 auto ssOK = ["1.", "1.1.1", "1.e5", "2e1e", "2a", "2e1_1", "3.4_",
3800 "inf", "-inf", "infa", "-infa", "inf2e2", "-inf2e2",
3801 "nan", "-NAN", "+NaN", "-nAna", "NAn2e2", "-naN2e2"];
3802 auto ssKO = ["", " ", "2e", "2e+", "2e-", "2ee", "2e++1", "2e--1", "2e_1",
3803 "+inf", "-in", "I", "+N", "-NaD", "0x3.F"];
3804 foreach (s; ssOK)
3805 parse!double(s);
3806 foreach (s; ssKO)
3807 assertThrown!ConvException(parse!double(s));
3808 }
3809
3810 @safe unittest // https://issues.dlang.org/show_bug.cgi?id=22637
3811 {
3812 import std.exception : assertThrown, assertNotThrown;
3813 auto src = "9991232549867999698999493543521458974414359998784641646846435132132543645435456345634541999999999999999"
3814 ~ "9999999943321231321311999231345312413646846354354354399999934153465464654646464654134135354199999999996515734999"
3815 ~ "9999999320135273486741354354731567431324134999999999999999999999999999999999999999999999135411.9";
3816 assertThrown!ConvException(parse!double(src));
3817 static if (real.max_10_exp > 310) assertNotThrown!ConvException(parse!real(src));
3818 }
3819
3820 /**
3821 Parses one character from a character range.
3822
3823 Params:
3824 Target = the type to convert to
3825 s = the lvalue of an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
3826 doCount = the flag for deciding to report the number of consumed characters
3827
3828 Returns:
3829 $(UL
3830 $(LI A character of type `Target` if `doCount` is set to `No.doCount`)
3831 $(LI A `tuple` containing a character of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`))
3832
3833 Throws:
3834 A $(LREF ConvException) if the range is empty.
3835 */
3836 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
3837 if (staticIndexOf!(immutable Target, immutable dchar, immutable ElementEncodingType!Source) >= 0 &&
3838 isSomeString!Source && !is(Source == enum))
3839 {
3840 if (s.empty)
3841 throw convError!(Source, Target)(s);
3842 static if (is(immutable Target == immutable dchar))
3843 {
3844 Target result = s.front;
3845 s.popFront();
3846 static if (doCount)
3847 {
3848 return tuple!("data", "count")(result, 1);
3849 }
3850 else
3851 {
3852 return result;
3853 }
3854
3855 }
3856 else
3857 {
3858 // Special case: okay so parse a Char off a Char[]
3859 Target result = s[0];
3860 s = s[1 .. $];
3861 static if (doCount)
3862 {
3863 return tuple!("data", "count")(result, 1);
3864 }
3865 else
3866 {
3867 return result;
3868 }
3869 }
3870 }
3871
3872 @safe pure unittest
3873 {
3874 static foreach (Str; AliasSeq!(string, wstring, dstring))
3875 {
3876 static foreach (Char; AliasSeq!(char, wchar, dchar))
3877 {{
3878 static if (is(immutable Char == immutable dchar) ||
3879 Char.sizeof == ElementEncodingType!Str.sizeof)
3880 {
3881 Str s = "aaa";
3882 assert(parse!Char(s) == 'a');
3883 assert(s == "aa");
3884 assert(parse!(Char, typeof(s), No.doCount)(s) == 'a');
3885 assert(s == "a");
3886 assert(parse!(Char, typeof(s), Yes.doCount)(s) == tuple('a', 1) && s == "");
3887 }
3888 }}
3889 }
3890 }
3891
3892 /// ditto
3893 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
3894 if (isSomeChar!Target && Target.sizeof >= ElementType!Source.sizeof && !is(Target == enum) &&
3895 !isSomeString!Source && isInputRange!Source && isSomeChar!(ElementType!Source))
3896 {
3897 if (s.empty)
3898 throw convError!(Source, Target)(s);
3899 Target result = s.front;
3900 s.popFront();
3901 static if (doCount)
3902 {
3903 return tuple!("data", "count")(result, 1);
3904 }
3905 else
3906 {
3907 return result;
3908 }
3909 }
3910
3911 ///
3912 @safe pure unittest
3913 {
3914 import std.typecons : Flag, Yes, No;
3915 auto s = "Hello, World!";
3916 char first = parse!char(s);
3917 assert(first == 'H');
3918 assert(s == "ello, World!");
3919 char second = parse!(char, string, No.doCount)(s);
3920 assert(second == 'e');
3921 assert(s == "llo, World!");
3922 auto third = parse!(char, string, Yes.doCount)(s);
3923 assert(third.data == 'l' && third.count == 1);
3924 assert(s == "lo, World!");
3925 }
3926
3927
3928 /*
3929 Tests for to!bool and parse!bool
3930 */
3931 @safe pure unittest
3932 {
3933 import std.exception;
3934
3935 assert(to!bool("TruE") == true);
3936 assert(to!bool("faLse"d) == false);
3937 assertThrown!ConvException(to!bool("maybe"));
3938
3939 auto t = "TrueType";
3940 assert(parse!bool(t) == true);
3941 assert(t == "Type");
3942
3943 auto f = "False killer whale"d;
3944 assert(parse!bool(f) == false);
3945 assert(f == " killer whale"d);
3946
3947 f = "False killer whale"d;
3948 assert(parse!(bool, dstring, Yes.doCount)(f) == tuple(false, 5));
3949 assert(f == " killer whale"d);
3950
3951 auto m = "maybe";
3952 assertThrown!ConvException(parse!bool(m));
3953 assertThrown!ConvException(parse!(bool, string, Yes.doCount)(m));
3954 assert(m == "maybe"); // m shouldn't change on failure
3955
3956 auto s = "true";
3957 auto b = parse!(const(bool))(s);
3958 assert(b == true);
3959 }
3960
3961 /**
3962 Parses `typeof(null)` from a character range if the range
3963 spells `"null"`. This function is case insensitive.
3964
3965 Params:
3966 Target = the type to convert to
3967 s = the lvalue of an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
3968 doCount = the flag for deciding to report the number of consumed characters
3969
3970 Returns:
3971 $(UL
3972 $(LI `null` if `doCount` is set to `No.doCount`)
3973 $(LI A `tuple` containing `null` and a `size_t` if `doCount` is set to `Yes.doCount`))
3974
3975 Throws:
3976 A $(LREF ConvException) if the range doesn't represent `null`.
3977 */
3978 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
3979 if (is(immutable Target == immutable typeof(null)) &&
3980 isInputRange!Source &&
3981 isSomeChar!(ElementType!Source))
3982 {
3983 import std.ascii : toLower;
3984 foreach (c; "null")
3985 {
3986 if (s.empty || toLower(s.front) != c)
3987 throw parseError("null should be case-insensitive 'null'");
3988 s.popFront();
3989 }
3990 static if (doCount)
3991 {
3992 return tuple!("data", "count")(null, 4);
3993 }
3994 else
3995 {
3996 return null;
3997 }
3998 }
3999
4000 ///
4001 @safe pure unittest
4002 {
4003 import std.exception : assertThrown;
4004 import std.typecons : Flag, Yes, No;
4005
4006 alias NullType = typeof(null);
4007 auto s1 = "null";
4008 assert(parse!NullType(s1) is null);
4009 assert(s1 == "");
4010
4011 auto s2 = "NUll"d;
4012 assert(parse!NullType(s2) is null);
4013 assert(s2 == "");
4014
4015 auto s3 = "nuLlNULl";
4016 assert(parse!(NullType, string, No.doCount)(s3) is null);
4017 auto r = parse!(NullType, string, Yes.doCount)(s3);
4018 assert(r.data is null && r.count == 4);
4019
4020 auto m = "maybe";
4021 assertThrown!ConvException(parse!NullType(m));
4022 assertThrown!ConvException(parse!(NullType, string, Yes.doCount)(m));
4023 assert(m == "maybe"); // m shouldn't change on failure
4024
4025 auto s = "NULL";
4026 assert(parse!(const NullType)(s) is null);
4027 }
4028
4029 //Used internally by parse Array/AA, to remove ascii whites
4030 package auto skipWS(R, Flag!"doCount" doCount = No.doCount)(ref R r)
4031 {
4032 import std.ascii : isWhite;
4033 static if (isSomeString!R)
4034 {
4035 //Implementation inspired from stripLeft.
4036 foreach (i, c; r)
4037 {
4038 if (!isWhite(c))
4039 {
4040 r = r[i .. $];
4041 static if (doCount)
4042 {
4043 return i;
4044 }
4045 else
4046 {
4047 return;
4048 }
4049 }
4050 }
4051 auto len = r.length;
4052 r = r[0 .. 0]; //Empty string with correct type.
4053 static if (doCount)
4054 {
4055 return len;
4056 }
4057 else
4058 {
4059 return;
4060 }
4061 }
4062 else
4063 {
4064 size_t i = 0;
4065 for (; !r.empty && isWhite(r.front); r.popFront(), ++i)
4066 { }
4067 static if (doCount)
4068 {
4069 return i;
4070 }
4071 }
4072 }
4073
4074 /**
4075 * Parses an array from a string given the left bracket (default $(D
4076 * '[')), right bracket (default `']'`), and element separator (by
4077 * default `','`). A trailing separator is allowed.
4078 *
4079 * Params:
4080 * s = The string to parse
4081 * lbracket = the character that starts the array
4082 * rbracket = the character that ends the array
4083 * comma = the character that separates the elements of the array
4084 * doCount = the flag for deciding to report the number of consumed characters
4085 *
4086 * Returns:
4087 $(UL
4088 * $(LI An array of type `Target` if `doCount` is set to `No.doCount`)
4089 * $(LI A `tuple` containing an array of type `Target` and a `size_t` if `doCount` is set to `Yes.doCount`))
4090 */
4091 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[',
4092 dchar rbracket = ']', dchar comma = ',')
4093 if (isDynamicArray!Target && !is(Target == enum) &&
4094 isSomeString!Source && !is(Source == enum))
4095 {
4096 import std.array : appender;
4097
4098 auto result = appender!Target();
4099
4100 parseCheck!s(lbracket);
4101 size_t count = 1 + skipWS!(Source, Yes.doCount)(s);
4102 if (s.empty)
4103 throw convError!(Source, Target)(s);
4104 if (s.front == rbracket)
4105 {
4106 s.popFront();
4107 static if (doCount)
4108 {
4109 return tuple!("data", "count")(result.data, ++count);
4110 }
4111 else
4112 {
4113 return result.data;
4114 }
4115 }
4116 for (;; s.popFront(), count += 1 + skipWS!(Source, Yes.doCount)(s))
4117 {
4118 if (!s.empty && s.front == rbracket)
4119 break;
4120 auto r = parseElement!(WideElementType!Target, Source, Yes.doCount)(s);
4121 result ~= r.data;
4122 count += r.count + skipWS!(Source, Yes.doCount)(s);
4123 if (s.empty)
4124 throw convError!(Source, Target)(s);
4125 if (s.front != comma)
4126 break;
4127 }
4128 parseCheck!s(rbracket);
4129 static if (doCount)
4130 {
4131 return tuple!("data", "count")(result.data, ++count);
4132 }
4133 else
4134 {
4135 return result.data;
4136 }
4137 }
4138
4139 ///
4140 @safe pure unittest
4141 {
4142 import std.typecons : Flag, Yes, No;
4143 auto s1 = `[['h', 'e', 'l', 'l', 'o'], "world"]`;
4144 auto a1 = parse!(string[])(s1);
4145 assert(a1 == ["hello", "world"]);
4146
4147 auto s2 = `["aaa", "bbb", "ccc"]`;
4148 auto a2 = parse!(string[])(s2);
4149 assert(a2 == ["aaa", "bbb", "ccc"]);
4150
4151 auto s3 = `[['h', 'e', 'l', 'l', 'o'], "world"]`;
4152 auto len3 = s3.length;
4153 auto a3 = parse!(string[], string, Yes.doCount)(s3);
4154 assert(a3.data == ["hello", "world"]);
4155 assert(a3.count == len3);
4156 }
4157
4158 // https://issues.dlang.org/show_bug.cgi?id=9615
4159 @safe unittest
4160 {
4161 import std.typecons : Flag, Yes, No, tuple;
4162 string s0 = "[1,2, ]";
4163 string s1 = "[1,2, \t\v\r\n]";
4164 string s2 = "[1,2]";
4165 assert(s0.parse!(int[]) == [1,2]);
4166 assert(s1.parse!(int[]) == [1,2]);
4167 assert(s2.parse!(int[]) == [1,2]);
4168
4169 s0 = "[1,2, ]";
4170 auto len0 = s0.length;
4171 s1 = "[1,2, \t\v\r\n]";
4172 auto len1 = s1.length;
4173 s2 = "[1,2]";
4174 auto len2 = s2.length;
4175 assert(s0.parse!(int[], string, Yes.doCount) == tuple([1,2], len0));
4176 assert(s1.parse!(int[], string, Yes.doCount) == tuple([1,2], len1));
4177 assert(s2.parse!(int[], string, Yes.doCount) == tuple([1,2], len2));
4178
4179 string s3 = `["a","b",]`;
4180 string s4 = `["a","b"]`;
4181 assert(s3.parse!(string[]) == ["a","b"]);
4182 assert(s4.parse!(string[]) == ["a","b"]);
4183
4184 s3 = `["a","b",]`;
4185 auto len3 = s3.length;
4186 assert(s3.parse!(string[], string, Yes.doCount) == tuple(["a","b"], len3));
4187
4188 s3 = `[ ]`;
4189 assert(tuple([], s3.length) == s3.parse!(string[], string, Yes.doCount));
4190
4191 import std.exception : assertThrown;
4192 string s5 = "[,]";
4193 string s6 = "[, \t,]";
4194 assertThrown!ConvException(parse!(string[])(s5));
4195 assertThrown!ConvException(parse!(int[])(s6));
4196
4197 s5 = "[,]";
4198 s6 = "[,·\t,]";
4199 assertThrown!ConvException(parse!(string[], string, Yes.doCount)(s5));
4200 assertThrown!ConvException(parse!(string[], string, Yes.doCount)(s6));
4201 }
4202
4203 @safe unittest
4204 {
4205 int[] a = [1, 2, 3, 4, 5];
4206 auto s = to!string(a);
4207 assert(to!(int[])(s) == a);
4208 }
4209
4210 @safe unittest
4211 {
4212 int[][] a = [ [1, 2] , [3], [4, 5] ];
4213 auto s = to!string(a);
4214 assert(to!(int[][])(s) == a);
4215 }
4216
4217 @safe unittest
4218 {
4219 int[][][] ia = [ [[1,2],[3,4],[5]] , [[6],[],[7,8,9]] , [[]] ];
4220
4221 char[] s = to!(char[])(ia);
4222 int[][][] ia2;
4223
4224 ia2 = to!(typeof(ia2))(s);
4225 assert( ia == ia2);
4226 }
4227
4228 @safe pure unittest
4229 {
4230 import std.exception;
4231 import std.typecons : Flag, Yes, No;
4232
4233 //Check proper failure
4234 auto s = "[ 1 , 2 , 3 ]";
4235 auto s2 = s.save;
4236 foreach (i ; 0 .. s.length-1)
4237 {
4238 auto ss = s[0 .. i];
4239 assertThrown!ConvException(parse!(int[])(ss));
4240 assertThrown!ConvException(parse!(int[], string, Yes.doCount)(ss));
4241 }
4242 int[] arr = parse!(int[])(s);
4243 auto arr2 = parse!(int[], string, Yes.doCount)(s2);
4244 arr = arr2.data;
4245 }
4246
4247 @safe pure unittest
4248 {
4249 //Checks parsing of strings with escaped characters
4250 string s1 = `[
4251 "Contains a\0null!",
4252 "tab\there",
4253 "line\nbreak",
4254 "backslash \\ slash / question \?",
4255 "number \x35 five",
4256 "unicode \u65E5 sun",
4257 "very long \U000065E5 sun"
4258 ]`;
4259
4260 //Note: escaped characters purposefully replaced and isolated to guarantee
4261 //there are no typos in the escape syntax
4262 string[] s2 = [
4263 "Contains a" ~ '\0' ~ "null!",
4264 "tab" ~ '\t' ~ "here",
4265 "line" ~ '\n' ~ "break",
4266 "backslash " ~ '\\' ~ " slash / question ?",
4267 "number 5 five",
4268 "unicode 日 sun",
4269 "very long 日 sun"
4270 ];
4271 string s3 = s1.save;
4272 assert(s2 == parse!(string[])(s1));
4273 assert(s1.empty);
4274 assert(tuple(s2, s3.length) == parse!(string[], string, Yes.doCount)(s3));
4275 }
4276
4277 /// ditto
4278 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[',
4279 dchar rbracket = ']', dchar comma = ',')
4280 if (isStaticArray!Target && !is(Target == enum) &&
4281 isExactSomeString!Source)
4282 {
4283 static if (hasIndirections!Target)
4284 Target result = Target.init[0].init;
4285 else
4286 Target result = void;
4287
4288 parseCheck!s(lbracket);
4289 size_t count = 1 + skipWS!(Source, Yes.doCount)(s);
4290 if (s.empty)
4291 throw convError!(Source, Target)(s);
4292 if (s.front == rbracket)
4293 {
4294 static if (result.length != 0)
4295 goto Lmanyerr;
4296 else
4297 {
4298 s.popFront();
4299 static if (doCount)
4300 {
4301 return tuple!("data", "count")(result, ++count);
4302 }
4303 else
4304 {
4305 return result;
4306 }
4307 }
4308 }
4309 for (size_t i = 0; ; s.popFront(), count += 1 + skipWS!(Source, Yes.doCount)(s))
4310 {
4311 if (i == result.length)
4312 goto Lmanyerr;
4313 auto r = parseElement!(ElementType!Target, Source, Yes.doCount)(s);
4314 result[i++] = r.data;
4315 count += r.count + skipWS!(Source, Yes.doCount)(s);
4316 if (s.empty)
4317 throw convError!(Source, Target)(s);
4318 if (s.front != comma)
4319 {
4320 if (i != result.length)
4321 goto Lfewerr;
4322 break;
4323 }
4324 }
4325 parseCheck!s(rbracket);
4326 static if (doCount)
4327 {
4328 return tuple!("data", "count")(result, ++count);
4329 }
4330 else
4331 {
4332 return result;
4333 }
4334
4335
4336 Lmanyerr:
4337 throw parseError(text("Too many elements in input, ", result.length, " elements expected."));
4338
4339 Lfewerr:
4340 throw parseError(text("Too few elements in input, ", result.length, " elements expected."));
4341 }
4342
4343 @safe pure unittest
4344 {
4345 import std.exception;
4346
4347 auto s1 = "[1,2,3,4]";
4348 auto sa1 = parse!(int[4])(s1);
4349 assert(sa1 == [1,2,3,4]);
4350 s1 = "[1,2,3,4]";
4351 assert(tuple([1,2,3,4], s1.length) == parse!(int[4], string, Yes.doCount)(s1));
4352
4353 auto s2 = "[[1],[2,3],[4]]";
4354 auto sa2 = parse!(int[][3])(s2);
4355 assert(sa2 == [[1],[2,3],[4]]);
4356 s2 = "[[1],[2,3],[4]]";
4357 assert(tuple([[1],[2,3],[4]], s2.length) == parse!(int[][3], string, Yes.doCount)(s2));
4358
4359 auto s3 = "[1,2,3]";
4360 assertThrown!ConvException(parse!(int[4])(s3));
4361 assertThrown!ConvException(parse!(int[4], string, Yes.doCount)(s3));
4362
4363 auto s4 = "[1,2,3,4,5]";
4364 assertThrown!ConvException(parse!(int[4])(s4));
4365 assertThrown!ConvException(parse!(int[4], string, Yes.doCount)(s4));
4366 }
4367
4368 /**
4369 * Parses an associative array from a string given the left bracket (default $(D
4370 * '[')), right bracket (default `']'`), key-value separator (default $(D
4371 * ':')), and element seprator (by default `','`).
4372 *
4373 * Params:
4374 * s = the string to parse
4375 * lbracket = the character that starts the associative array
4376 * rbracket = the character that ends the associative array
4377 * keyval = the character that associates the key with the value
4378 * comma = the character that separates the elements of the associative array
4379 * doCount = the flag for deciding to report the number of consumed characters
4380 *
4381 * Returns:
4382 $(UL
4383 * $(LI An associative array of type `Target` if `doCount` is set to `No.doCount`)
4384 * $(LI A `tuple` containing an associative array of type `Target` and a `size_t`
4385 * if `doCount` is set to `Yes.doCount`))
4386 */
4387 auto parse(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s, dchar lbracket = '[',
4388 dchar rbracket = ']', dchar keyval = ':', dchar comma = ',')
4389 if (isAssociativeArray!Target && !is(Target == enum) &&
4390 isSomeString!Source && !is(Source == enum))
4391 {
4392 alias KeyType = typeof(Target.init.keys[0]);
4393 alias ValType = typeof(Target.init.values[0]);
4394
4395 Target result;
4396
4397 parseCheck!s(lbracket);
4398 size_t count = 1 + skipWS!(Source, Yes.doCount)(s);
4399 if (s.empty)
4400 throw convError!(Source, Target)(s);
4401 if (s.front == rbracket)
4402 {
4403 s.popFront();
4404 static if (doCount)
4405 {
4406 return tuple!("data", "count")(result, ++count);
4407 }
4408 else
4409 {
4410 return result;
4411 }
4412 }
4413 for (;; s.popFront(), count += 1 + skipWS!(Source, Yes.doCount)(s))
4414 {
4415 auto key = parseElement!(KeyType, Source, Yes.doCount)(s);
4416 count += key.count + skipWS!(Source, Yes.doCount)(s);
4417 parseCheck!s(keyval);
4418 count += 1 + skipWS!(Source, Yes.doCount)(s);
4419 auto val = parseElement!(ValType, Source, Yes.doCount)(s);
4420 count += val.count + skipWS!(Source, Yes.doCount)(s);
4421 result[key.data] = val.data;
4422 if (s.empty)
4423 throw convError!(Source, Target)(s);
4424 if (s.front != comma)
4425 break;
4426 }
4427 parseCheck!s(rbracket);
4428 static if (doCount)
4429 {
4430 return tuple!("data", "count")(result, ++count);
4431 }
4432 else
4433 {
4434 return result;
4435 }
4436 }
4437
4438 ///
4439 @safe pure unittest
4440 {
4441 import std.typecons : Flag, Yes, No, tuple;
4442 import std.range.primitives : save;
4443 import std.array : assocArray;
4444 auto s1 = "[1:10, 2:20, 3:30]";
4445 auto copyS1 = s1.save;
4446 auto aa1 = parse!(int[int])(s1);
4447 assert(aa1 == [1:10, 2:20, 3:30]);
4448 assert(tuple([1:10, 2:20, 3:30], copyS1.length) == parse!(int[int], string, Yes.doCount)(copyS1));
4449
4450 auto s2 = `["aaa":10, "bbb":20, "ccc":30]`;
4451 auto copyS2 = s2.save;
4452 auto aa2 = parse!(int[string])(s2);
4453 assert(aa2 == ["aaa":10, "bbb":20, "ccc":30]);
4454 assert(tuple(["aaa":10, "bbb":20, "ccc":30], copyS2.length) ==
4455 parse!(int[string], string, Yes.doCount)(copyS2));
4456
4457 auto s3 = `["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]]`;
4458 auto copyS3 = s3.save;
4459 auto aa3 = parse!(int[][string])(s3);
4460 assert(aa3 == ["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]]);
4461 assert(tuple(["aaa":[1], "bbb":[2,3], "ccc":[4,5,6]], copyS3.length) ==
4462 parse!(int[][string], string, Yes.doCount)(copyS3));
4463
4464 auto s4 = `[]`;
4465 int[int] emptyAA;
4466 assert(tuple(emptyAA, s4.length) == parse!(int[int], string, Yes.doCount)(s4));
4467 }
4468
4469 @safe pure unittest
4470 {
4471 import std.exception;
4472
4473 //Check proper failure
4474 auto s = "[1:10, 2:20, 3:30]";
4475 auto s2 = s.save;
4476 foreach (i ; 0 .. s.length-1)
4477 {
4478 auto ss = s[0 .. i];
4479 assertThrown!ConvException(parse!(int[int])(ss));
4480 assertThrown!ConvException(parse!(int[int], string, Yes.doCount)(ss));
4481 }
4482 int[int] aa = parse!(int[int])(s);
4483 auto aa2 = parse!(int[int], string, Yes.doCount)(s2);
4484 aa = aa2[0];
4485
4486 }
4487
4488 private auto parseEscape(Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
4489 if (isInputRange!Source && isSomeChar!(ElementType!Source))
4490 {
4491 parseCheck!s('\\');
4492 size_t count = 1;
4493 if (s.empty)
4494 throw parseError("Unterminated escape sequence");
4495
4496 // consumes 1 element from Source
4497 dchar getHexDigit()(ref Source s_ = s) // workaround
4498 {
4499 import std.ascii : isAlpha, isHexDigit;
4500 if (s_.empty)
4501 throw parseError("Unterminated escape sequence");
4502 s_.popFront();
4503 if (s_.empty)
4504 throw parseError("Unterminated escape sequence");
4505 dchar c = s_.front;
4506 if (!isHexDigit(c))
4507 throw parseError("Hex digit is missing");
4508 return isAlpha(c) ? ((c & ~0x20) - ('A' - 10)) : c - '0';
4509 }
4510
4511 // We need to do octals separate, because they need a lookahead to find out,
4512 // where the escape sequence ends.
4513 auto first = s.front;
4514 if (first >= '0' && first <= '7')
4515 {
4516 dchar c1 = s.front;
4517 ++count;
4518 s.popFront();
4519 if (s.empty)
4520 {
4521 static if (doCount)
4522 {
4523 return tuple!("data", "count")(cast (dchar) (c1 - '0'), count);
4524 }
4525 else
4526 {
4527 return cast (dchar) (c1 - '0');
4528 }
4529 }
4530 dchar c2 = s.front;
4531 if (c2 < '0' || c2 > '7')
4532 {
4533 static if (doCount)
4534 {
4535 return tuple!("data", "count")(cast (dchar)(c1 - '0'), count);
4536 }
4537 else
4538 {
4539 return cast (dchar)(c1 - '0');
4540 }
4541 }
4542 ++count;
4543 s.popFront();
4544 dchar c3 = s.front;
4545 if (c3 < '0' || c3 > '7')
4546 {
4547 static if (doCount)
4548 {
4549 return tuple!("data", "count")(cast (dchar) (8 * (c1 - '0') + (c2 - '0')), count);
4550 }
4551 else
4552 {
4553 return cast (dchar) (8 * (c1 - '0') + (c2 - '0'));
4554 }
4555 }
4556 ++count;
4557 s.popFront();
4558 if (c1 > '3')
4559 throw parseError("Octal sequence is larger than \\377");
4560 static if (doCount)
4561 {
4562 return tuple!("data", "count")(cast (dchar) (64 * (c1 - '0') + 8 * (c2 - '0') + (c3 - '0')), count);
4563 }
4564 else
4565 {
4566 return cast (dchar) (64 * (c1 - '0') + 8 * (c2 - '0') + (c3 - '0'));
4567 }
4568 }
4569
4570 dchar result;
4571
4572 switch (first)
4573 {
4574 case '"': result = '\"'; break;
4575 case '\'': result = '\''; break;
4576 case '?': result = '\?'; break;
4577 case '\\': result = '\\'; break;
4578 case 'a': result = '\a'; break;
4579 case 'b': result = '\b'; break;
4580 case 'f': result = '\f'; break;
4581 case 'n': result = '\n'; break;
4582 case 'r': result = '\r'; break;
4583 case 't': result = '\t'; break;
4584 case 'v': result = '\v'; break;
4585 case 'x':
4586 result = getHexDigit() << 4;
4587 result |= getHexDigit();
4588 count += 2;
4589 break;
4590 case 'u':
4591 result = getHexDigit() << 12;
4592 result |= getHexDigit() << 8;
4593 result |= getHexDigit() << 4;
4594 result |= getHexDigit();
4595 count += 4;
4596 break;
4597 case 'U':
4598 result = getHexDigit() << 28;
4599 result |= getHexDigit() << 24;
4600 result |= getHexDigit() << 20;
4601 result |= getHexDigit() << 16;
4602 result |= getHexDigit() << 12;
4603 result |= getHexDigit() << 8;
4604 result |= getHexDigit() << 4;
4605 result |= getHexDigit();
4606 count += 8;
4607 break;
4608 default:
4609 throw parseError("Unknown escape character " ~ to!string(s.front));
4610 }
4611 if (s.empty)
4612 throw parseError("Unterminated escape sequence");
4613
4614 s.popFront();
4615
4616 static if (doCount)
4617 {
4618 return tuple!("data", "count")(cast (dchar) result, ++count);
4619 }
4620 else
4621 {
4622 return cast (dchar) result;
4623 }
4624 }
4625
4626 @safe pure unittest
4627 {
4628 string[] s1 = [
4629 `\"`, `\'`, `\?`, `\\`, `\a`, `\b`, `\f`, `\n`, `\r`, `\t`, `\v`, //Normal escapes
4630 `\141`,
4631 `\x61`,
4632 `\u65E5`, `\U00012456`,
4633 // https://issues.dlang.org/show_bug.cgi?id=9621 (Named Character Entities)
4634 //`\&amp;`, `\&quot;`,
4635 ];
4636 string[] copyS1 = s1 ~ s1[0 .. 0];
4637
4638 const(dchar)[] s2 = [
4639 '\"', '\'', '\?', '\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v', //Normal escapes
4640 '\141',
4641 '\x61',
4642 '\u65E5', '\U00012456',
4643 // https://issues.dlang.org/show_bug.cgi?id=9621 (Named Character Entities)
4644 //'\&amp;', '\&quot;',
4645 ];
4646
4647 foreach (i ; 0 .. s1.length)
4648 {
4649 assert(s2[i] == parseEscape(s1[i]));
4650 assert(s1[i].empty);
4651
4652 assert(tuple(s2[i], copyS1[i].length) == parseEscape!(string, Yes.doCount)(copyS1[i]));
4653 assert(copyS1[i].empty);
4654 }
4655 }
4656
4657 @safe pure unittest
4658 {
4659 import std.exception;
4660
4661 string[] ss = [
4662 `hello!`, //Not an escape
4663 `\`, //Premature termination
4664 `\/`, //Not an escape
4665 `\gggg`, //Not an escape
4666 `\xzz`, //Not an hex
4667 `\x0`, //Premature hex end
4668 `\XB9`, //Not legal hex syntax
4669 `\u!!`, //Not a unicode hex
4670 `\777`, //Octal is larger than a byte
4671 `\80`, //Wrong digit at beginning of octal
4672 `\u123`, //Premature hex end
4673 `\U123123` //Premature hex end
4674 ];
4675 foreach (s ; ss)
4676 {
4677 assertThrown!ConvException(parseEscape(s));
4678 assertThrown!ConvException(parseEscape!(string, Yes.doCount)(s));
4679 }
4680 }
4681
4682 // Undocumented
4683 auto parseElement(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
4684 if (isInputRange!Source && isSomeChar!(ElementType!Source) && !is(Source == enum) &&
4685 isExactSomeString!Target)
4686 {
4687 import std.array : appender;
4688 auto result = appender!Target();
4689
4690 // parse array of chars
4691 if (s.empty)
4692 throw convError!(Source, Target)(s);
4693 if (s.front == '[')
4694 {
4695 return parse!(Target, Source, doCount)(s);
4696 }
4697
4698 parseCheck!s('\"');
4699 size_t count = 1;
4700 if (s.empty)
4701 throw convError!(Source, Target)(s);
4702 if (s.front == '\"')
4703 {
4704 s.popFront();
4705 static if (doCount)
4706 {
4707 return tuple!("data", "count")(result.data, ++count);
4708 }
4709 else
4710 {
4711 return result.data;
4712 }
4713
4714 }
4715 while (true)
4716 {
4717 if (s.empty)
4718 throw parseError("Unterminated quoted string");
4719 switch (s.front)
4720 {
4721 case '\"':
4722 s.popFront();
4723 static if (doCount)
4724 {
4725 return tuple!("data", "count")(result.data, ++count);
4726 }
4727 else
4728 {
4729 return result.data;
4730 }
4731 case '\\':
4732 auto r = parseEscape!(typeof(s), Yes.doCount)(s);
4733 result.put(r[0]);
4734 count += r[1];
4735 break;
4736 default:
4737 result.put(s.front);
4738 ++count;
4739 s.popFront();
4740 break;
4741 }
4742 }
4743 assert(false, "Unexpected fallthrough");
4744 }
4745
4746 // ditto
4747 auto parseElement(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
4748 if (isInputRange!Source && isSomeChar!(ElementType!Source) && !is(Source == enum) &&
4749 is(CharTypeOf!Target == dchar) && !is(Target == enum))
4750 {
4751 Unqual!Target c;
4752
4753 parseCheck!s('\'');
4754 size_t count = 1;
4755 if (s.empty)
4756 throw convError!(Source, Target)(s);
4757 ++count; // for the following if-else sequence
4758 if (s.front != '\\')
4759 {
4760 c = s.front;
4761 s.popFront();
4762 }
4763 else
4764 c = parseEscape(s);
4765 parseCheck!s('\'');
4766 static if (doCount)
4767 {
4768 return tuple!("data", "count")(c, ++count);
4769 }
4770 else
4771 {
4772 return c;
4773 }
4774 }
4775
4776 // ditto
4777 auto parseElement(Target, Source, Flag!"doCount" doCount = No.doCount)(ref Source s)
4778 if (isInputRange!Source && isSomeChar!(ElementType!Source) &&
4779 !isSomeString!Target && !isSomeChar!Target)
4780 {
4781 return parse!(Target, Source, doCount)(s);
4782 }
4783
4784 // Use this when parsing a type that will ultimately be appended to a
4785 // string.
4786 package template WideElementType(T)
4787 {
4788 alias E = ElementType!T;
4789 static if (isSomeChar!E)
4790 alias WideElementType = dchar;
4791 else
4792 alias WideElementType = E;
4793 }
4794
4795
4796 /***************************************************************
4797 * Convenience functions for converting one or more arguments
4798 * of any type into _text (the three character widths).
4799 */
4800 string text(T...)(T args)
4801 if (T.length > 0) { return textImpl!string(args); }
4802
4803 ///ditto
4804 wstring wtext(T...)(T args)
4805 if (T.length > 0) { return textImpl!wstring(args); }
4806
4807 ///ditto
4808 dstring dtext(T...)(T args)
4809 if (T.length > 0) { return textImpl!dstring(args); }
4810
4811 ///
4812 @safe unittest
4813 {
4814 assert( text(42, ' ', 1.5, ": xyz") == "42 1.5: xyz"c);
4815 assert(wtext(42, ' ', 1.5, ": xyz") == "42 1.5: xyz"w);
4816 assert(dtext(42, ' ', 1.5, ": xyz") == "42 1.5: xyz"d);
4817 }
4818
4819 @safe unittest
4820 {
4821 char c = 'h';
4822 wchar w = '你';
4823 dchar d = 'እ';
4824
4825 assert( text(c, "ello", ' ', w, "好 ", d, "ው ሰላም ነው") == "hello 你好 እው ሰላም ነው"c);
4826 assert(wtext(c, "ello", ' ', w, "好 ", d, "ው ሰላም ነው") == "hello 你好 እው ሰላም ነው"w);
4827 assert(dtext(c, "ello", ' ', w, "好 ", d, "ው ሰላም ነው") == "hello 你好 እው ሰላም ነው"d);
4828
4829 string cs = "今日は";
4830 wstring ws = "여보세요";
4831 dstring ds = "Здравствуйте";
4832
4833 assert( text(cs, ' ', ws, " ", ds) == "今日は 여보세요 Здравствуйте"c);
4834 assert(wtext(cs, ' ', ws, " ", ds) == "今日は 여보세요 Здравствуйте"w);
4835 assert(dtext(cs, ' ', ws, " ", ds) == "今日は 여보세요 Здравствуйте"d);
4836 }
4837
4838 private S textImpl(S, U...)(U args)
4839 {
4840 static if (U.length == 0)
4841 {
4842 return null;
4843 }
4844 else static if (U.length == 1)
4845 {
4846 return to!S(args[0]);
4847 }
4848 else
4849 {
4850 import std.array : appender;
4851 import std.traits : isSomeChar, isSomeString;
4852
4853 auto app = appender!S();
4854
4855 // assume that on average, parameters will have less
4856 // than 20 elements
4857 app.reserve(U.length * 20);
4858 // Must be static foreach because of https://issues.dlang.org/show_bug.cgi?id=21209
4859 static foreach (arg; args)
4860 {
4861 static if (
4862 isSomeChar!(typeof(arg))
4863 || isSomeString!(typeof(arg))
4864 || ( isInputRange!(typeof(arg)) && isSomeChar!(ElementType!(typeof(arg))) )
4865 )
4866 app.put(arg);
4867 else static if (
4868
4869 is(immutable typeof(arg) == immutable uint) || is(immutable typeof(arg) == immutable ulong) ||
4870 is(immutable typeof(arg) == immutable int) || is(immutable typeof(arg) == immutable long)
4871 )
4872 // https://issues.dlang.org/show_bug.cgi?id=17712#c15
4873 app.put(textImpl!(S)(arg));
4874 else
4875 app.put(to!S(arg));
4876 }
4877
4878 return app.data;
4879 }
4880 }
4881
4882
4883 /***************************************************************
4884 The `octal` facility provides a means to declare a number in base 8.
4885 Using `octal!177` or `octal!"177"` for 127 represented in octal
4886 (same as 0177 in C).
4887
4888 The rules for strings are the usual for literals: If it can fit in an
4889 `int`, it is an `int`. Otherwise, it is a `long`. But, if the
4890 user specifically asks for a `long` with the `L` suffix, always
4891 give the `long`. Give an unsigned iff it is asked for with the $(D
4892 U) or `u` suffix. _Octals created from integers preserve the type
4893 of the passed-in integral.
4894
4895 See_Also:
4896 $(LREF parse) for parsing octal strings at runtime.
4897 */
4898 template octal(string num)
4899 if (isOctalLiteral(num))
4900 {
4901 static if ((octalFitsInInt!num && !literalIsLong!num) && !literalIsUnsigned!num)
4902 enum octal = octal!int(num);
4903 else static if ((!octalFitsInInt!num || literalIsLong!num) && !literalIsUnsigned!num)
4904 enum octal = octal!long(num);
4905 else static if ((octalFitsInInt!num && !literalIsLong!num) && literalIsUnsigned!num)
4906 enum octal = octal!uint(num);
4907 else static if ((!octalFitsInInt!(num) || literalIsLong!(num)) && literalIsUnsigned!(num))
4908 enum octal = octal!ulong(num);
4909 else
4910 static assert(false, "Unusable input " ~ num);
4911 }
4912
4913 /// Ditto
4914 template octal(alias decimalInteger)
4915 if (is(typeof(decimalInteger)) && isIntegral!(typeof(decimalInteger)))
4916 {
4917 enum octal = convertToOctal(decimalInteger);
4918 }
4919
4920 ///
4921 @safe unittest
4922 {
4923 // Same as 0177
4924 auto a = octal!177;
4925 // octal is a compile-time device
4926 enum b = octal!160;
4927 // Create an unsigned octal
4928 auto c = octal!"1_000_000u";
4929 // Leading zeros are allowed when converting from a string
4930 auto d = octal!"0001_200_000";
4931 }
4932
4933 /*************************************
4934 * Convert a decimal integer to an octal integer with the same digits.
4935 * Params:
4936 * i = integer to convert
4937 * Returns:
4938 * octal integer with the same type and same digits
4939 */
4940 private T convertToOctal(T)(T i)
4941 {
4942 assert((i % 10) < 8);
4943 return i ? convertToOctal(i / 10) * 8 + i % 10 : 0;
4944 }
4945
4946 /*
4947 Takes a string, num, which is an octal literal, and returns its
4948 value, in the type T specified.
4949 */
4950 private T octal(T)(const string num)
4951 {
4952 assert(isOctalLiteral(num), num ~ " is not an octal literal");
4953
4954 T value = 0;
4955
4956 foreach (const char s; num)
4957 {
4958 if (s < '0' || s > '7') // we only care about digits; skip the rest
4959 // safe to skip - this is checked out in the assert so these
4960 // are just suffixes
4961 continue;
4962
4963 value *= 8;
4964 value += s - '0';
4965 }
4966
4967 return value;
4968 }
4969
4970 @safe unittest
4971 {
4972 int a = octal!int("10");
4973 assert(a == 8);
4974
4975 int b = octal!int("000137");
4976 assert(b == 95);
4977 }
4978
4979 /*
4980 Take a look at int.max and int.max+1 in octal and the logic for this
4981 function follows directly.
4982 */
4983 private template octalFitsInInt(string octalNum)
4984 {
4985 // note it is important to strip the literal of all
4986 // non-numbers. kill the suffix and underscores lest they mess up
4987 // the number of digits here that we depend on.
4988 enum bool octalFitsInInt = strippedOctalLiteral(octalNum).length < 11 ||
4989 strippedOctalLiteral(octalNum).length == 11 &&
4990 strippedOctalLiteral(octalNum)[0] == '1';
4991 }
4992
4993 private string strippedOctalLiteral(string original)
4994 {
4995 string stripped = "";
4996 bool leading_zeros = true;
4997 foreach (c; original)
4998 {
4999 if (!('0' <= c && c <= '7'))
5000 continue;
5001 if (c == '0')
5002 {
5003 if (leading_zeros)
5004 continue;
5005 }
5006 else
5007 {
5008 leading_zeros = false;
5009 }
5010 stripped ~= c;
5011 }
5012 if (stripped.length == 0)
5013 {
5014 assert(leading_zeros);
5015 return "0";
5016 }
5017 return stripped;
5018 }
5019
5020 @safe unittest
5021 {
5022 static assert(strippedOctalLiteral("7") == "7");
5023 static assert(strippedOctalLiteral("123") == "123");
5024 static assert(strippedOctalLiteral("00123") == "123");
5025 static assert(strippedOctalLiteral("01230") == "1230");
5026 static assert(strippedOctalLiteral("0") == "0");
5027 static assert(strippedOctalLiteral("00_000") == "0");
5028 static assert(strippedOctalLiteral("000_000_12_300") == "12300");
5029 }
5030
5031 private template literalIsLong(string num)
5032 {
5033 static if (num.length > 1)
5034 // can be xxL or xxLu according to spec
5035 enum literalIsLong = (num[$-1] == 'L' || num[$-2] == 'L');
5036 else
5037 enum literalIsLong = false;
5038 }
5039
5040 private template literalIsUnsigned(string num)
5041 {
5042 static if (num.length > 1)
5043 // can be xxU or xxUL according to spec
5044 enum literalIsUnsigned = (num[$-1] == 'u' || num[$-2] == 'u')
5045 // both cases are allowed too
5046 || (num[$-1] == 'U' || num[$-2] == 'U');
5047 else
5048 enum literalIsUnsigned = false;
5049 }
5050
5051 /*
5052 Returns if the given string is a correctly formatted octal literal.
5053
5054 The format is specified in spec/lex.html. The leading zeros are allowed,
5055 but not required.
5056 */
5057 @safe pure nothrow @nogc
5058 private bool isOctalLiteral(const string num)
5059 {
5060 if (num.length == 0)
5061 return false;
5062
5063 // Must start with a digit.
5064 if (num[0] < '0' || num[0] > '7')
5065 return false;
5066
5067 foreach (i, c; num)
5068 {
5069 if (('0' <= c && c <= '7') || c == '_') // a legal character
5070 continue;
5071
5072 if (i < num.length - 2)
5073 return false;
5074
5075 // gotta check for those suffixes
5076 if (c != 'U' && c != 'u' && c != 'L')
5077 return false;
5078 if (i != num.length - 1)
5079 {
5080 // if we're not the last one, the next one must
5081 // also be a suffix to be valid
5082 char c2 = num[$-1];
5083 if (c2 != 'U' && c2 != 'u' && c2 != 'L')
5084 return false; // spam at the end of the string
5085 if (c2 == c)
5086 return false; // repeats are disallowed
5087 }
5088 }
5089
5090 return true;
5091 }
5092
5093 @safe unittest
5094 {
5095 // ensure that you get the right types, even with embedded underscores
5096 auto w = octal!"100_000_000_000";
5097 static assert(!is(typeof(w) == int));
5098 auto w2 = octal!"1_000_000_000";
5099 static assert(is(typeof(w2) == int));
5100
5101 static assert(octal!"45" == 37);
5102 static assert(octal!"0" == 0);
5103 static assert(octal!"7" == 7);
5104 static assert(octal!"10" == 8);
5105 static assert(octal!"666" == 438);
5106 static assert(octal!"0004001" == 2049);
5107 static assert(octal!"00" == 0);
5108 static assert(octal!"0_0" == 0);
5109
5110 static assert(octal!45 == 37);
5111 static assert(octal!0 == 0);
5112 static assert(octal!7 == 7);
5113 static assert(octal!10 == 8);
5114 static assert(octal!666 == 438);
5115
5116 static assert(octal!"66_6" == 438);
5117 static assert(octal!"0_0_66_6" == 438);
5118
5119 static assert(octal!2520046213 == 356535435);
5120 static assert(octal!"2520046213" == 356535435);
5121
5122 static assert(octal!17777777777 == int.max);
5123
5124 static assert(!__traits(compiles, octal!823));
5125
5126 static assert(!__traits(compiles, octal!"823"));
5127
5128 static assert(!__traits(compiles, octal!"_823"));
5129 static assert(!__traits(compiles, octal!"spam"));
5130 static assert(!__traits(compiles, octal!"77%"));
5131
5132 static assert(is(typeof(octal!"17777777777") == int));
5133 static assert(octal!"17777777777" == int.max);
5134
5135 static assert(is(typeof(octal!"20000000000U") == ulong)); // Shouldn't this be uint?
5136 static assert(octal!"20000000000" == uint(int.max) + 1);
5137
5138 static assert(is(typeof(octal!"777777777777777777777") == long));
5139 static assert(octal!"777777777777777777777" == long.max);
5140
5141 static assert(is(typeof(octal!"1000000000000000000000U") == ulong));
5142 static assert(octal!"1000000000000000000000" == ulong(long.max) + 1);
5143
5144 int a;
5145 long b;
5146
5147 // biggest value that should fit in an it
5148 a = octal!"17777777777";
5149 assert(a == int.max);
5150 // should not fit in the int
5151 static assert(!__traits(compiles, a = octal!"20000000000"));
5152 // ... but should fit in a long
5153 b = octal!"20000000000";
5154 assert(b == 1L + int.max);
5155
5156 b = octal!"1L";
5157 assert(b == 1);
5158 b = octal!1L;
5159 assert(b == 1);
5160 }
5161
5162 // emplace() used to be here but was moved to druntime
5163 public import core.lifetime : emplace;
5164
5165 // https://issues.dlang.org/show_bug.cgi?id=9559
5166 @safe unittest
5167 {
5168 import std.algorithm.iteration : map;
5169 import std.array : array;
5170 import std.typecons : Nullable;
5171 alias I = Nullable!int;
5172 auto ints = [0, 1, 2].map!(i => i & 1 ? I.init : I(i))();
5173 auto asArray = array(ints);
5174 }
5175
5176 @system unittest //http://forum.dlang.org/post/[email protected]
5177 {
5178 import std.array : array;
5179 import std.datetime : SysTime, UTC;
5180 import std.math.traits : isNaN;
5181
5182 static struct A
5183 {
5184 double i;
5185 }
5186
5187 static struct B
5188 {
5189 invariant()
5190 {
5191 if (j == 0)
5192 assert(a.i.isNaN(), "why is 'j' zero?? and i is not NaN?");
5193 else
5194 assert(!a.i.isNaN());
5195 }
5196 SysTime when; // comment this line avoid the breakage
5197 int j;
5198 A a;
5199 }
5200
5201 B b1 = B.init;
5202 assert(&b1); // verify that default eyes invariants are ok;
5203
5204 auto b2 = B(SysTime(0, UTC()), 1, A(1));
5205 assert(&b2);
5206 auto b3 = B(SysTime(0, UTC()), 1, A(1));
5207 assert(&b3);
5208
5209 auto arr = [b2, b3];
5210
5211 assert(arr[0].j == 1);
5212 assert(arr[1].j == 1);
5213 auto a2 = arr.array(); // << bang, invariant is raised, also if b2 and b3 are good
5214 }
5215
5216 @safe unittest
5217 {
5218 import std.algorithm.comparison : equal;
5219 import std.algorithm.iteration : map;
5220 // Check fix for https://issues.dlang.org/show_bug.cgi?id=2971
5221 assert(equal(map!(to!int)(["42", "34", "345"]), [42, 34, 345]));
5222 }
5223
5224 // Undocumented for the time being
5225 void toTextRange(T, W)(T value, W writer)
5226 if (isIntegral!T && isOutputRange!(W, char))
5227 {
5228 import core.internal.string : SignedStringBuf, signedToTempString,
5229 UnsignedStringBuf, unsignedToTempString;
5230
5231 if (value < 0)
5232 {
5233 SignedStringBuf buf = void;
5234 put(writer, signedToTempString(value, buf));
5235 }
5236 else
5237 {
5238 UnsignedStringBuf buf = void;
5239 put(writer, unsignedToTempString(value, buf));
5240 }
5241 }
5242
5243 @safe unittest
5244 {
5245 import std.array : appender;
5246 auto result = appender!(char[])();
5247 toTextRange(-1, result);
5248 assert(result.data == "-1");
5249 }
5250
5251
5252 /**
5253 Returns the corresponding _unsigned value for `x` (e.g. if `x` has type
5254 `int`, it returns $(D cast(uint) x)). The advantage compared to the cast
5255 is that you do not need to rewrite the cast if `x` later changes type
5256 (e.g from `int` to `long`).
5257
5258 Note that the result is always mutable even if the original type was const
5259 or immutable. In order to retain the constness, use $(REF Unsigned, std,traits).
5260 */
5261 auto unsigned(T)(T x)
5262 if (isIntegral!T)
5263 {
5264 return cast() cast(Unsigned!T) x;
5265 }
5266
5267 ///
5268 @safe unittest
5269 {
5270 import std.traits : Unsigned;
5271 immutable int s = 42;
5272 auto u1 = unsigned(s); //not qualified
5273 static assert(is(typeof(u1) == uint));
5274 Unsigned!(typeof(s)) u2 = unsigned(s); //same qualification
5275 static assert(is(typeof(u2) == immutable uint));
5276 immutable u3 = unsigned(s); //explicitly qualified
5277 }
5278
5279 /// Ditto
5280 auto unsigned(T)(T x)
5281 if (isSomeChar!T)
5282 {
5283 // All characters are unsigned
5284 static assert(T.min == 0, T.stringof ~ ".min must be zero");
5285 return cast() x;
5286 }
5287
5288 @safe unittest
5289 {
5290 static foreach (T; AliasSeq!(byte, ubyte))
5291 {
5292 static assert(is(typeof(unsigned(cast(T) 1)) == ubyte));
5293 static assert(is(typeof(unsigned(cast(const T) 1)) == ubyte));
5294 static assert(is(typeof(unsigned(cast(immutable T) 1)) == ubyte));
5295 }
5296
5297 static foreach (T; AliasSeq!(short, ushort))
5298 {
5299 static assert(is(typeof(unsigned(cast(T) 1)) == ushort));
5300 static assert(is(typeof(unsigned(cast(const T) 1)) == ushort));
5301 static assert(is(typeof(unsigned(cast(immutable T) 1)) == ushort));
5302 }
5303
5304 static foreach (T; AliasSeq!(int, uint))
5305 {
5306 static assert(is(typeof(unsigned(cast(T) 1)) == uint));
5307 static assert(is(typeof(unsigned(cast(const T) 1)) == uint));
5308 static assert(is(typeof(unsigned(cast(immutable T) 1)) == uint));
5309 }
5310
5311 static foreach (T; AliasSeq!(long, ulong))
5312 {
5313 static assert(is(typeof(unsigned(cast(T) 1)) == ulong));
5314 static assert(is(typeof(unsigned(cast(const T) 1)) == ulong));
5315 static assert(is(typeof(unsigned(cast(immutable T) 1)) == ulong));
5316 }
5317 }
5318
5319 @safe unittest
5320 {
5321 static foreach (T; AliasSeq!(char, wchar, dchar))
5322 {
5323 static assert(is(typeof(unsigned(cast(T)'A')) == T));
5324 static assert(is(typeof(unsigned(cast(const T)'A')) == T));
5325 static assert(is(typeof(unsigned(cast(immutable T)'A')) == T));
5326 }
5327 }
5328
5329
5330 /**
5331 Returns the corresponding _signed value for `x` (e.g. if `x` has type
5332 `uint`, it returns $(D cast(int) x)). The advantage compared to the cast
5333 is that you do not need to rewrite the cast if `x` later changes type
5334 (e.g from `uint` to `ulong`).
5335
5336 Note that the result is always mutable even if the original type was const
5337 or immutable. In order to retain the constness, use $(REF Signed, std,traits).
5338 */
5339 auto signed(T)(T x)
5340 if (isIntegral!T)
5341 {
5342 return cast() cast(Signed!T) x;
5343 }
5344
5345 ///
5346 @safe unittest
5347 {
5348 import std.traits : Signed;
5349
5350 immutable uint u = 42;
5351 auto s1 = signed(u); //not qualified
5352 static assert(is(typeof(s1) == int));
5353 Signed!(typeof(u)) s2 = signed(u); //same qualification
5354 static assert(is(typeof(s2) == immutable int));
5355 immutable s3 = signed(u); //explicitly qualified
5356 }
5357
5358 @system unittest
5359 {
5360 static foreach (T; AliasSeq!(byte, ubyte))
5361 {
5362 static assert(is(typeof(signed(cast(T) 1)) == byte));
5363 static assert(is(typeof(signed(cast(const T) 1)) == byte));
5364 static assert(is(typeof(signed(cast(immutable T) 1)) == byte));
5365 }
5366
5367 static foreach (T; AliasSeq!(short, ushort))
5368 {
5369 static assert(is(typeof(signed(cast(T) 1)) == short));
5370 static assert(is(typeof(signed(cast(const T) 1)) == short));
5371 static assert(is(typeof(signed(cast(immutable T) 1)) == short));
5372 }
5373
5374 static foreach (T; AliasSeq!(int, uint))
5375 {
5376 static assert(is(typeof(signed(cast(T) 1)) == int));
5377 static assert(is(typeof(signed(cast(const T) 1)) == int));
5378 static assert(is(typeof(signed(cast(immutable T) 1)) == int));
5379 }
5380
5381 static foreach (T; AliasSeq!(long, ulong))
5382 {
5383 static assert(is(typeof(signed(cast(T) 1)) == long));
5384 static assert(is(typeof(signed(cast(const T) 1)) == long));
5385 static assert(is(typeof(signed(cast(immutable T) 1)) == long));
5386 }
5387 }
5388
5389 // https://issues.dlang.org/show_bug.cgi?id=10874
5390 @safe unittest
5391 {
5392 enum Test { a = 0 }
5393 ulong l = 0;
5394 auto t = l.to!Test;
5395 }
5396
5397 // asOriginalType
5398 /**
5399 Returns the representation of an enumerated value, i.e. the value converted to
5400 the base type of the enumeration.
5401 */
5402 OriginalType!E asOriginalType(E)(E value)
5403 if (is(E == enum))
5404 {
5405 return value;
5406 }
5407
5408 ///
5409 @safe unittest
5410 {
5411 enum A { a = 42 }
5412 static assert(is(typeof(A.a.asOriginalType) == int));
5413 assert(A.a.asOriginalType == 42);
5414 enum B : double { a = 43 }
5415 static assert(is(typeof(B.a.asOriginalType) == double));
5416 assert(B.a.asOriginalType == 43);
5417 }
5418
5419 /**
5420 A wrapper on top of the built-in cast operator that allows one to restrict
5421 casting of the original type of the value.
5422
5423 A common issue with using a raw cast is that it may silently continue to
5424 compile even if the value's type has changed during refactoring,
5425 which breaks the initial assumption about the cast.
5426
5427 Params:
5428 From = The type to cast from. The programmer must ensure it is legal
5429 to make this cast.
5430 */
5431 template castFrom(From)
5432 {
5433 /**
5434 Params:
5435 To = The type _to cast _to.
5436 value = The value _to cast. It must be of type `From`,
5437 otherwise a compile-time error is emitted.
5438
5439 Returns:
5440 the value after the cast, returned by reference if possible.
5441 */
5442 auto ref to(To, T)(auto ref T value) @system
5443 {
5444 static assert(
5445 is(From == T),
5446 "the value to cast is not of specified type '" ~ From.stringof ~
5447 "', it is of type '" ~ T.stringof ~ "'"
5448 );
5449
5450 static assert(
5451 is(typeof(cast(To) value)),
5452 "can't cast from '" ~ From.stringof ~ "' to '" ~ To.stringof ~ "'"
5453 );
5454
5455 return cast(To) value;
5456 }
5457 }
5458
5459 ///
5460 @system unittest
5461 {
5462 // Regular cast, which has been verified to be legal by the programmer:
5463 {
5464 long x;
5465 auto y = cast(int) x;
5466 }
5467
5468 // However this will still compile if 'x' is changed to be a pointer:
5469 {
5470 long* x;
5471 auto y = cast(int) x;
5472 }
5473
5474 // castFrom provides a more reliable alternative to casting:
5475 {
5476 long x;
5477 auto y = castFrom!long.to!int(x);
5478 }
5479
5480 // Changing the type of 'x' will now issue a compiler error,
5481 // allowing bad casts to be caught before it's too late:
5482 {
5483 long* x;
5484 static assert(
5485 !__traits(compiles, castFrom!long.to!int(x))
5486 );
5487
5488 // if cast is still needed, must be changed to:
5489 auto y = castFrom!(long*).to!int(x);
5490 }
5491 }
5492
5493 // https://issues.dlang.org/show_bug.cgi?id=16667
5494 @system unittest
5495 {
5496 ubyte[] a = ['a', 'b', 'c'];
5497 assert(castFrom!(ubyte[]).to!(string)(a) == "abc");
5498 }
5499
5500 /**
5501 Check the correctness of a string for `hexString`.
5502 The result is true if and only if the input string is composed of whitespace
5503 characters (\f\n\r\t\v lineSep paraSep nelSep) and
5504 an even number of hexadecimal digits (regardless of the case).
5505 */
5506 @safe pure @nogc
5507 private bool isHexLiteral(String)(scope const String hexData)
5508 {
5509 import std.ascii : isHexDigit;
5510 import std.uni : lineSep, paraSep, nelSep;
5511 size_t i;
5512 foreach (const dchar c; hexData)
5513 {
5514 switch (c)
5515 {
5516 case ' ':
5517 case '\t':
5518 case '\v':
5519 case '\f':
5520 case '\r':
5521 case '\n':
5522 case lineSep:
5523 case paraSep:
5524 case nelSep:
5525 continue;
5526
5527 default:
5528 break;
5529 }
5530 if (c.isHexDigit)
5531 ++i;
5532 else
5533 return false;
5534 }
5535 return !(i & 1);
5536 }
5537
5538 @safe unittest
5539 {
5540 // test all the hex digits
5541 static assert( ("0123456789abcdefABCDEF").isHexLiteral);
5542 // empty or white strings are not valid
5543 static assert( "\r\n\t".isHexLiteral);
5544 // but are accepted if the count of hex digits is even
5545 static assert( "A\r\n\tB".isHexLiteral);
5546 }
5547
5548 @safe unittest
5549 {
5550 import std.ascii;
5551 // empty/whites
5552 static assert( "".isHexLiteral);
5553 static assert( " \r".isHexLiteral);
5554 static assert( whitespace.isHexLiteral);
5555 static assert( ""w.isHexLiteral);
5556 static assert( " \r"w.isHexLiteral);
5557 static assert( ""d.isHexLiteral);
5558 static assert( " \r"d.isHexLiteral);
5559 static assert( "\u2028\u2029\u0085"d.isHexLiteral);
5560 // odd x strings
5561 static assert( !("5" ~ whitespace).isHexLiteral);
5562 static assert( !"123".isHexLiteral);
5563 static assert( !"1A3".isHexLiteral);
5564 static assert( !"1 23".isHexLiteral);
5565 static assert( !"\r\n\tC".isHexLiteral);
5566 static assert( !"123"w.isHexLiteral);
5567 static assert( !"1A3"w.isHexLiteral);
5568 static assert( !"1 23"w.isHexLiteral);
5569 static assert( !"\r\n\tC"w.isHexLiteral);
5570 static assert( !"123"d.isHexLiteral);
5571 static assert( !"1A3"d.isHexLiteral);
5572 static assert( !"1 23"d.isHexLiteral);
5573 static assert( !"\r\n\tC"d.isHexLiteral);
5574 // even x strings with invalid charset
5575 static assert( !"12gG".isHexLiteral);
5576 static assert( !"2A 3q".isHexLiteral);
5577 static assert( !"12gG"w.isHexLiteral);
5578 static assert( !"2A 3q"w.isHexLiteral);
5579 static assert( !"12gG"d.isHexLiteral);
5580 static assert( !"2A 3q"d.isHexLiteral);
5581 // valid x strings
5582 static assert( ("5A" ~ whitespace).isHexLiteral);
5583 static assert( ("5A 01A C FF de 1b").isHexLiteral);
5584 static assert( ("0123456789abcdefABCDEF").isHexLiteral);
5585 static assert( (" 012 34 5 6789 abcd ef\rAB\nCDEF").isHexLiteral);
5586 static assert( ("5A 01A C FF de 1b"w).isHexLiteral);
5587 static assert( ("0123456789abcdefABCDEF"w).isHexLiteral);
5588 static assert( (" 012 34 5 6789 abcd ef\rAB\nCDEF"w).isHexLiteral);
5589 static assert( ("5A 01A C FF de 1b"d).isHexLiteral);
5590 static assert( ("0123456789abcdefABCDEF"d).isHexLiteral);
5591 static assert( (" 012 34 5 6789 abcd ef\rAB\nCDEF"d).isHexLiteral);
5592 // library version allows what's pointed by https://issues.dlang.org/show_bug.cgi?id=10454
5593 static assert( ("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").isHexLiteral);
5594 }
5595
5596 /**
5597 Converts a hex literal to a string at compile time.
5598
5599 Takes a string made of hexadecimal digits and returns
5600 the matching string by converting each pair of digits to a character.
5601 The input string can also include white characters, which can be used
5602 to keep the literal string readable in the source code.
5603
5604 The function is intended to replace the hexadecimal literal strings
5605 starting with `'x'`, which could be removed to simplify the core language.
5606
5607 Params:
5608 hexData = string to be converted.
5609
5610 Returns:
5611 a `string`, a `wstring` or a `dstring`, according to the type of hexData.
5612
5613 See_Also:
5614 Use $(REF fromHexString, std, digest) for run time conversions.
5615 Note, these functions are not drop-in replacements and have different
5616 input requirements.
5617 This template inherits its data syntax from builtin
5618 $(LINK2 $(ROOT_DIR)spec/lex.html#hex_string, hex strings).
5619 See $(REF fromHexString, std, digest) for its own respective requirements.
5620 */
5621 template hexString(string hexData)
5622 if (hexData.isHexLiteral)
5623 {
5624 enum hexString = mixin(hexToString(hexData));
5625 }
5626
5627 /// ditto
5628 template hexString(wstring hexData)
5629 if (hexData.isHexLiteral)
5630 {
5631 enum wstring hexString = mixin(hexToString(hexData));
5632 }
5633
5634 /// ditto
5635 template hexString(dstring hexData)
5636 if (hexData.isHexLiteral)
5637 {
5638 enum dstring hexString = mixin(hexToString(hexData));
5639 }
5640
5641 ///
5642 @safe unittest
5643 {
5644 // conversion at compile time
5645 auto string1 = hexString!"304A314B";
5646 assert(string1 == "0J1K");
5647 auto string2 = hexString!"304A314B"w;
5648 assert(string2 == "0J1K"w);
5649 auto string3 = hexString!"304A314B"d;
5650 assert(string3 == "0J1K"d);
5651 }
5652
5653 @safe nothrow pure private
5654 {
5655 /* These are meant to be used with CTFE.
5656 * They cause the instantiations of hexStrLiteral()
5657 * to be in Phobos, not user code.
5658 */
5659 string hexToString(string s)
5660 {
5661 return hexStrLiteral(s);
5662 }
5663
5664 wstring hexToString(wstring s)
5665 {
5666 return hexStrLiteral(s);
5667 }
5668
5669 dstring hexToString(dstring s)
5670 {
5671 return hexStrLiteral(s);
5672 }
5673 }
5674
5675 /*
5676 Turn a hexadecimal string into a regular string literal.
5677 I.e. "dead beef" is transformed into "\xde\xad\xbe\xef"
5678 suitable for use in a mixin.
5679 Params:
5680 hexData is string, wstring, or dstring and validated by isHexLiteral()
5681 */
5682 @trusted nothrow pure
5683 private auto hexStrLiteral(String)(scope String hexData)
5684 {
5685 import std.ascii : isHexDigit;
5686 alias C = Unqual!(ElementEncodingType!String); // char, wchar or dchar
5687 C[] result;
5688 result.length = 1 + hexData.length * 2 + 1; // don't forget the " "
5689 /* Use a pointer because we know it won't overrun,
5690 * and this will reduce the size of the function substantially
5691 * by not doing the array bounds checks.
5692 * This is why this function is @trusted.
5693 */
5694 auto r = result.ptr;
5695 r[0] = '"';
5696 size_t cnt = 0;
5697 foreach (c; hexData)
5698 {
5699 if (c.isHexDigit)
5700 {
5701 if ((cnt & 1) == 0)
5702 {
5703 r[1 + cnt] = '\\';
5704 r[1 + cnt + 1] = 'x';
5705 cnt += 2;
5706 }
5707 r[1 + cnt] = c;
5708 ++cnt;
5709 }
5710 }
5711 r[1 + cnt] = '"';
5712 result.length = 1 + cnt + 1; // trim off any excess length
5713 return result;
5714 }
5715
5716
5717 @safe unittest
5718 {
5719 // compile time
5720 assert(hexString!"46 47 48 49 4A 4B" == "FGHIJK");
5721 assert(hexString!"30\r\n\t\f\v31 32 33 32 31 30" == "0123210");
5722 assert(hexString!"ab cd" == hexString!"ABCD");
5723 }
5724
5725
5726 /**
5727 * Convert integer to a range of characters.
5728 * Intended to be lightweight and fast.
5729 *
5730 * Params:
5731 * radix = 2, 8, 10, 16
5732 * Char = character type for output
5733 * letterCase = lower for deadbeef, upper for DEADBEEF
5734 * value = integer to convert. Can be ubyte, ushort, uint or ulong. If radix
5735 * is 10, can also be byte, short, int or long.
5736 * Returns:
5737 * Random access range with slicing and everything
5738 */
5739
5740 auto toChars(ubyte radix = 10, Char = char, LetterCase letterCase = LetterCase.lower, T)(T value)
5741 pure nothrow @nogc @safe
5742 if ((radix == 2 || radix == 8 || radix == 10 || radix == 16) &&
5743 isIntegral!T && (radix == 10 || isUnsigned!T))
5744 {
5745 alias UT = Unqual!T;
5746
5747 static if (radix == 10)
5748 {
5749 /* uint.max is 42_9496_7295
5750 * int.max is 21_4748_3647
5751 * ulong.max is 1844_6744_0737_0955_1615
5752 * long.max is 922_3372_0368_5477_5807
5753 */
5754 static struct Result
5755 {
5756 void initialize(UT value)
5757 {
5758 import core.internal.string : signedToTempString, unsignedToTempString;
5759
5760 char[] t = value < 0
5761 ? signedToTempString!(10, false, char)(value, buf)
5762 : unsignedToTempString!(10, false, char)(value, buf);
5763
5764 lwr = cast(uint) (buf.length - t.length);
5765 upr = cast(uint) buf.length;
5766 }
5767
5768 @property size_t length() { return upr - lwr; }
5769
5770 alias opDollar = length;
5771
5772 @property bool empty() { return upr == lwr; }
5773
5774 @property Char front() { return buf[lwr]; }
5775
5776 void popFront() { ++lwr; }
5777
5778 @property Char back() { return buf[upr - 1]; }
5779
5780 void popBack() { --upr; }
5781
5782 @property Result save() { return this; }
5783
5784 Char opIndex(size_t i) { return buf[lwr + i]; }
5785
5786 Result opSlice(size_t lwr, size_t upr)
5787 {
5788 Result result = void;
5789 result.buf = buf;
5790 result.lwr = cast(uint)(this.lwr + lwr);
5791 result.upr = cast(uint)(this.lwr + upr);
5792 return result;
5793 }
5794
5795 private:
5796 uint lwr = void, upr = void;
5797 char[(UT.sizeof == 4) ? 10 + isSigned!T : 20] buf = void;
5798 }
5799
5800 Result result;
5801 result.initialize(value);
5802 return result;
5803 }
5804 else
5805 {
5806 static if (radix == 2)
5807 enum SHIFT = 1;
5808 else static if (radix == 8)
5809 enum SHIFT = 3;
5810 else static if (radix == 16)
5811 enum SHIFT = 4;
5812 else
5813 static assert(false, "radix must be 2, 8, 10, or 16");
5814 static struct Result
5815 {
5816 this(UT value)
5817 {
5818 this.value = value;
5819
5820 ubyte len = 1;
5821 while (value >>>= SHIFT)
5822 ++len;
5823 this.len = len;
5824 }
5825
5826 @property size_t length() { return len; }
5827
5828 @property bool empty() { return len == 0; }
5829
5830 @property Char front() { return opIndex(0); }
5831
5832 void popFront() { --len; }
5833
5834 @property Char back() { return opIndex(len - 1); }
5835
5836 void popBack()
5837 {
5838 value >>>= SHIFT;
5839 --len;
5840 }
5841
5842 @property Result save() { return this; }
5843
5844 Char opIndex(size_t i)
5845 {
5846 Char c = (value >>> ((len - i - 1) * SHIFT)) & ((1 << SHIFT) - 1);
5847 return cast(Char)((radix < 10 || c < 10) ? c + '0'
5848 : (letterCase == LetterCase.upper ? c + 'A' - 10
5849 : c + 'a' - 10));
5850 }
5851
5852 Result opSlice(size_t lwr, size_t upr)
5853 {
5854 Result result = void;
5855 result.value = value >>> ((len - upr) * SHIFT);
5856 result.len = cast(ubyte)(upr - lwr);
5857 return result;
5858 }
5859
5860 private:
5861 UT value;
5862 ubyte len;
5863 }
5864
5865 return Result(value);
5866 }
5867 }
5868
5869 ///
5870 @safe unittest
5871 {
5872 import std.algorithm.comparison : equal;
5873
5874 assert(toChars(1).equal("1"));
5875 assert(toChars(1_000_000).equal("1000000"));
5876
5877 assert(toChars!(2)(2U).equal("10"));
5878 assert(toChars!(16)(255U).equal("ff"));
5879 assert(toChars!(16, char, LetterCase.upper)(255U).equal("FF"));
5880 }
5881
5882
5883 @safe unittest
5884 {
5885 import std.array;
5886 import std.range;
5887
5888 assert(toChars(123) == toChars(123));
5889
5890 {
5891 assert(toChars!2(ubyte(0)).array == "0");
5892 assert(toChars!2(ushort(0)).array == "0");
5893 assert(toChars!2(0u).array == "0");
5894 assert(toChars!2(0Lu).array == "0");
5895 assert(toChars!2(ubyte(1)).array == "1");
5896 assert(toChars!2(ushort(1)).array == "1");
5897 assert(toChars!2(1u).array == "1");
5898 assert(toChars!2(1Lu).array == "1");
5899
5900 auto r = toChars!2(2u);
5901 assert(r.length == 2);
5902 assert(r[0] == '1');
5903 assert(r[1 .. 2].array == "0");
5904 auto s = r.save;
5905 assert(r.array == "10");
5906 assert(s.retro.array == "01");
5907 }
5908 {
5909 assert(toChars!8(ubyte(0)).array == "0");
5910 assert(toChars!8(ushort(0)).array == "0");
5911 assert(toChars!8(0u).array == "0");
5912 assert(toChars!8(0Lu).array == "0");
5913 assert(toChars!8(1u).array == "1");
5914 assert(toChars!8(1234567Lu).array == "4553207");
5915 assert(toChars!8(ubyte.max).array == "377");
5916 assert(toChars!8(ushort.max).array == "177777");
5917
5918 auto r = toChars!8(8u);
5919 assert(r.length == 2);
5920 assert(r[0] == '1');
5921 assert(r[1 .. 2].array == "0");
5922 auto s = r.save;
5923 assert(r.array == "10");
5924 assert(s.retro.array == "01");
5925 }
5926 {
5927 assert(toChars!10(ubyte(0)).array == "0");
5928 assert(toChars!10(ushort(0)).array == "0");
5929 assert(toChars!10(0u).array == "0");
5930 assert(toChars!10(0Lu).array == "0");
5931 assert(toChars!10(1u).array == "1");
5932 assert(toChars!10(1234567Lu).array == "1234567");
5933 assert(toChars!10(ubyte.max).array == "255");
5934 assert(toChars!10(ushort.max).array == "65535");
5935 assert(toChars!10(uint.max).array == "4294967295");
5936 assert(toChars!10(ulong.max).array == "18446744073709551615");
5937
5938 auto r = toChars(10u);
5939 assert(r.length == 2);
5940 assert(r[0] == '1');
5941 assert(r[1 .. 2].array == "0");
5942 auto s = r.save;
5943 assert(r.array == "10");
5944 assert(s.retro.array == "01");
5945 }
5946 {
5947 assert(toChars!10(0).array == "0");
5948 assert(toChars!10(0L).array == "0");
5949 assert(toChars!10(1).array == "1");
5950 assert(toChars!10(1234567L).array == "1234567");
5951 assert(toChars!10(byte.max).array == "127");
5952 assert(toChars!10(short.max).array == "32767");
5953 assert(toChars!10(int.max).array == "2147483647");
5954 assert(toChars!10(long.max).array == "9223372036854775807");
5955 assert(toChars!10(-byte.max).array == "-127");
5956 assert(toChars!10(-short.max).array == "-32767");
5957 assert(toChars!10(-int.max).array == "-2147483647");
5958 assert(toChars!10(-long.max).array == "-9223372036854775807");
5959 assert(toChars!10(byte.min).array == "-128");
5960 assert(toChars!10(short.min).array == "-32768");
5961 assert(toChars!10(int.min).array == "-2147483648");
5962 assert(toChars!10(long.min).array == "-9223372036854775808");
5963
5964 auto r = toChars!10(10);
5965 assert(r.length == 2);
5966 assert(r[0] == '1');
5967 assert(r[1 .. 2].array == "0");
5968 auto s = r.save;
5969 assert(r.array == "10");
5970 assert(s.retro.array == "01");
5971 }
5972 {
5973 assert(toChars!(16)(0u).array == "0");
5974 assert(toChars!(16)(0Lu).array == "0");
5975 assert(toChars!(16)(10u).array == "a");
5976 assert(toChars!(16, char, LetterCase.upper)(0x12AF34567Lu).array == "12AF34567");
5977 assert(toChars!(16)(ubyte(0)).array == "0");
5978 assert(toChars!(16)(ushort(0)).array == "0");
5979 assert(toChars!(16)(ubyte.max).array == "ff");
5980 assert(toChars!(16)(ushort.max).array == "ffff");
5981
5982 auto r = toChars!(16)(16u);
5983 assert(r.length == 2);
5984 assert(r[0] == '1');
5985 assert(r[1 .. 2].array == "0");
5986 auto s = r.save;
5987 assert(r.array == "10");
5988 assert(s.retro.array == "01");
5989 }
5990 }
5991
5992 @safe unittest // opSlice (https://issues.dlang.org/show_bug.cgi?id=16192)
5993 {
5994 import std.meta : AliasSeq;
5995
5996 static struct Test { ubyte radix; uint number; }
5997
5998 alias tests = AliasSeq!(
5999 Test(2, 0b1_0110_0111u),
6000 Test(2, 0b10_1100_1110u),
6001 Test(8, octal!123456701u),
6002 Test(8, octal!1234567012u),
6003 Test(10, 123456789u),
6004 Test(10, 1234567890u),
6005 Test(16, 0x789ABCDu),
6006 Test(16, 0x789ABCDEu),
6007 );
6008
6009 foreach (test; tests)
6010 {
6011 enum ubyte radix = test.radix;
6012 auto original = toChars!radix(test.number);
6013
6014 // opSlice vs popFront
6015 auto r = original.save;
6016 size_t i = 0;
6017 for (; !r.empty; r.popFront(), ++i)
6018 {
6019 assert(original[i .. original.length].tupleof == r.tupleof);
6020 // tupleof is used to work around https://issues.dlang.org/show_bug.cgi?id=16216.
6021 }
6022
6023 // opSlice vs popBack
6024 r = original.save;
6025 i = 0;
6026 for (; !r.empty; r.popBack(), ++i)
6027 {
6028 assert(original[0 .. original.length - i].tupleof == r.tupleof);
6029 }
6030
6031 // opSlice vs both popFront and popBack
6032 r = original.save;
6033 i = 0;
6034 for (; r.length >= 2; r.popFront(), r.popBack(), ++i)
6035 {
6036 assert(original[i .. original.length - i].tupleof == r.tupleof);
6037 }
6038 }
6039 }
6040
6041 // Converts an unsigned integer to a compile-time string constant.
6042 package enum toCtString(ulong n) = n.stringof[0 .. $ - "LU".length];
6043
6044 // Check that .stringof does what we expect, since it's not guaranteed by the
6045 // language spec.
6046 @safe /*@betterC*/ unittest
6047 {
6048 assert(toCtString!0 == "0");
6049 assert(toCtString!123456 == "123456");
6050 }
6051
6052 /**
6053 * Takes the raw bits of a value and reinterprets them as a different type.
6054 *
6055 * Params:
6056 * T = the new type.
6057 * value = the value to reinterpret.
6058 *
6059 * Returns: a reference to the reinterpreted value.
6060 */
6061 pragma(inline, true)
6062 ref T bitCast(T, S)(ref S value)
6063 if (T.sizeof <= S.sizeof)
6064 {
6065 return *cast(T*) &value;
6066 }
6067
6068 ///
6069 @safe unittest
6070 {
6071 uint n = 0xDEADBEEF;
6072
6073 version (LittleEndian)
6074 assert(n.bitCast!(ubyte[4]) == [0xEF, 0xBE, 0xAD, 0xDE]);
6075 version (BigEndian)
6076 assert(n.bitCast!(ubyte[4]) == [0xDE, 0xAD, 0xBE, 0xEF]);
6077 }
6078
6079 // Sizes must be compatible
6080 @safe unittest
6081 {
6082 uint n;
6083
6084 assert(!__traits(compiles, n.bitCast!ulong));
6085 }