/
conv.d
5354 lines (4772 loc) · 140 KB
/
conv.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
A one-stop shop for converting values from one type to another.
Copyright: Copyright Digital Mars 2007-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu),
Shin Fujishiro,
Adam D. Ruppe,
Kenji Hara
Source: $(PHOBOSSRC std/_conv.d)
Macros:
WIKI = Phobos/StdConv
*/
module std.conv;
public import std.ascii : LetterCase;
import std.range.primitives;
import std.traits;
import std.typetuple;
private string convFormat(Char, Args...)(in Char[] fmt, Args args)
{
import std.format : format;
return std.format.format(fmt, args);
}
/* ************* Exceptions *************** */
/**
* Thrown on conversion errors.
*/
class ConvException : Exception
{
@safe pure nothrow
this(string s, string fn = __FILE__, size_t ln = __LINE__)
{
super(s, fn, ln);
}
}
private string convError_unexpected(S)(S source)
{
return source.empty ? "end of input" : text("'", source.front, "'");
}
private auto convError(S, T)(S source, string fn = __FILE__, size_t ln = __LINE__)
{
return new ConvException(
text("Unexpected ", convError_unexpected(source),
" when converting from type "~S.stringof~" to type "~T.stringof),
fn, ln);
}
private auto convError(S, T)(S source, int radix, string fn = __FILE__, size_t ln = __LINE__)
{
return new ConvException(
text("Unexpected ", convError_unexpected(source),
" when converting from type "~S.stringof~" base ", radix,
" to type "~T.stringof),
fn, ln);
}
@safe pure/* nothrow*/ // lazy parameter bug
private auto parseError(lazy string msg, string fn = __FILE__, size_t ln = __LINE__)
{
return new ConvException(text("Can't parse string: ", msg), fn, ln);
}
private void parseCheck(alias source)(dchar c, string fn = __FILE__, size_t ln = __LINE__)
{
if (source.empty)
throw parseError(text("unexpected end of input when expecting", "\"", c, "\""));
if (source.front != c)
throw parseError(text("\"", c, "\" is missing"), fn, ln);
source.popFront();
}
private
{
template isImaginary(T)
{
enum bool isImaginary = staticIndexOf!(Unqual!T,
ifloat, idouble, ireal) >= 0;
}
template isComplex(T)
{
enum bool isComplex = staticIndexOf!(Unqual!T,
cfloat, cdouble, creal) >= 0;
}
template isNarrowInteger(T)
{
enum bool isNarrowInteger = staticIndexOf!(Unqual!T,
byte, ubyte, short, ushort) >= 0;
}
T toStr(T, S)(S src)
if (isSomeString!T)
{
// workaround for Bugzilla 14198
static if (is(S == bool) && is(typeof({ T s = "string"; })))
{
return src ? "true" : "false";
}
else
{
import std.format : FormatSpec, formatValue;
import std.array : appender;
auto w = appender!T();
FormatSpec!(ElementEncodingType!T) f;
formatValue(w, src, f);
return w.data;
}
}
template isExactSomeString(T)
{
enum isExactSomeString = isSomeString!T && !is(T == enum);
}
template isEnumStrToStr(S, T)
{
enum isEnumStrToStr = isImplicitlyConvertible!(S, T) &&
is(S == enum) && isExactSomeString!T;
}
template isNullToStr(S, T)
{
enum isNullToStr = isImplicitlyConvertible!(S, T) &&
(is(Unqual!S == typeof(null))) && isExactSomeString!T;
}
template isRawStaticArray(T, A...)
{
enum isRawStaticArray =
A.length == 0 &&
isStaticArray!T &&
!is(T == class) &&
!is(T == interface) &&
!is(T == struct) &&
!is(T == union);
}
}
/**
* Thrown on conversion overflow errors.
*/
class ConvOverflowException : ConvException
{
@safe pure nothrow
this(string s, string fn = __FILE__, size_t ln = __LINE__)
{
super(s, fn, ln);
}
}
/**
The $(D_PARAM to) family of functions converts a value from type
$(D_PARAM Source) to type $(D_PARAM Target). The source type is
deduced and the target type must be specified, for example the
expression $(D_PARAM to!int(42.0)) converts the number 42 from
$(D_PARAM double) to $(D_PARAM int). The conversion is "safe", i.e.,
it checks for overflow; $(D_PARAM to!int(4.2e10)) would throw the
$(D_PARAM ConvOverflowException) exception. Overflow checks are only
inserted when necessary, e.g., $(D_PARAM to!double(42)) does not do
any checking because any int fits in a double.
Converting a value to its own type (useful mostly for generic code)
simply returns its argument.
Example:
-------------------------
int a = 42;
auto b = to!int(a); // b is int with value 42
auto c = to!double(3.14); // c is double with value 3.14
-------------------------
Converting among numeric types is a safe way to cast them around.
Conversions from floating-point types to integral types allow loss of
precision (the fractional part of a floating-point number). The
conversion is truncating towards zero, the same way a cast would
truncate. (To round a floating point value when casting to an
integral, use $(D_PARAM roundTo).)
Examples:
-------------------------
int a = 420;
auto b = to!long(a); // same as long b = a;
auto c = to!byte(a / 10); // fine, c = 42
auto d = to!byte(a); // throw ConvOverflowException
double e = 4.2e6;
auto f = to!int(e); // f == 4200000
e = -3.14;
auto g = to!uint(e); // fails: floating-to-integral negative overflow
e = 3.14;
auto h = to!uint(e); // h = 3
e = 3.99;
h = to!uint(a); // h = 3
e = -3.99;
f = to!int(a); // f = -3
-------------------------
Conversions from integral types to floating-point types always
succeed, but might lose accuracy. The largest integers with a
predecessor representable in floating-point format are 2^24-1 for
float, 2^53-1 for double, and 2^64-1 for $(D_PARAM real) (when
$(D_PARAM real) is 80-bit, e.g. on Intel machines).
Example:
-------------------------
int a = 16_777_215; // 2^24 - 1, largest proper integer representable as float
assert(to!int(to!float(a)) == a);
assert(to!int(to!float(-a)) == -a);
a += 2;
assert(to!int(to!float(a)) == a); // fails!
-------------------------
Conversions from string to numeric types differ from the C equivalents
$(D_PARAM atoi()) and $(D_PARAM atol()) by checking for overflow and
not allowing whitespace.
For conversion of strings to signed types, the grammar recognized is:
<pre>
$(I Integer): $(I Sign UnsignedInteger)
$(I UnsignedInteger)
$(I Sign):
$(B +)
$(B -)
</pre>
For conversion to unsigned types, the grammar recognized is:
<pre>
$(I UnsignedInteger):
$(I DecimalDigit)
$(I DecimalDigit) $(I UnsignedInteger)
</pre>
Converting an array to another array type works by converting each
element in turn. Associative arrays can be converted to associative
arrays as long as keys and values can in turn be converted.
Example:
-------------------------
int[] a = [1, 2, 3];
auto b = to!(float[])(a);
assert(b == [1.0f, 2, 3]);
string str = "1 2 3 4 5 6";
auto numbers = to!(double[])(split(str));
assert(numbers == [1.0, 2, 3, 4, 5, 6]);
int[string] c;
c["a"] = 1;
c["b"] = 2;
auto d = to!(double[wstring])(c);
assert(d["a"w] == 1 && d["b"w] == 2);
-------------------------
Conversions operate transitively, meaning that they work on arrays and
associative arrays of any complexity:
-------------------------
int[string][double[int[]]] a;
...
auto b = to!(short[wstring][string[double[]]])(a);
-------------------------
This conversion works because $(D_PARAM to!short) applies to an
$(D_PARAM int), $(D_PARAM to!wstring) applies to a $(D_PARAM
string), $(D_PARAM to!string) applies to a $(D_PARAM double), and
$(D_PARAM to!(double[])) applies to an $(D_PARAM int[]). The
conversion might throw an exception because $(D_PARAM to!short)
might fail the range check.
*/
/**
Entry point that dispatches to the appropriate conversion
primitive. Client code normally calls $(D _to!TargetType(value))
(and not some variant of $(D toImpl)).
*/
template to(T)
{
T to(A...)(A args)
if (!isRawStaticArray!A)
{
return toImpl!T(args);
}
// Fix issue 6175
T to(S)(ref S arg)
if (isRawStaticArray!S)
{
return toImpl!T(arg);
}
}
// Tests for issue 6175
@safe pure nothrow unittest
{
char[9] sarr = "blablabla";
auto darr = to!(char[])(sarr);
assert(sarr.ptr == darr.ptr);
assert(sarr.length == darr.length);
}
// Tests for issue 7348
@safe pure /+nothrow+/ unittest
{
assert(to!string(null) == "null");
assert(text(null) == "null");
}
// Tests for issue 11390
@safe pure /+nothrow+/ unittest
{
const(typeof(null)) ctn;
immutable(typeof(null)) itn;
assert(to!string(ctn) == "null");
assert(to!string(itn) == "null");
}
// Tests for issue 8729: do NOT skip leading WS
@safe pure unittest
{
import std.exception;
foreach (T; TypeTuple!(byte, ubyte, short, ushort, int, uint, long, ulong))
{
assertThrown!ConvException(to!T(" 0"));
assertThrown!ConvException(to!T(" 0", 8));
}
foreach (T; TypeTuple!(float, double, real))
{
assertThrown!ConvException(to!T(" 0"));
}
assertThrown!ConvException(to!bool(" true"));
alias NullType = typeof(null);
assertThrown!ConvException(to!NullType(" null"));
alias ARR = int[];
assertThrown!ConvException(to!ARR(" [1]"));
alias AA = int[int];
assertThrown!ConvException(to!AA(" [1:1]"));
}
/**
If the source type is implicitly convertible to the target type, $(D
to) simply performs the implicit conversion.
*/
T toImpl(T, S)(S value)
if (isImplicitlyConvertible!(S, T) &&
!isEnumStrToStr!(S, T) && !isNullToStr!(S, T))
{
template isSignedInt(T)
{
enum isSignedInt = isIntegral!T && isSigned!T;
}
alias isUnsignedInt = isUnsigned;
// Conversion from integer to integer, and changing its sign
static if (isUnsignedInt!S && isSignedInt!T && S.sizeof == T.sizeof)
{ // unsigned to signed & same size
import std.exception : enforce;
enforce(value <= cast(S)T.max,
new ConvOverflowException("Conversion positive overflow"));
}
else static if (isSignedInt!S && isUnsignedInt!T)
{ // signed to unsigned
import std.exception : enforce;
enforce(0 <= value,
new ConvOverflowException("Conversion negative overflow"));
}
return value;
}
@safe pure nothrow unittest
{
enum E { a } // Issue 9523 - Allow identity enum conversion
auto e = to!E(E.a);
assert(e == E.a);
}
@safe pure nothrow unittest
{
int a = 42;
auto b = to!long(a);
assert(a == b);
}
// Tests for issue 6377
@safe pure unittest
{
import std.exception;
// Conversion between same size
foreach (S; TypeTuple!(byte, short, int, long))
(){ // avoid slow optimizations for large functions @@@BUG@@@ 2396
alias U = Unsigned!S;
foreach (Sint; TypeTuple!(S, const S, immutable S))
foreach (Uint; TypeTuple!(U, const U, immutable U))
{
// positive overflow
Uint un = Uint.max;
assertThrown!ConvOverflowException(to!Sint(un),
text(Sint.stringof, ' ', Uint.stringof, ' ', un));
// negative overflow
Sint sn = -1;
assertThrown!ConvOverflowException(to!Uint(sn),
text(Sint.stringof, ' ', Uint.stringof, ' ', un));
}
}();
// Conversion between different size
foreach (i, S1; TypeTuple!(byte, short, int, long))
foreach ( S2; TypeTuple!(byte, short, int, long)[i+1..$])
(){ // avoid slow optimizations for large functions @@@BUG@@@ 2396
alias U1 = Unsigned!S1;
alias U2 = Unsigned!S2;
static assert(U1.sizeof < S2.sizeof);
// small unsigned to big signed
foreach (Uint; TypeTuple!(U1, const U1, immutable U1))
foreach (Sint; TypeTuple!(S2, const S2, immutable S2))
{
Uint un = Uint.max;
assertNotThrown(to!Sint(un));
assert(to!Sint(un) == un);
}
// big unsigned to small signed
foreach (Uint; TypeTuple!(U2, const U2, immutable U2))
foreach (Sint; TypeTuple!(S1, const S1, immutable S1))
{
Uint un = Uint.max;
assertThrown(to!Sint(un));
}
static assert(S1.sizeof < U2.sizeof);
// small signed to big unsigned
foreach (Sint; TypeTuple!(S1, const S1, immutable S1))
foreach (Uint; TypeTuple!(U2, const U2, immutable U2))
{
Sint sn = -1;
assertThrown!ConvOverflowException(to!Uint(sn));
}
// big signed to small unsigned
foreach (Sint; TypeTuple!(S2, const S2, immutable S2))
foreach (Uint; TypeTuple!(U1, const U1, immutable U1))
{
Sint sn = -1;
assertThrown!ConvOverflowException(to!Uint(sn));
}
}();
}
/*
Converting static arrays forwards to their dynamic counterparts.
*/
T toImpl(T, S)(ref S s)
if (isRawStaticArray!S)
{
return toImpl!(T, typeof(s[0])[])(s);
}
@safe pure nothrow unittest
{
char[4] test = ['a', 'b', 'c', 'd'];
static assert(!isInputRange!(Unqual!(char[4])));
assert(to!string(test) == test);
}
/**
When source type supports member template function opCast, it is used.
*/
T toImpl(T, S)(S value)
if (!isImplicitlyConvertible!(S, T) &&
is(typeof(S.init.opCast!T()) : T) &&
!isExactSomeString!T &&
!is(typeof(T(value))))
{
return value.opCast!T();
}
@safe pure unittest
{
static struct Test
{
struct T
{
this(S s) @safe pure { }
}
struct S
{
T opCast(U)() @safe pure { assert(false); }
}
}
to!(Test.T)(Test.S());
// make sure std.conv.to is doing the same thing as initialization
Test.S s;
Test.T t = s;
}
@safe pure unittest
{
class B
{
T opCast(T)() { return 43; }
}
auto b = new B;
assert(to!int(b) == 43);
struct S
{
T opCast(T)() { return 43; }
}
auto s = S();
assert(to!int(s) == 43);
}
/**
When target type supports 'converting construction', it is used.
$(UL $(LI If target type is struct, $(D T(value)) is used.)
$(LI If target type is class, $(D new T(value)) is used.))
*/
T toImpl(T, S)(S value)
if (!isImplicitlyConvertible!(S, T) &&
is(T == struct) && is(typeof(T(value))))
{
return T(value);
}
// Bugzilla 3961
@safe pure unittest
{
struct Int
{
int x;
}
Int i = to!Int(1);
static struct Int2
{
int x;
this(int x) @safe pure { this.x = x; }
}
Int2 i2 = to!Int2(1);
static struct Int3
{
int x;
static Int3 opCall(int x) @safe pure
{
Int3 i;
i.x = x;
return i;
}
}
Int3 i3 = to!Int3(1);
}
// Bugzilla 6808
@safe pure unittest
{
static struct FakeBigInt
{
this(string s) @safe pure {}
}
string s = "101";
auto i3 = to!FakeBigInt(s);
}
/// ditto
T toImpl(T, S)(S value)
if (!isImplicitlyConvertible!(S, T) &&
is(T == class) && is(typeof(new T(value))))
{
return new T(value);
}
@safe pure unittest
{
static struct S
{
int x;
}
static class C
{
int x;
this(int x) @safe pure { this.x = x; }
}
static class B
{
int value;
this(S src) @safe pure { value = src.x; }
this(C src) @safe pure { value = src.x; }
}
S s = S(1);
auto b1 = to!B(s); // == new B(s)
assert(b1.value == 1);
C c = new C(2);
auto b2 = to!B(c); // == new B(c)
assert(b2.value == 2);
auto c2 = to!C(3); // == new C(3)
assert(c2.x == 3);
}
@safe pure unittest
{
struct S
{
class A
{
this(B b) @safe pure {}
}
class B : A
{
this() @safe pure { super(this); }
}
}
S.B b = new S.B();
S.A a = to!(S.A)(b); // == cast(S.A)b
// (do not run construction conversion like new S.A(b))
assert(b is a);
static class C : Object
{
this() @safe pure {}
this(Object o) @safe pure {}
}
Object oc = new C();
C a2 = to!C(oc); // == new C(a)
// Construction conversion overrides down-casting conversion
assert(a2 !is a); //
}
/**
Object-to-object conversions by dynamic casting throw exception when the source is
non-null and the target is null.
*/
T toImpl(T, S)(S value)
if (!isImplicitlyConvertible!(S, T) &&
(is(S == class) || is(S == interface)) && !is(typeof(value.opCast!T()) : T) &&
(is(T == class) || is(T == interface)) && !is(typeof(new T(value))))
{
static if (is(T == immutable))
{
// immutable <- immutable
enum isModConvertible = is(S == immutable);
}
else static if (is(T == const))
{
static if (is(T == shared))
{
// shared const <- shared
// shared const <- shared const
// shared const <- immutable
enum isModConvertible = is(S == shared) || is(S == immutable);
}
else
{
// const <- mutable
// const <- immutable
enum isModConvertible = !is(S == shared);
}
}
else
{
static if (is(T == shared))
{
// shared <- shared mutable
enum isModConvertible = is(S == shared) && !is(S == const);
}
else
{
// (mutable) <- (mutable)
enum isModConvertible = is(Unqual!S == S);
}
}
static assert(isModConvertible, "Bad modifier conversion: "~S.stringof~" to "~T.stringof);
auto result = ()@trusted{ return cast(T) value; }();
if (!result && value)
{
throw new ConvException("Cannot convert object of static type "
~S.classinfo.name~" and dynamic type "~value.classinfo.name
~" to type "~T.classinfo.name);
}
return result;
}
@safe pure unittest
{
import std.exception;
// Testing object conversions
class A {}
class B : A {}
class C : A {}
A a1 = new A, a2 = new B, a3 = new C;
assert(to!B(a2) is a2);
assert(to!C(a3) is a3);
assertThrown!ConvException(to!B(a3));
}
// Unittest for 6288
@safe pure unittest
{
import std.exception;
alias Identity(T) = T;
alias toConst(T) = const T;
alias toShared(T) = shared T;
alias toSharedConst(T) = shared const T;
alias toImmutable(T) = immutable T;
template AddModifier(int n) if (0 <= n && n < 5)
{
static if (n == 0) alias AddModifier = Identity;
else static if (n == 1) alias AddModifier = toConst;
else static if (n == 2) alias AddModifier = toShared;
else static if (n == 3) alias AddModifier = toSharedConst;
else static if (n == 4) alias AddModifier = toImmutable;
}
interface I {}
interface J {}
class A {}
class B : A {}
class C : B, I, J {}
class D : I {}
foreach (m1; TypeTuple!(0,1,2,3,4)) // enumerate modifiers
foreach (m2; TypeTuple!(0,1,2,3,4)) // ditto
(){ // avoid slow optimizations for large functions @@@BUG@@@ 2396
alias srcmod = AddModifier!m1;
alias tgtmod = AddModifier!m2;
//pragma(msg, srcmod!Object, " -> ", tgtmod!Object, ", convertible = ",
// isImplicitlyConvertible!(srcmod!Object, tgtmod!Object));
// Compile time convertible equals to modifier convertible.
static if (isImplicitlyConvertible!(srcmod!Object, tgtmod!Object))
{
// Test runtime conversions: class to class, class to interface,
// interface to class, and interface to interface
// Check that the runtime conversion to succeed
srcmod!A ac = new srcmod!C();
srcmod!I ic = new srcmod!C();
assert(to!(tgtmod!C)(ac) !is null); // A(c) to C
assert(to!(tgtmod!I)(ac) !is null); // A(c) to I
assert(to!(tgtmod!C)(ic) !is null); // I(c) to C
assert(to!(tgtmod!J)(ic) !is null); // I(c) to J
// Check that the runtime conversion fails
srcmod!A ab = new srcmod!B();
srcmod!I id = new srcmod!D();
assertThrown(to!(tgtmod!C)(ab)); // A(b) to C
assertThrown(to!(tgtmod!I)(ab)); // A(b) to I
assertThrown(to!(tgtmod!C)(id)); // I(d) to C
assertThrown(to!(tgtmod!J)(id)); // I(d) to J
}
else
{
// Check that the conversion is rejected statically
static assert(!is(typeof(to!(tgtmod!C)(srcmod!A.init)))); // A to C
static assert(!is(typeof(to!(tgtmod!I)(srcmod!A.init)))); // A to I
static assert(!is(typeof(to!(tgtmod!C)(srcmod!I.init)))); // I to C
static assert(!is(typeof(to!(tgtmod!J)(srcmod!I.init)))); // I to J
}
}();
}
/**
Stringize conversion from all types is supported.
$(UL
$(LI String _to string conversion works for any two string types having
($(D char), $(D wchar), $(D dchar)) character widths and any
combination of qualifiers (mutable, $(D const), or $(D immutable)).)
$(LI Converts array (other than strings) to string.
Each element is converted by calling $(D to!T).)
$(LI Associative array to string conversion.
Each element is printed by calling $(D to!T).)
$(LI Object to string conversion calls $(D toString) against the object or
returns $(D "null") if the object is null.)
$(LI Struct to string conversion calls $(D toString) against the struct if
it is defined.)
$(LI For structs that do not define $(D toString), the conversion to string
produces the list of fields.)
$(LI Enumerated types are converted to strings as their symbolic names.)
$(LI Boolean values are printed as $(D "true") or $(D "false").)
$(LI $(D char), $(D wchar), $(D dchar) to a string type.)
$(LI Unsigned or signed integers to strings.
$(DL $(DT [special case])
$(DD Convert integral value to string in $(D_PARAM radix) radix.
radix must be a value from 2 to 36.
value is treated as a signed value only if radix is 10.
The characters A through Z are used to represent values 10 through 36
and their case is determined by the $(D_PARAM letterCase) parameter.)))
$(LI All floating point types to all string types.)
$(LI Pointer to string conversions prints the pointer as a $(D size_t) value.
If pointer is $(D char*), treat it as C-style strings.
In that case, this function is $(D @system).))
*/
T toImpl(T, S)(S value)
if (!(isImplicitlyConvertible!(S, T) &&
!isEnumStrToStr!(S, T) && !isNullToStr!(S, T)) &&
!isInfinite!S && isExactSomeString!T)
{
static if (isExactSomeString!S && value[0].sizeof == ElementEncodingType!T.sizeof)
{
// string-to-string with incompatible qualifier conversion
static if (is(ElementEncodingType!T == immutable))
{
// conversion (mutable|const) -> immutable
return value.idup;
}
else
{
// conversion (immutable|const) -> mutable
return value.dup;
}
}
else static if (isExactSomeString!S)
{
import std.array : appender;
// other string-to-string
//Use Appender directly instead of toStr, which also uses a formatedWrite
auto w = appender!T();
w.put(value);
return w.data;
}
else static if (isIntegral!S && !is(S == enum))
{
// other integral-to-string conversions with default radix
return toImpl!(T, S)(value, 10);
}
else static if (is(S == void[]) || is(S == const(void)[]) || is(S == immutable(void)[]))
{
import core.stdc.string : memcpy;
import std.exception : enforce;
// Converting void array to string
alias Char = Unqual!(ElementEncodingType!T);
auto raw = cast(const(ubyte)[]) value;
enforce(raw.length % Char.sizeof == 0,
new ConvException("Alignment mismatch in converting a "
~ S.stringof ~ " to a "
~ T.stringof));
auto result = new Char[raw.length / Char.sizeof];
()@trusted{ memcpy(result.ptr, value.ptr, value.length); }();
return cast(T) result;
}
else static if (isPointer!S && is(S : const(char)*))
{
import core.stdc.string : strlen;
// It is unsafe because we cannot guarantee that the pointer is null terminated.
return value ? cast(T) value[0 .. strlen(value)].dup : null;
}
else static if (isSomeString!T && is(S == enum))
{
static if (isSwitchable!(OriginalType!S) && EnumMembers!S.length <= 50)
{
switch(value)
{
foreach (member; NoDuplicates!(EnumMembers!S))
{
case member:
return to!T(enumRep!(immutable(T), S, member));
}
default:
}
}
else
{
foreach (member; EnumMembers!S)
{
if (value == member)
return to!T(enumRep!(immutable(T), S, member));
}
}
import std.format : FormatSpec, formatValue;
import std.array : appender;
//Default case, delegate to format
//Note: we don't call toStr directly, to avoid duplicate work.
auto app = appender!T();
app.put("cast(");
app.put(S.stringof);
app.put(')');
FormatSpec!char f;
formatValue(app, cast(OriginalType!S)value, f);
return app.data;
}
else
{
// other non-string values runs formatting
return toStr!T(value);
}
}
// Bugzilla 14042
unittest
{
immutable(char)* ptr = "hello".ptr;
auto result = ptr.to!(char[]);
}
/*
Check whether type $(D T) can be used in a switch statement.
This is useful for compile-time generation of switch case statements.
*/
private template isSwitchable(E)
{
enum bool isSwitchable = is(typeof({
switch (E.init) { default: }
}));
}
//
unittest
{
static assert(isSwitchable!int);
static assert(!isSwitchable!double);
static assert(!isSwitchable!real);
}
//Static representation of the index I of the enum S,
//In representation T.
//T must be an immutable string (avoids un-necessary initializations).
private template enumRep(T, S, S value)
if (is (T == immutable) && isExactSomeString!T && is(S == enum))
{
static T enumRep = toStr!T(value);
}
@safe pure unittest
{
import std.exception;
void dg()
{
// string to string conversion
alias Chars = TypeTuple!(char, wchar, dchar);
foreach (LhsC; Chars)
{
alias LhStrings = TypeTuple!(LhsC[], const(LhsC)[], immutable(LhsC)[]);
foreach (Lhs; LhStrings)
{
foreach (RhsC; Chars)
{
alias RhStrings = TypeTuple!(RhsC[], const(RhsC)[], immutable(RhsC)[]);
foreach (Rhs; RhStrings)
{
Lhs s1 = to!Lhs("wyda");
Rhs s2 = to!Rhs(s1);
//writeln(Lhs.stringof, " -> ", Rhs.stringof);
assert(s1 == to!Lhs(s2));
}
}
}
}
foreach (T; Chars)
{
foreach (U; Chars)
{
T[] s1 = to!(T[])("Hello, world!");
auto s2 = to!(U[])(s1);
assert(s1 == to!(T[])(s2));
auto s3 = to!(const(U)[])(s1);
assert(s1 == to!(T[])(s3));
auto s4 = to!(immutable(U)[])(s1);
assert(s1 == to!(T[])(s4));
}
}
}
dg();
assertCTFEable!dg;