/
variant.d
2524 lines (2282 loc) · 72.3 KB
/
variant.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.
/**
* This module implements a
* $(LINK2 http://erdani.org/publications/cuj-04-2002.html,discriminated union)
* type (a.k.a.
* $(LINK2 http://en.wikipedia.org/wiki/Tagged_union,tagged union),
* $(LINK2 http://en.wikipedia.org/wiki/Algebraic_data_type,algebraic type)).
* Such types are useful
* for type-uniform binary interfaces, interfacing with scripting
* languages, and comfortable exploratory programming.
*
* Macros:
* WIKI = Phobos/StdVariant
*
* Synopsis:
*
* ----
* Variant a; // Must assign before use, otherwise exception ensues
* // Initialize with an integer; make the type int
* Variant b = 42;
* assert(b.type == typeid(int));
* // Peek at the value
* assert(b.peek!(int) !is null && *b.peek!(int) == 42);
* // Automatically convert per language rules
* auto x = b.get!(real);
* // Assign any other type, including other variants
* a = b;
* a = 3.14;
* assert(a.type == typeid(double));
* // Implicit conversions work just as with built-in types
* assert(a < b);
* // Check for convertibility
* assert(!a.convertsTo!(int)); // double not convertible to int
* // Strings and all other arrays are supported
* a = "now I'm a string";
* assert(a == "now I'm a string");
* a = new int[42]; // can also assign arrays
* assert(a.length == 42);
* a[5] = 7;
* assert(a[5] == 7);
* // Can also assign class values
* class Foo {}
* auto foo = new Foo;
* a = foo;
* assert(*a.peek!(Foo) == foo); // and full type information is preserved
* ----
*
* Credits:
*
* Reviewed by Brad Roberts. Daniel Keep provided a detailed code
* review prompting the following improvements: (1) better support for
* arrays; (2) support for associative arrays; (3) friendlier behavior
* towards the garbage collector.
*
* Copyright: Copyright Andrei Alexandrescu 2007 - 2009.
* License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
* Authors: $(WEB erdani.org, Andrei Alexandrescu)
* Source: $(PHOBOSSRC std/_variant.d)
*/
/* Copyright Andrei Alexandrescu 2007 - 2009.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
module std.variant;
import core.stdc.string, std.conv, std.exception, std.traits, std.typecons,
std.typetuple;
@trusted:
/++
Gives the $(D sizeof) the largest type given.
+/
template maxSize(T...)
{
static if (T.length == 1)
{
enum size_t maxSize = T[0].sizeof;
}
else
{
enum size_t maxSize = T[0].sizeof >= maxSize!(T[1 .. $])
? T[0].sizeof : maxSize!(T[1 .. $]);
}
}
struct This;
template AssociativeArray(T)
{
enum bool valid = false;
alias Key = void;
alias Value = void;
}
template AssociativeArray(T : V[K], K, V)
{
enum bool valid = true;
alias Key = K;
alias Value = V;
}
template This2Variant(V, T...)
{
static if (T.length == 0)
alias This2Variant = TypeTuple!();
else static if (is(AssociativeArray!(T[0]).Key == This))
{
static if (is(AssociativeArray!(T[0]).Value == This))
alias This2Variant =
TypeTuple!(V[V],
This2Variant!(V, T[1 .. $]));
else
alias This2Variant =
TypeTuple!(AssociativeArray!(T[0]).Value[V],
This2Variant!(V, T[1 .. $]));
}
else static if (is(AssociativeArray!(T[0]).Value == This))
alias This2Variant =
TypeTuple!(V[AssociativeArray!(T[0]).Key],
This2Variant!(V, T[1 .. $]));
else static if (is(T[0] == This[]))
alias This2Variant = TypeTuple!(V[], This2Variant!(V, T[1 .. $]));
else static if (is(T[0] == This*))
alias This2Variant = TypeTuple!(V*, This2Variant!(V, T[1 .. $]));
else
alias This2Variant = TypeTuple!(T[0], This2Variant!(V, T[1 .. $]));
}
/**
* $(D_PARAM VariantN) is a back-end type seldom used directly by user
* code. Two commonly-used types using $(D_PARAM VariantN) as
* back-end are:
*
* $(OL $(LI $(B Algebraic): A closed discriminated union with a
* limited type universe (e.g., $(D_PARAM Algebraic!(int, double,
* string)) only accepts these three types and rejects anything
* else).) $(LI $(B Variant): An open discriminated union allowing an
* unbounded set of types. The restriction is that the size of the
* stored type cannot be larger than the largest built-in type. This
* means that $(D_PARAM Variant) can accommodate all primitive types
* and all user-defined types except for large $(D_PARAM struct)s.) )
*
* Both $(D_PARAM Algebraic) and $(D_PARAM Variant) share $(D_PARAM
* VariantN)'s interface. (See their respective documentations below.)
*
* $(D_PARAM VariantN) is a discriminated union type parameterized
* with the largest size of the types stored ($(D_PARAM maxDataSize))
* and with the list of allowed types ($(D_PARAM AllowedTypes)). If
* the list is empty, then any type up of size up to $(D_PARAM
* maxDataSize) (rounded up for alignment) can be stored in a
* $(D_PARAM VariantN) object.
*
*/
struct VariantN(size_t maxDataSize, AllowedTypesX...)
{
alias AllowedTypes = This2Variant!(VariantN, AllowedTypesX);
private:
// Compute the largest practical size from maxDataSize
struct SizeChecker
{
int function() fptr;
ubyte[maxDataSize] data;
}
enum size = SizeChecker.sizeof - (int function()).sizeof;
/** Tells whether a type $(D_PARAM T) is statically allowed for
* storage inside a $(D_PARAM VariantN) object by looking
* $(D_PARAM T) up in $(D_PARAM AllowedTypes). If $(D_PARAM
* AllowedTypes) is empty, all types of size up to $(D_PARAM
* maxSize) are allowed.
*/
public template allowed(T)
{
enum bool allowed
= is(T == VariantN)
||
//T.sizeof <= size &&
(AllowedTypes.length == 0 || staticIndexOf!(T, AllowedTypes) >= 0);
}
// Each internal operation is encoded with an identifier. See
// the "handler" function below.
enum OpID { getTypeInfo, get, compare, equals, testConversion, toString,
index, indexAssign, catAssign, copyOut, length,
apply, postblit, destruct }
// state
ptrdiff_t function(OpID selector, ubyte[size]* store, void* data) fptr
= &handler!(void);
union
{
ubyte[size] store;
// conservatively mark the region as pointers
static if (size >= (void*).sizeof)
void*[size / (void*).sizeof] p;
}
// internals
// Handler for an uninitialized value
static ptrdiff_t handler(A : void)(OpID selector, ubyte[size]*, void* parm)
{
switch (selector)
{
case OpID.getTypeInfo:
*cast(TypeInfo *) parm = typeid(A);
break;
case OpID.copyOut:
auto target = cast(VariantN *) parm;
target.fptr = &handler!(A);
// no need to copy the data (it's garbage)
break;
case OpID.compare:
case OpID.equals:
auto rhs = cast(const VariantN *) parm;
return rhs.peek!(A)
? 0 // all uninitialized are equal
: ptrdiff_t.min; // uninitialized variant is not comparable otherwise
case OpID.toString:
string * target = cast(string*) parm;
*target = "<Uninitialized VariantN>";
break;
case OpID.postblit:
case OpID.destruct:
break;
case OpID.get:
case OpID.testConversion:
case OpID.index:
case OpID.indexAssign:
case OpID.catAssign:
case OpID.length:
throw new VariantException(
"Attempt to use an uninitialized VariantN");
default: assert(false, "Invalid OpID");
}
return 0;
}
// Handler for all of a type's operations
static ptrdiff_t handler(A)(OpID selector, ubyte[size]* pStore, void* parm)
{
static A* getPtr(void* untyped)
{
if (untyped)
{
static if (A.sizeof <= size)
return cast(A*) untyped;
else
return *cast(A**) untyped;
}
return null;
}
static ptrdiff_t compare(A* rhsPA, A* zis, OpID selector)
{
static if (is(typeof(*rhsPA == *zis)))
{
if (*rhsPA == *zis)
{
return 0;
}
static if (is(typeof(*zis < *rhsPA)))
{
// Many types (such as any using the default Object opCmp)
// will throw on an invalid opCmp, so do it only
// if the caller requests it.
if (selector == OpID.compare)
return *zis < *rhsPA ? -1 : 1;
else
return ptrdiff_t.min;
}
else
{
// Not equal, and type does not support ordering
// comparisons.
return ptrdiff_t.min;
}
}
else
{
// Type does not support comparisons at all.
return ptrdiff_t.min;
}
}
auto zis = getPtr(pStore);
// Input: TypeInfo object
// Output: target points to a copy of *me, if me was not null
// Returns: true iff the A can be converted to the type represented
// by the incoming TypeInfo
static bool tryPutting(A* src, TypeInfo targetType, void* target)
{
alias UA = Unqual!A;
alias MutaTypes = TypeTuple!(UA, ImplicitConversionTargets!UA);
alias ConstTypes = staticMap!(ConstOf, MutaTypes);
alias SharedTypes = staticMap!(SharedOf, MutaTypes);
alias SharedConstTypes = staticMap!(SharedConstOf, MutaTypes);
alias ImmuTypes = staticMap!(ImmutableOf, MutaTypes);
static if (is(A == immutable))
alias AllTypes = TypeTuple!(ImmuTypes, ConstTypes, SharedConstTypes);
else static if (is(A == shared))
{
static if (is(A == const))
alias AllTypes = SharedConstTypes;
else
alias AllTypes = TypeTuple!(SharedTypes, SharedConstTypes);
}
else
{
static if (is(A == const))
alias AllTypes = ConstTypes;
else
alias AllTypes = TypeTuple!(MutaTypes, ConstTypes);
}
foreach (T ; AllTypes)
{
if (targetType != typeid(T))
{
continue;
}
static if (is(typeof(*cast(T*) target = *src)))
{
auto zat = cast(T*) target;
if (src)
{
assert(target, "target must be non-null");
*zat = *src;
}
}
else static if (is(T == const(U), U) ||
is(T == shared(U), U) ||
is(T == shared const(U), U) ||
is(T == immutable(U), U))
{
auto zat = cast(U*) target;
if (src)
{
assert(target, "target must be non-null");
*zat = *(cast(UA*) (src));
}
}
else
{
// type is not assignable
if (src) assert(false, A.stringof);
}
return true;
}
return false;
}
switch (selector)
{
case OpID.getTypeInfo:
*cast(TypeInfo *) parm = typeid(A);
break;
case OpID.copyOut:
auto target = cast(VariantN *) parm;
assert(target);
static if (target.size < A.sizeof)
{
if (target.type.tsize < A.sizeof)
*cast(A**)&target.store = new A;
}
tryPutting(zis, typeid(A), cast(void*) getPtr(&target.store))
|| assert(false);
target.fptr = &handler!(A);
break;
case OpID.get:
return !tryPutting(zis, *cast(TypeInfo*) parm, parm);
case OpID.testConversion:
return !tryPutting(null, *cast(TypeInfo*) parm, null);
case OpID.compare:
case OpID.equals:
auto rhsP = cast(VariantN *) parm;
auto rhsType = rhsP.type;
// Are we the same?
if (rhsType == typeid(A))
{
// cool! Same type!
auto rhsPA = getPtr(&rhsP.store);
return compare(rhsPA, zis, selector);
} else if (rhsType == typeid(void))
{
// No support for ordering comparisons with
// uninitialized vars
return ptrdiff_t.min;
}
VariantN temp;
// Do I convert to rhs?
if (tryPutting(zis, rhsType, &temp.store))
{
// cool, I do; temp's store contains my data in rhs's type!
// also fix up its fptr
temp.fptr = rhsP.fptr;
// now lhsWithRhsType is a full-blown VariantN of rhs's type
if (selector == OpID.compare)
return temp.opCmp(*rhsP);
else
return temp.opEquals(*rhsP) ? 0 : 1;
}
// Does rhs convert to zis?
*cast(TypeInfo*) &temp.store = typeid(A);
if (rhsP.fptr(OpID.get, &rhsP.store, &temp.store) == 0)
{
// cool! Now temp has rhs in my type!
auto rhsPA = getPtr(&temp.store);
return compare(rhsPA, zis, selector);
}
return ptrdiff_t.min; // dunno
case OpID.toString:
auto target = cast(string*) parm;
static if (is(typeof(to!(string)(*zis))))
{
*target = to!(string)(*zis);
break;
}
// TODO: The following test evaluates to true for shared objects.
// Use __traits for now until this is sorted out.
// else static if (is(typeof((*zis).toString)))
else static if (__traits(compiles, {(*zis).toString();}))
{
*target = (*zis).toString();
break;
}
else
{
throw new VariantException(typeid(A), typeid(string));
}
case OpID.index:
auto result = cast(Variant*) parm;
static if (isArray!(A) && !is(Unqual!(typeof(A.init[0])) == void))
{
// array type; input and output are the same VariantN
size_t index = result.convertsTo!(int)
? result.get!(int) : result.get!(size_t);
*result = (*zis)[index];
break;
}
else static if (isAssociativeArray!(A))
{
*result = (*zis)[result.get!(typeof(A.init.keys[0]))];
break;
}
else
{
throw new VariantException(typeid(A), result[0].type);
}
case OpID.indexAssign:
// array type; result comes first, index comes second
auto args = cast(Variant*) parm;
static if (isArray!(A) && is(typeof((*zis)[0] = (*zis)[0])))
{
size_t index = args[1].convertsTo!(int)
? args[1].get!(int) : args[1].get!(size_t);
(*zis)[index] = args[0].get!(typeof((*zis)[0]));
break;
}
else static if (isAssociativeArray!(A))
{
(*zis)[args[1].get!(typeof(A.init.keys[0]))]
= args[0].get!(typeof(A.init.values[0]));
break;
}
else
{
throw new VariantException(typeid(A), args[0].type);
}
case OpID.catAssign:
static if (!is(Unqual!(typeof((*zis)[0])) == void) && is(typeof((*zis)[0])) && is(typeof((*zis) ~= *zis)))
{
// array type; parm is the element to append
auto arg = cast(VariantN*) parm;
alias E = typeof((*zis)[0]);
if (arg[0].convertsTo!(E))
{
// append one element to the array
(*zis) ~= [ arg[0].get!(E) ];
}
else
{
// append a whole array to the array
(*zis) ~= arg[0].get!(A);
}
break;
}
else
{
throw new VariantException(typeid(A), typeid(void[]));
}
case OpID.length:
static if (isArray!(A) || isAssociativeArray!(A))
{
return zis.length;
}
else
{
throw new VariantException(typeid(A), typeid(void[]));
}
case OpID.apply:
static if (!isFunctionPointer!A && !isDelegate!A)
{
enforce(0, text("Cannot apply `()' to a value of type `",
A.stringof, "'."));
}
else
{
alias ParamTypes = ParameterTypeTuple!A;
auto p = cast(Variant*) parm;
auto argCount = p.get!size_t;
// To assign the tuple we need to use the unqualified version,
// otherwise we run into issues such as with const values.
// We still get the actual type from the Variant though
// to ensure that we retain const correctness.
Tuple!(staticMap!(Unqual, ParamTypes)) t;
enforce(t.length == argCount,
text("Argument count mismatch: ",
A.stringof, " expects ", t.length,
" argument(s), not ", argCount, "."));
auto variantArgs = p[1 .. argCount + 1];
foreach (i, T; ParamTypes)
{
t[i] = cast()variantArgs[i].get!T;
}
auto args = cast(Tuple!(ParamTypes))t;
static if(is(ReturnType!A == void))
{
(*zis)(args.expand);
*p = Variant.init; // void returns uninitialized Variant.
}
else
{
*p = (*zis)(args.expand);
}
}
break;
case OpID.postblit:
static if (hasElaborateCopyConstructor!A)
{
typeid(A).postblit(zis);
}
break;
case OpID.destruct:
static if (hasElaborateDestructor!A)
{
typeid(A).destroy(zis);
}
break;
default: assert(false);
}
return 0;
}
public:
/** Constructs a $(D_PARAM VariantN) value given an argument of a
* generic type. Statically rejects disallowed types.
*/
this(T)(T value)
{
static assert(allowed!(T), "Cannot store a " ~ T.stringof
~ " in a " ~ VariantN.stringof);
opAssign(value);
}
static if (!AllowedTypes.length || anySatisfy!(hasElaborateCopyConstructor, AllowedTypes))
{
this(this)
{
fptr(OpID.postblit, &store, null);
}
}
static if (!AllowedTypes.length || anySatisfy!(hasElaborateDestructor, AllowedTypes))
{
~this()
{
fptr(OpID.destruct, &store, null);
}
}
/** Assigns a $(D_PARAM VariantN) from a generic
* argument. Statically rejects disallowed types. */
VariantN opAssign(T)(T rhs)
{
//writeln(typeid(rhs));
static assert(allowed!(T), "Cannot store a " ~ T.stringof
~ " in a " ~ VariantN.stringof ~ ". Valid types are "
~ AllowedTypes.stringof);
// Assignment should destruct previous value
fptr(OpID.destruct, &store, null);
static if (is(T : VariantN))
{
rhs.fptr(OpID.copyOut, &rhs.store, &this);
}
else static if (is(T : const(VariantN)))
{
static assert(false,
"Assigning Variant objects from const Variant"~
" objects is currently not supported.");
}
else
{
static if (T.sizeof <= size)
{
// If T is a class we're only copying the reference, so it
// should be safe to cast away shared so the memcpy will work.
//
// TODO: If a shared class has an atomic reference then using
// an atomic load may be more correct. Just make sure
// to use the fastest approach for the load op.
static if (is(T == class) && is(T == shared))
memcpy(&store, cast(const(void*)) &rhs, rhs.sizeof);
else
memcpy(&store, &rhs, rhs.sizeof);
static if (hasElaborateCopyConstructor!T)
{
typeid(T).postblit(&store);
}
}
else
{
static if (__traits(compiles, {new T(rhs);}))
{
auto p = new T(rhs);
}
else
{
auto p = new T;
*p = rhs;
}
memcpy(&store, &p, p.sizeof);
}
fptr = &handler!(T);
}
return this;
}
Variant opCall(P...)(auto ref P params)
{
Variant[P.length + 1] pack;
pack[0] = P.length;
foreach (i, _; params)
{
pack[i + 1] = params[i];
}
fptr(OpID.apply, &store, &pack);
return pack[0];
}
/** Returns true if and only if the $(D_PARAM VariantN) object
* holds a valid value (has been initialized with, or assigned
* from, a valid value).
* Example:
* ----
* Variant a;
* assert(!a.hasValue);
* Variant b;
* a = b;
* assert(!a.hasValue); // still no value
* a = 5;
* assert(a.hasValue);
* ----
*/
@property bool hasValue() const pure nothrow
{
// @@@BUG@@@ in compiler, the cast shouldn't be needed
return cast(typeof(&handler!(void))) fptr != &handler!(void);
}
/**
* If the $(D_PARAM VariantN) object holds a value of the
* $(I exact) type $(D_PARAM T), returns a pointer to that
* value. Otherwise, returns $(D_PARAM null). In cases
* where $(D_PARAM T) is statically disallowed, $(D_PARAM
* peek) will not compile.
*
* Example:
* ----
* Variant a = 5;
* auto b = a.peek!(int);
* assert(b !is null);
* *b = 6;
* assert(a == 6);
* ----
*/
@property inout(T)* peek(T)() inout
{
static if (!is(T == void))
static assert(allowed!(T), "Cannot store a " ~ T.stringof
~ " in a " ~ VariantN.stringof);
if (type != typeid(T))
return null;
static if (T.sizeof <= size)
return cast(inout T*)&store;
else
return *cast(inout T**)&store;
}
/**
* Returns the $(D_PARAM typeid) of the currently held value.
*/
@property TypeInfo type() const nothrow @trusted
{
scope(failure) assert(0);
TypeInfo result;
fptr(OpID.getTypeInfo, null, &result);
return result;
}
/**
* Returns $(D_PARAM true) if and only if the $(D_PARAM VariantN)
* object holds an object implicitly convertible to type $(D_PARAM
* U). Implicit convertibility is defined as per
* $(LINK2 std_traits.html#ImplicitConversionTargets,ImplicitConversionTargets).
*/
@property bool convertsTo(T)() const
{
TypeInfo info = typeid(T);
return fptr(OpID.testConversion, null, &info) == 0;
}
// private T[] testing123(T)(T*);
// /**
// * A workaround for the fact that functions cannot return
// * statically-sized arrays by value. Essentially $(D_PARAM
// * DecayStaticToDynamicArray!(T[N])) is an alias for $(D_PARAM
// * T[]) and $(D_PARAM DecayStaticToDynamicArray!(T)) is an alias
// * for $(D_PARAM T).
// */
// template DecayStaticToDynamicArray(T)
// {
// static if (isStaticArray!(T))
// {
// alias DecayStaticToDynamicArray = typeof(testing123(&T[0]));
// }
// else
// {
// alias DecayStaticToDynamicArray = T;
// }
// }
// static assert(is(DecayStaticToDynamicArray!(immutable(char)[21]) ==
// immutable(char)[]),
// DecayStaticToDynamicArray!(immutable(char)[21]).stringof);
/**
* Returns the value stored in the $(D_PARAM VariantN) object,
* implicitly converted to the requested type $(D_PARAM T), in
* fact $(D_PARAM DecayStaticToDynamicArray!(T)). If an implicit
* conversion is not possible, throws a $(D_PARAM
* VariantException).
*/
@property T get(T)() if (!is(T == const))
{
union Buf
{
TypeInfo info;
T result;
}
auto p = *cast(T**) &store;
Buf buf = { typeid(T) };
if (fptr(OpID.get, &store, &buf))
{
throw new VariantException(type, typeid(T));
}
return buf.result;
}
@property T get(T)() const if (is(T == const))
{
union Buf
{
TypeInfo info;
static if (is(T == shared))
shared(Unqual!T) result;
else
Unqual!T result;
}
auto p = *cast(T**) &store;
Buf buf = { typeid(T) };
if (fptr(OpID.get, cast(ubyte[size]*) &store, &buf))
{
throw new VariantException(type, typeid(T));
}
return buf.result;
}
/**
* Returns the value stored in the $(D_PARAM VariantN) object,
* explicitly converted (coerced) to the requested type $(D_PARAM
* T). If $(D_PARAM T) is a string type, the value is formatted as
* a string. If the $(D_PARAM VariantN) object is a string, a
* parse of the string to type $(D_PARAM T) is attempted. If a
* conversion is not possible, throws a $(D_PARAM
* VariantException).
*/
@property T coerce(T)()
{
static if (isNumeric!T || isBoolean!T)
{
if (convertsTo!real)
{
// maybe optimize this fella; handle ints separately
return to!T(get!real);
}
else if (convertsTo!(const(char)[]))
{
return to!T(get!(const(char)[]));
}
// I'm not sure why this doesn't convert to const(char),
// but apparently it doesn't (probably a deeper bug).
//
// Until that is fixed, this quick addition keeps a common
// function working. "10".coerce!int ought to work.
else if (convertsTo!(immutable(char)[]))
{
return to!T(get!(immutable(char)[]));
}
else
{
enforce(false, text("Type ", type, " does not convert to ",
typeid(T)));
assert(0);
}
}
else static if (is(T : Object))
{
return to!(T)(get!(Object));
}
else static if (isSomeString!(T))
{
return to!(T)(toString());
}
else
{
// Fix for bug 1649
static assert(false, "unsupported type for coercion");
}
}
/**
* Formats the stored value as a string.
*/
string toString()
{
string result;
fptr(OpID.toString, &store, &result) == 0 || assert(false);
return result;
}
/**
* Comparison for equality used by the "==" and "!=" operators.
*/
// returns 1 if the two are equal
bool opEquals(T)(auto ref T rhs) const
{
static if (is(Unqual!T == VariantN))
alias temp = rhs;
else
auto temp = VariantN(rhs);
return !fptr(OpID.equals, cast(ubyte[size]*) &store,
cast(void*) &temp);
}
// workaround for bug 10567 fix
int opCmp(ref const VariantN rhs) const
{
return (cast()this).opCmp!(VariantN)(cast()rhs);
}
/**
* Ordering comparison used by the "<", "<=", ">", and ">="
* operators. In case comparison is not sensible between the held
* value and $(D_PARAM rhs), an exception is thrown.
*/
int opCmp(T)(T rhs)
{
static if (is(T == VariantN))
alias temp = rhs;
else
auto temp = VariantN(rhs);
auto result = fptr(OpID.compare, &store, &temp);
if (result == ptrdiff_t.min)
{
throw new VariantException(type, temp.type);
}
assert(result >= -1 && result <= 1); // Should be true for opCmp.
return cast(int) result;
}
/**
* Computes the hash of the held value.
*/
size_t toHash() const nothrow @safe
{
return type.getHash(&store);
}
private VariantN opArithmetic(T, string op)(T other)
{
static if (isInstanceOf!(VariantN, T))
{
string tryUseType(string tp)
{
import std.string : format;
return q{
static if (allowed!%1$s && T.allowed!%1$s)
if (convertsTo!%1$s && other.convertsTo!%1$s)
return VariantN(get!%1$s %2$s other.get!%1$s);
}.format(tp, op);
}
mixin(tryUseType("uint"));
mixin(tryUseType("int"));
mixin(tryUseType("ulong"));
mixin(tryUseType("long"));
mixin(tryUseType("float"));
mixin(tryUseType("double"));
mixin(tryUseType("real"));
}
else
{
static if (allowed!T)
if (auto pv = peek!T) return VariantN(mixin("*pv " ~ op ~ " other"));
static if (allowed!uint && is(typeof(T.max) : uint) && isUnsigned!T)
if (convertsTo!uint) return VariantN(mixin("get!(uint) " ~ op ~ " other"));
static if (allowed!int && is(typeof(T.max) : int) && !isUnsigned!T)
if (convertsTo!int) return VariantN(mixin("get!(int) " ~ op ~ " other"));
static if (allowed!ulong && is(typeof(T.max) : ulong) && isUnsigned!T)
if (convertsTo!ulong) return VariantN(mixin("get!(ulong) " ~ op ~ " other"));
static if (allowed!long && is(typeof(T.max) : long) && !isUnsigned!T)
if (convertsTo!long) return VariantN(mixin("get!(long) " ~ op ~ " other"));
static if (allowed!float && is(T : float))
if (convertsTo!float) return VariantN(mixin("get!(float) " ~ op ~ " other"));
static if (allowed!double && is(T : double))
if (convertsTo!double) return VariantN(mixin("get!(double) " ~ op ~ " other"));
static if (allowed!real && is (T : real))
if (convertsTo!real) return VariantN(mixin("get!(real) " ~ op ~ " other"));
}
throw new VariantException("No possible match found for VariantN "~op~" "~T.stringof);
}
private VariantN opLogic(T, string op)(T other)
{
VariantN result;
static if (is(T == VariantN))
{
if (convertsTo!(uint) && other.convertsTo!(uint))
result = mixin("get!(uint) " ~ op ~ " other.get!(uint)");
else if (convertsTo!(int) && other.convertsTo!(int))
result = mixin("get!(int) " ~ op ~ " other.get!(int)");
else if (convertsTo!(ulong) && other.convertsTo!(ulong))
result = mixin("get!(ulong) " ~ op ~ " other.get!(ulong)");
else
result = mixin("get!(long) " ~ op ~ " other.get!(long)");
}
else
{
if (is(typeof(T.max) : uint) && T.min == 0 && convertsTo!(uint))
result = mixin("get!(uint) " ~ op ~ " other");
else if (is(typeof(T.max) : int) && T.min < 0 && convertsTo!(int))
result = mixin("get!(int) " ~ op ~ " other");
else if (is(typeof(T.max) : ulong) && T.min == 0
&& convertsTo!(ulong))
result = mixin("get!(ulong) " ~ op ~ " other");
else