forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvariant.d
3005 lines (2674 loc) · 84.1 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
$(HTTP erdani.org/publications/cuj-04-2002.html,discriminated union)
type (a.k.a.
$(HTTP en.wikipedia.org/wiki/Tagged_union,tagged union),
$(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.
A $(LREF Variant) object can hold a value of any type, with very few
restrictions (such as `shared` types and noncopyable types). Setting the value
is as immediate as assigning to the `Variant` object. To read back the value of
the appropriate type `T`, use the $(LREF get!T) call. To query whether a
`Variant` currently holds a value of type `T`, use $(LREF peek!T). To fetch the
exact type currently held, call $(LREF type), which returns the `TypeInfo` of
the current value.
In addition to $(LREF Variant), this module also defines the $(LREF Algebraic)
type constructor. Unlike `Variant`, `Algebraic` only allows a finite set of
types, which are specified in the instantiation (e.g. $(D Algebraic!(int,
string)) may only hold an `int` or a `string`).
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 - 2015.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.org, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/variant.d)
*/
module std.variant;
import std.meta, std.traits, std.typecons;
///
@system unittest
{
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");
// can also assign arrays
a = new int[42];
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
}
/++
Gives the `sizeof` the largest type given.
+/
template maxSize(T...)
{
static if (T.length == 1)
{
enum size_t maxSize = T[0].sizeof;
}
else
{
import std.algorithm.comparison : max;
enum size_t maxSize = max(T[0].sizeof, maxSize!(T[1 .. $]));
}
}
///
@safe unittest
{
static assert(maxSize!(int, long) == 8);
static assert(maxSize!(bool, byte) == 1);
struct Cat { int a, b, c; }
static assert(maxSize!(bool, Cat) == 12);
}
struct This;
private alias This2Variant(V, T...) = AliasSeq!(ReplaceType!(This, V, T));
/**
* Back-end type seldom used directly by user
* code. Two commonly-used types using `VariantN` are:
*
* $(OL $(LI $(LREF Algebraic): A closed discriminated union with a
* limited type universe (e.g., $(D Algebraic!(int, double,
* string)) only accepts these three types and rejects anything
* else).) $(LI $(LREF Variant): An open discriminated union allowing an
* unbounded set of types. If any of the types in the `Variant`
* are larger than the largest built-in type, they will automatically
* be boxed. This means that even large types will only be the size
* of a pointer within the `Variant`, but this also implies some
* overhead. `Variant` can accommodate all primitive types and
* all user-defined types.))
*
* Both `Algebraic` and `Variant` share $(D
* VariantN)'s interface. (See their respective documentations below.)
*
* `VariantN` is a discriminated union type parameterized
* with the largest size of the types stored (`maxDataSize`)
* and with the list of allowed types (`AllowedTypes`). If
* the list is empty, then any type up of size up to $(D
* maxDataSize) (rounded up for alignment) can be stored in a
* `VariantN` object without being boxed (types larger
* than this will be boxed).
*
*/
struct VariantN(size_t maxDataSize, AllowedTypesParam...)
{
/**
The list of allowed types. If empty, any type is allowed.
*/
alias AllowedTypes = This2Variant!(VariantN, AllowedTypesParam);
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 `T` is statically _allowed for
* storage inside a `VariantN` object by looking
* `T` up in `AllowedTypes`.
*/
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)
{
import std.conv : to;
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 = AliasSeq!(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 = AliasSeq!(ImmuTypes, ConstTypes, SharedConstTypes);
else static if (is(A == shared))
{
static if (is(A == const))
alias AllTypes = SharedConstTypes;
else
alias AllTypes = AliasSeq!(SharedTypes, SharedConstTypes);
}
else
{
static if (is(A == const))
alias AllTypes = ConstTypes;
else
alias AllTypes = AliasSeq!(MutaTypes, ConstTypes);
}
foreach (T ; AllTypes)
{
if (targetType != typeid(T))
continue;
static if (is(typeof(*cast(T*) target = *src)) ||
is(T == const(U), U) ||
is(T == shared(U), U) ||
is(T == shared const(U), U) ||
is(T == immutable(U), U))
{
import std.conv : emplaceRef;
auto zat = cast(T*) target;
if (src)
{
static if (T.sizeof > 0)
assert(target, "target must be non-null");
emplaceRef(*cast(Unqual!T*) zat, *cast(UA*) src);
}
}
else
{
// type T is not constructible from A
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)
{
static if (is(A == U[n], U, size_t n))
{
A* p = cast(A*)(new U[n]).ptr;
}
else
{
A* p = new A;
}
*cast(A**)&target.store = p;
}
}
tryPutting(zis, typeid(A), cast(void*) getPtr(&target.store))
|| assert(false);
target.fptr = &handler!(A);
break;
case OpID.get:
auto t = * cast(Tuple!(TypeInfo, void*)*) parm;
return !tryPutting(zis, t[0], t[1]);
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?
auto t = tuple(typeid(A), &temp.store);
if (rhsP.fptr(OpID.get, &rhsP.store, &t) == 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(Variant*) 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)
{
import std.conv : text;
import std.exception : enforce;
enforce(0, text("Cannot apply `()' to a value of type `",
A.stringof, "'."));
}
else
{
import std.conv : text;
import std.exception : enforce;
alias ParamTypes = Parameters!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)
{
zis.__xpostblit();
}
break;
case OpID.destruct:
static if (hasElaborateDestructor!A)
{
zis.__xdtor();
}
break;
default: assert(false);
}
return 0;
}
public:
/** Constructs a `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);
}
/// Allows assignment from a subset algebraic type
this(T : VariantN!(tsize, Types), size_t tsize, Types...)(T value)
if (!is(T : VariantN) && Types.length > 0 && allSatisfy!(allowed, Types))
{
opAssign(value);
}
static if (!AllowedTypes.length || anySatisfy!(hasElaborateCopyConstructor, AllowedTypes))
{
this(this)
{
fptr(OpID.postblit, &store, null);
}
}
static if (!AllowedTypes.length || anySatisfy!(hasElaborateDestructor, AllowedTypes))
{
~this()
{
// Infer the safety of the provided types
static if (AllowedTypes.length)
{
if (0)
{
AllowedTypes var;
}
}
(() @trusted => fptr(OpID.destruct, &store, null))();
}
}
/** Assigns a `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);
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 (!AllowedTypes.length || anySatisfy!(hasElaborateDestructor, AllowedTypes))
{
// Assignment should destruct previous value
fptr(OpID.destruct, &store, null);
}
static if (T.sizeof <= size)
{
import core.stdc.string : memcpy;
// rhs has already been copied onto the stack, so even if T is
// shared, it's not really shared. Therefore, we can safely
// remove the shared qualifier when copying, as we are only
// copying from the unshared stack.
//
// In addition, the storage location is not accessible outside
// the Variant, so even if shared data is stored there, it's
// not really shared, as it's copied out as well.
memcpy(&store, cast(const(void*)) &rhs, rhs.sizeof);
static if (hasElaborateCopyConstructor!T)
{
// Safer than using typeid's postblit function because it
// type-checks the postblit function against the qualifiers
// of the type.
(cast(T*)&store).__xpostblit();
}
}
else
{
import core.stdc.string : memcpy;
static if (__traits(compiles, {new T(T.init);}))
{
auto p = new T(rhs);
}
else static if (is(T == U[n], U, size_t n))
{
auto p = cast(T*)(new U[n]).ptr;
*p = rhs;
}
else
{
auto p = new T;
*p = rhs;
}
memcpy(&store, &p, p.sizeof);
}
fptr = &handler!(T);
}
return this;
}
// Allow assignment from another variant which is a subset of this one
VariantN opAssign(T : VariantN!(tsize, Types), size_t tsize, Types...)(T rhs)
if (!is(T : VariantN) && Types.length > 0 && allSatisfy!(allowed, Types))
{
// discover which type rhs is actually storing
foreach (V; T.AllowedTypes)
if (rhs.type == typeid(V))
return this = rhs.get!V;
assert(0, T.AllowedTypes.stringof);
}
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 `VariantN` object
* holds a valid value (has been initialized with, or assigned
* from, a valid value).
*/
@property bool hasValue() const pure nothrow
{
// @@@BUG@@@ in compiler, the cast shouldn't be needed
return cast(typeof(&handler!(void))) fptr != &handler!(void);
}
///
version(unittest)
@system unittest
{
Variant a;
assert(!a.hasValue);
Variant b;
a = b;
assert(!a.hasValue); // still no value
a = 5;
assert(a.hasValue);
}
/**
* If the `VariantN` object holds a value of the
* $(I exact) type `T`, returns a pointer to that
* value. Otherwise, returns `null`. In cases
* where `T` is statically disallowed, $(D
* peek) will not compile.
*/
@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;
}
///
version(unittest)
@system unittest
{
Variant a = 5;
auto b = a.peek!(int);
assert(b !is null);
*b = 6;
assert(a == 6);
}
/**
* Returns the `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 `true` if and only if the `VariantN`
* object holds an object implicitly convertible to type `T`.
* Implicit convertibility is defined as per
* $(REF_ALTTEXT ImplicitConversionTargets, ImplicitConversionTargets, std,traits).
*/
@property bool convertsTo(T)() const
{
TypeInfo info = typeid(T);
return fptr(OpID.testConversion, null, &info) == 0;
}
/**
Returns the value stored in the `VariantN` object, either by specifying the
needed type or the index in the list of allowed types. The latter overload
only applies to bounded variants (e.g. $(LREF Algebraic)).
Params:
T = The requested type. The currently stored value must implicitly convert
to the requested type, in fact `DecayStaticToDynamicArray!T`. If an
implicit conversion is not possible, throws a `VariantException`.
index = The index of the type among `AllowedTypesParam`, zero-based.
*/
@property inout(T) get(T)() inout
{
inout(T) result = void;
static if (is(T == shared))
alias R = shared Unqual!T;
else
alias R = Unqual!T;
auto buf = tuple(typeid(T), cast(R*)&result);
if (fptr(OpID.get, cast(ubyte[size]*) &store, &buf))
{
throw new VariantException(type, typeid(T));
}
return result;
}
/// Ditto
@property auto get(uint index)() inout
if (index < AllowedTypes.length)
{
foreach (i, T; AllowedTypes)
{
static if (index == i) return get!T;
}
assert(0);
}
/**
* Returns the value stored in the `VariantN` object,
* explicitly converted (coerced) to the requested type $(D
* T). If `T` is a string type, the value is formatted as
* a string. If the `VariantN` object is a string, a
* parse of the string to type `T` is attempted. If a
* conversion is not possible, throws a $(D
* VariantException).
*/
@property T coerce(T)()
{
import std.conv : to, text;
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
{
import std.exception : enforce;
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
if (allowed!T || is(Unqual!T == VariantN))
{
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 `rhs`, an exception is thrown.
*/
int opCmp(T)(T rhs)
if (allowed!T) // includes T == VariantN
{
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.format : 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");