/
typecons.d
5077 lines (4516 loc) · 136 KB
/
typecons.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 variety of type constructors, i.e., templates
that allow construction of new, useful general-purpose types.
Source: $(PHOBOSSRC std/_typecons.d)
Macros:
WIKI = Phobos/StdVariant
Synopsis:
----
// value tuples
alias Coord = Tuple!(float, "x", float, "y", float, "z");
Coord c;
c[1] = 1; // access by index
c.z = 1; // access by given name
alias DicEntry = Tuple!(string, string); // names can be omitted
// Rebindable references to const and immutable objects
void bar()
{
const w1 = new Widget, w2 = new Widget;
w1.foo();
// w1 = w2 would not work; can't rebind const object
auto r = Rebindable!(const Widget)(w1);
// invoke method as if r were a Widget object
r.foo();
// rebind r to refer to another object
r = w2;
}
----
Copyright: Copyright the respective authors, 2008-
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB erdani.org, Andrei Alexandrescu),
$(WEB bartoszmilewski.wordpress.com, Bartosz Milewski),
Don Clugston,
Shin Fujishiro,
Kenji Hara
*/
module std.typecons;
import std.traits, std.range;
import std.typetuple : TypeTuple, allSatisfy;
debug(Unique) import std.stdio;
/**
Encapsulates unique ownership of a resource. Resource of type $(D T) is
deleted at the end of the scope, unless it is transferred. The
transfer can be explicit, by calling $(D release), or implicit, when
returning Unique from a function. The resource can be a polymorphic
class object, in which case Unique behaves polymorphically too.
*/
struct Unique(T)
{
/** Represents a reference to $(D T). Resolves to $(D T*) if $(D T) is a value type. */
static if (is(T:Object))
alias RefT = T;
else
alias RefT = T*;
public:
// Deferred in case we get some language support for checking uniqueness.
version(None)
/**
Allows safe construction of $(D Unique). It creates the resource and
guarantees unique ownership of it (unless $(D T) publishes aliases of
$(D this)).
Note: Nested structs/classes cannot be created.
Params:
args = Arguments to pass to $(D T)'s constructor.
---
static class C {}
auto u = Unique!(C).create();
---
*/
static Unique!T create(A...)(auto ref A args)
if (__traits(compiles, new T(args)))
{
debug(Unique) writeln("Unique.create for ", T.stringof);
Unique!T u;
u._p = new T(args);
return u;
}
/**
Constructor that takes an rvalue.
It will ensure uniqueness, as long as the rvalue
isn't just a view on an lvalue (e.g., a cast).
Typical usage:
----
Unique!Foo f = new Foo;
----
*/
this(RefT p)
{
debug(Unique) writeln("Unique constructor with rvalue");
_p = p;
}
/**
Constructor that takes an lvalue. It nulls its source.
The nulling will ensure uniqueness as long as there
are no previous aliases to the source.
*/
this(ref RefT p)
{
_p = p;
debug(Unique) writeln("Unique constructor nulling source");
p = null;
assert(p is null);
}
/**
Constructor that takes a $(D Unique) of a type that is convertible to our type.
Typically used to transfer a $(D Unique) rvalue of derived type to
a $(D Unique) of base type.
Example:
---
class C : Object {}
Unique!C uc = new C;
Unique!Object uo = uc.release;
---
*/
this(U)(Unique!U u)
if (is(u.RefT:RefT))
{
debug(Unique) writeln("Unique constructor converting from ", U.stringof);
_p = u._p;
u._p = null;
}
/// Transfer ownership from a $(D Unique) of a type that is convertible to our type.
void opAssign(U)(Unique!U u)
if (is(u.RefT:RefT))
{
debug(Unique) writeln("Unique opAssign converting from ", U.stringof);
// first delete any resource we own
destroy(this);
_p = u._p;
u._p = null;
}
~this()
{
debug(Unique) writeln("Unique destructor of ", (_p is null)? null: _p);
if (_p !is null) delete _p;
_p = null;
}
/** Returns whether the resource exists. */
@property bool isEmpty() const
{
return _p is null;
}
/** Transfer ownership to a $(D Unique) rvalue. Nullifies the current contents. */
Unique release()
{
debug(Unique) writeln("Release");
auto u = Unique(_p);
assert(_p is null);
debug(Unique) writeln("return from Release");
return u;
}
/** Forwards member access to contents. */
RefT opDot() { return _p; }
/**
Postblit operator is undefined to prevent the cloning of $(D Unique) objects.
*/
@disable this(this);
private:
RefT _p;
}
///
unittest
{
static struct S
{
int i;
this(int i){this.i = i;}
}
Unique!S produce()
{
// Construct a unique instance of S on the heap
Unique!S ut = new S(5);
// Implicit transfer of ownership
return ut;
}
// Borrow a unique resource by ref
void increment(ref Unique!S ur)
{
ur.i++;
}
void consume(Unique!S u2)
{
assert(u2.i == 6);
// Resource automatically deleted here
}
Unique!S u1;
assert(u1.isEmpty);
u1 = produce();
increment(u1);
assert(u1.i == 6);
//consume(u1); // Error: u1 is not copyable
// Transfer ownership of the resource
consume(u1.release);
assert(u1.isEmpty);
}
unittest
{
// test conversion to base ref
int deleted = 0;
class C
{
~this(){deleted++;}
}
// constructor conversion
Unique!Object u = Unique!C(new C);
static assert(!__traits(compiles, {u = new C;}));
assert(!u.isEmpty);
destroy(u);
assert(deleted == 1);
Unique!C uc = new C;
static assert(!__traits(compiles, {Unique!Object uo = uc;}));
Unique!Object uo = new C;
// opAssign conversion, deleting uo resource first
uo = uc.release;
assert(uc.isEmpty);
assert(!uo.isEmpty);
assert(deleted == 2);
}
unittest
{
debug(Unique) writeln("Unique class");
class Bar
{
~this() { debug(Unique) writeln(" Bar destructor"); }
int val() const { return 4; }
}
alias UBar = Unique!(Bar);
UBar g(UBar u)
{
debug(Unique) writeln("inside g");
return u.release;
}
auto ub = UBar(new Bar);
assert(!ub.isEmpty);
assert(ub.val == 4);
static assert(!__traits(compiles, {auto ub3 = g(ub);}));
debug(Unique) writeln("Calling g");
auto ub2 = g(ub.release);
debug(Unique) writeln("Returned from g");
assert(ub.isEmpty);
assert(!ub2.isEmpty);
}
unittest
{
debug(Unique) writeln("Unique struct");
struct Foo
{
~this() { debug(Unique) writeln(" Foo destructor"); }
int val() const { return 3; }
}
alias UFoo = Unique!(Foo);
UFoo f(UFoo u)
{
debug(Unique) writeln("inside f");
return u.release;
}
auto uf = UFoo(new Foo);
assert(!uf.isEmpty);
assert(uf.val == 3);
static assert(!__traits(compiles, {auto uf3 = f(uf);}));
debug(Unique) writeln("Unique struct: calling f");
auto uf2 = f(uf.release);
debug(Unique) writeln("Unique struct: returned from f");
assert(uf.isEmpty);
assert(!uf2.isEmpty);
}
/**
Tuple of values, for example $(D Tuple!(int, string)) is a record that
stores an $(D int) and a $(D string). $(D Tuple) can be used to bundle
values together, notably when returning multiple values from a
function. If $(D obj) is a tuple, the individual members are
accessible with the syntax $(D obj[0]) for the first field, $(D obj[1])
for the second, and so on.
The choice of zero-based indexing instead of one-base indexing was
motivated by the ability to use value tuples with various compile-time
loop constructs (e.g. type tuple iteration), all of which use
zero-based indexing.
Example:
----
Tuple!(int, int) point;
// assign coordinates
point[0] = 5;
point[1] = 6;
// read coordinates
auto x = point[0];
auto y = point[1];
----
Tuple members can be named. It is legal to mix named and unnamed
members. The method above is still applicable to all fields.
Example:
----
alias Entry = Tuple!(int, "index", string, "value");
Entry e;
e.index = 4;
e.value = "Hello";
assert(e[1] == "Hello");
assert(e[0] == 4);
----
Tuples with named fields are distinct types from tuples with unnamed
fields, i.e. each naming imparts a separate type for the tuple. Two
tuple differing in naming only are still distinct, even though they
might have the same structure.
Example:
----
Tuple!(int, "x", int, "y") point1;
Tuple!(int, int) point2;
assert(!is(typeof(point1) == typeof(point2))); // passes
----
*/
template Tuple(Specs...)
{
import std.typetuple : staticMap;
// Parse (type,name) pairs (FieldSpecs) out of the specified
// arguments. Some fields would have name, others not.
template parseSpecs(Specs...)
{
static if (Specs.length == 0)
{
alias parseSpecs = TypeTuple!();
}
else static if (is(Specs[0]))
{
static if (is(typeof(Specs[1]) : string))
{
alias parseSpecs =
TypeTuple!(FieldSpec!(Specs[0 .. 2]),
parseSpecs!(Specs[2 .. $]));
}
else
{
alias parseSpecs =
TypeTuple!(FieldSpec!(Specs[0]),
parseSpecs!(Specs[1 .. $]));
}
}
else
{
static assert(0, "Attempted to instantiate Tuple with an "
~"invalid argument: "~ Specs[0].stringof);
}
}
template FieldSpec(T, string s = "")
{
alias Type = T;
alias name = s;
}
alias fieldSpecs = parseSpecs!Specs;
// Used with staticMap.
alias extractType(alias spec) = spec.Type;
alias extractName(alias spec) = spec.name;
// Generates named fields as follows:
// alias name_0 = Identity!(field[0]);
// alias name_1 = Identity!(field[1]);
// :
// NOTE: field[k] is an expression (which yields a symbol of a
// variable) and can't be aliased directly.
string injectNamedFields()
{
string decl = "";
foreach (i, name; staticMap!(extractName, fieldSpecs))
{
import std.string : format;
decl ~= format("alias _%s = Identity!(field[%s]);", i, i);
if (name.length != 0)
{
decl ~= format("alias %s = _%s;", name, i);
}
}
return decl;
}
// Returns Specs for a subtuple this[from .. to] preserving field
// names if any.
alias sliceSpecs(size_t from, size_t to) =
staticMap!(expandSpec, fieldSpecs[from .. to]);
template expandSpec(alias spec)
{
static if (spec.name.length == 0)
{
alias expandSpec = TypeTuple!(spec.Type);
}
else
{
alias expandSpec = TypeTuple!(spec.Type, spec.name);
}
}
enum areCompatibleTuples(Tup1, Tup2, string op) = isTuple!Tup2 && is(typeof(
{
Tup1 tup1 = void;
Tup2 tup2 = void;
static assert(tup1.field.length == tup2.field.length);
foreach (i, _; Tup1.Types)
{
auto lhs = typeof(tup1.field[i]).init;
auto rhs = typeof(tup2.field[i]).init;
auto result = mixin("lhs "~op~" rhs");
}
}));
enum areBuildCompatibleTuples(Tup1, Tup2) = isTuple!Tup2 && is(typeof(
{
static assert(Tup1.Types.length == Tup2.Types.length);
foreach (i, _; Tup1.Types)
static assert(isBuildable!(Tup1.Types[i], Tup2.Types[i]));
}));
/+ Returns $(D true) iff a $(D T) can be initialized from a $(D U). +/
enum isBuildable(T, U) = is(typeof(
{
U u = U.init;
T t = u;
}));
/+ Helper for partial instanciation +/
template isBuildableFrom(U)
{
enum isBuildableFrom(T) = isBuildable!(T, U);
}
struct Tuple
{
/**
* The type of the tuple's components.
*/
alias Types = staticMap!(extractType, fieldSpecs);
/**
* The names of the tuple's components. Unnamed fields have empty names.
*
* Examples:
* ----
* alias Fields = Tuple!(int, "id", string, float);
* static assert(Fields.fieldNames == TypeTuple!("id", "", ""));
* ----
*/
alias fieldNames = staticMap!(extractName, fieldSpecs);
/**
* Use $(D t.expand) for a tuple $(D t) to expand it into its
* components. The result of $(D expand) acts as if the tuple components
* were listed as a list of values. (Ordinarily, a $(D Tuple) acts as a
* single value.)
*
* Examples:
* ----
* auto t = tuple(1, " hello ", 2.3);
* writeln(t); // Tuple!(int, string, double)(1, " hello ", 2.3)
* writeln(t.expand); // 1 hello 2.3
* ----
*/
Types expand;
mixin(injectNamedFields());
static if (is(Specs))
{
// This is mostly to make t[n] work.
alias expand this;
}
else
{
@property
ref inout(Tuple!Types) _Tuple_super() inout @trusted
{
foreach (i, _; Types) // Rely on the field layout
{
static assert(typeof(return).init.tupleof[i].offsetof ==
expand[i].offsetof);
}
return *cast(typeof(return)*) &(field[0]);
}
// This is mostly to make t[n] work.
alias _Tuple_super this;
}
// backwards compatibility
alias field = expand;
/**
* Constructor taking one value for each field.
*/
static if (Types.length > 0)
{
this(Types values)
{
field[] = values[];
}
}
/**
* Constructor taking a compatible array.
*
* Examples:
* ----
* int[2] ints;
* Tuple!(int, int) t = ints;
* ----
*/
this(U, size_t n)(U[n] values)
if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types))
{
foreach (i, _; Types)
{
field[i] = values[i];
}
}
/**
* Constructor taking a compatible tuple.
*/
this(U)(U another)
if (areBuildCompatibleTuples!(typeof(this), U))
{
field[] = another.field[];
}
/**
* Comparison for equality.
*/
bool opEquals(R)(R rhs)
if (areCompatibleTuples!(typeof(this), R, "=="))
{
return field[] == rhs.field[];
}
/// ditto
bool opEquals(R)(R rhs) const
if (areCompatibleTuples!(typeof(this), R, "=="))
{
return field[] == rhs.field[];
}
/**
* Comparison for ordering.
*/
int opCmp(R)(R rhs)
if (areCompatibleTuples!(typeof(this), R, "<"))
{
foreach (i, Unused; Types)
{
if (field[i] != rhs.field[i])
{
return field[i] < rhs.field[i] ? -1 : 1;
}
}
return 0;
}
/// ditto
int opCmp(R)(R rhs) const
if (areCompatibleTuples!(typeof(this), R, "<"))
{
foreach (i, Unused; Types)
{
if (field[i] != rhs.field[i])
{
return field[i] < rhs.field[i] ? -1 : 1;
}
}
return 0;
}
/**
* Assignment from another tuple. Each element of the source must be
* implicitly assignable to the respective element of the target.
*/
void opAssign(R)(auto ref R rhs)
if (areCompatibleTuples!(typeof(this), R, "="))
{
import std.algorithm : swap;
static if (is(R : Tuple!Types) && !__traits(isRef, rhs))
{
if (__ctfe)
{
// Cannot use swap at compile time
field[] = rhs.field[];
}
else
{
// Use swap-and-destroy to optimize rvalue assignment
swap!(Tuple!Types)(this, rhs);
}
}
else
{
// Do not swap; opAssign should be called on the fields.
field[] = rhs.field[];
}
}
/**
* Takes a slice of the tuple.
*
* Examples:
* ----
* Tuple!(int, string, float, double) a;
* a[1] = "abc";
* a[2] = 4.5;
* auto s = a.slice!(1, 3);
* static assert(is(typeof(s) == Tuple!(string, float)));
* assert(s[0] == "abc" && s[1] == 4.5);
* ----
*/
@property
ref Tuple!(sliceSpecs!(from, to)) slice(size_t from, size_t to)() @trusted
if (from <= to && to <= Types.length)
{
return *cast(typeof(return)*) &(field[from]);
}
size_t toHash() const nothrow @trusted
{
size_t h = 0;
foreach (i, T; Types)
h += typeid(T).getHash(cast(const void*)&field[i]);
return h;
}
/**
* Converts to string.
*/
static if (allSatisfy!(isPrintable, Types))
string toString()
{
enum header = typeof(this).stringof ~ "(",
footer = ")",
separator = ", ";
Appender!string w;
w.put(header);
foreach (i, Unused; Types)
{
static if (i > 0)
{
w.put(separator);
}
// TODO: Change this once toString() works for shared objects.
static if (is(Unused == class) && is(Unused == shared))
formattedWrite(w, "%s", field[i].stringof);
else
{
import std.format : FormatSpec, formatElement;
FormatSpec!char f; // "%s"
formatElement(w, field[i], f);
}
}
w.put(footer);
return w.data;
}
}
}
private enum bool isPrintable(T) =
is(typeof({
import std.format : formattedWrite;
Appender!string w;
formattedWrite(w, "%s", T.init);
}));
/**
Return a copy of a Tuple with its fields in reverse order.
*/
ReverseTupleType!T reverse(T)(T t)
if (isTuple!T)
{
import std.typetuple : Reverse;
// @@@BUG@@@ Cannot be an internal function due to forward reference issues.
// @@@BUG@@@ 9929 Need 'this' when calling template with expanded tuple
// return tuple(Reverse!(t.expand));
typeof(return) result;
auto tup = t.expand;
result.expand = Reverse!tup;
return result;
}
///
unittest
{
auto tup = tuple(1, "2");
assert(tup.reverse == tuple("2", 1));
}
/* Get a Tuple type with the reverse specification of Tuple T. */
private template ReverseTupleType(T)
if (isTuple!T)
{
static if (is(T : Tuple!A, A...))
alias ReverseTupleType = Tuple!(ReverseTupleSpecs!A);
}
/* Reverse the Specs of a Tuple. */
private template ReverseTupleSpecs(T...)
{
static if (T.length > 1)
{
static if (is(typeof(T[$-1]) : string))
{
alias ReverseTupleSpecs = TypeTuple!(T[$-2], T[$-1], ReverseTupleSpecs!(T[0 .. $-2]));
}
else
{
alias ReverseTupleSpecs = TypeTuple!(T[$-1], ReverseTupleSpecs!(T[0 .. $-1]));
}
}
else
{
alias ReverseTupleSpecs = T;
}
}
unittest
{
{
Tuple!(int, "a", int, "b") nosh;
static assert(nosh.length == 2);
nosh.a = 5;
nosh.b = 6;
assert(nosh.a == 5);
assert(nosh.b == 6);
}
{
Tuple!(short, double) b;
static assert(b.length == 2);
b[1] = 5;
auto a = Tuple!(int, real)(b);
assert(a[0] == 0 && a[1] == 5);
a = Tuple!(int, real)(1, 2);
assert(a[0] == 1 && a[1] == 2);
auto c = Tuple!(int, "a", double, "b")(a);
assert(c[0] == 1 && c[1] == 2);
}
{
Tuple!(int, real) nosh;
nosh[0] = 5;
nosh[1] = 0;
assert(nosh[0] == 5 && nosh[1] == 0);
assert(nosh.toString() == "Tuple!(int, real)(5, 0)", nosh.toString());
Tuple!(int, int) yessh;
nosh = yessh;
}
{
Tuple!(int, string) t;
t[0] = 10;
t[1] = "str";
assert(t[0] == 10 && t[1] == "str");
assert(t.toString() == `Tuple!(int, string)(10, "str")`, t.toString());
}
{
Tuple!(int, "a", double, "b") x;
static assert(x.a.offsetof == x[0].offsetof);
static assert(x.b.offsetof == x[1].offsetof);
x.b = 4.5;
x.a = 5;
assert(x[0] == 5 && x[1] == 4.5);
assert(x.a == 5 && x.b == 4.5);
}
// indexing
{
Tuple!(int, real) t;
static assert(is(typeof(t[0]) == int));
static assert(is(typeof(t[1]) == real));
int* p0 = &t[0];
real* p1 = &t[1];
t[0] = 10;
t[1] = -200.0L;
assert(*p0 == t[0]);
assert(*p1 == t[1]);
}
// slicing
{
Tuple!(int, "x", real, "y", double, "z", string) t;
t[0] = 10;
t[1] = 11;
t[2] = 12;
t[3] = "abc";
auto a = t.slice!(0, 3);
assert(a.length == 3);
assert(a.x == t.x);
assert(a.y == t.y);
assert(a.z == t.z);
auto b = t.slice!(2, 4);
assert(b.length == 2);
assert(b.z == t.z);
assert(b[1] == t[3]);
}
// nesting
{
Tuple!(Tuple!(int, real), Tuple!(string, "s")) t;
static assert(is(typeof(t[0]) == Tuple!(int, real)));
static assert(is(typeof(t[1]) == Tuple!(string, "s")));
static assert(is(typeof(t[0][0]) == int));
static assert(is(typeof(t[0][1]) == real));
static assert(is(typeof(t[1].s) == string));
t[0] = tuple(10, 20.0L);
t[1].s = "abc";
assert(t[0][0] == 10);
assert(t[0][1] == 20.0L);
assert(t[1].s == "abc");
}
// non-POD
{
static struct S
{
int count;
this(this) { ++count; }
~this() { --count; }
void opAssign(S rhs) { count = rhs.count; }
}
Tuple!(S, S) ss;
Tuple!(S, S) ssCopy = ss;
assert(ssCopy[0].count == 1);
assert(ssCopy[1].count == 1);
ssCopy[1] = ssCopy[0];
assert(ssCopy[1].count == 2);
}
// bug 2800
{
static struct R
{
Tuple!(int, int) _front;
@property ref Tuple!(int, int) front() { return _front; }
@property bool empty() { return _front[0] >= 10; }
void popFront() { ++_front[0]; }
}
foreach (a; R())
{
static assert(is(typeof(a) == Tuple!(int, int)));
assert(0 <= a[0] && a[0] < 10);
assert(a[1] == 0);
}
}
// Construction with compatible elements
{
auto t1 = Tuple!(int, double)(1, 1);
// 8702
auto t8702a = tuple(tuple(1));
auto t8702b = Tuple!(Tuple!(int))(Tuple!(int)(1));
}
// Construction with compatible tuple
{
Tuple!(int, int) x;
x[0] = 10;
x[1] = 20;
Tuple!(int, "a", double, "b") y = x;
assert(y.a == 10);
assert(y.b == 20);
// incompatible
static assert(!__traits(compiles, Tuple!(int, int)(y)));
}
// 6275
{
const int x = 1;
auto t1 = tuple(x);
alias T = Tuple!(const(int));
auto t2 = T(1);
}
// 9431
{
alias T = Tuple!(int[1][]);
auto t = T([[10]]);
}
// 7666
{
auto tup = tuple(1, "2");
assert(tup.reverse == tuple("2", 1));
}
{
Tuple!(int, "x", string, "y") tup = tuple(1, "2");
auto rev = tup.reverse;
assert(rev == tuple("2", 1));
assert(rev.x == 1 && rev.y == "2");
}
{
Tuple!(wchar, dchar, int, "x", string, "y", char, byte, float) tup;
tup = tuple('a', 'b', 3, "4", 'c', cast(byte)0x0D, 0.00);
auto rev = tup.reverse;
assert(rev == tuple(0.00, cast(byte)0x0D, 'c', "4", 3, 'b', 'a'));
assert(rev.x == 3 && rev.y == "4");
}
}
unittest
{
// opEquals
{
struct Equ1 { bool opEquals(Equ1) { return true; } }
auto tm1 = tuple(Equ1.init);
const tc1 = tuple(Equ1.init);
static assert( is(typeof(tm1 == tm1)));
static assert(!is(typeof(tm1 == tc1)));
static assert(!is(typeof(tc1 == tm1)));
static assert(!is(typeof(tc1 == tc1)));
struct Equ2 { bool opEquals(const Equ2) const { return true; } }
auto tm2 = tuple(Equ2.init);
const tc2 = tuple(Equ2.init);
static assert( is(typeof(tm2 == tm2)));
static assert( is(typeof(tm2 == tc2)));
static assert( is(typeof(tc2 == tm2)));
static assert( is(typeof(tc2 == tc2)));
struct Equ3 { bool opEquals(T)(T) { return true; } }
auto tm3 = tuple(Equ3.init); // bugzilla 8686
const tc3 = tuple(Equ3.init);
static assert( is(typeof(tm3 == tm3)));
static assert( is(typeof(tm3 == tc3)));
static assert(!is(typeof(tc3 == tm3)));
static assert(!is(typeof(tc3 == tc3)));
struct Equ4 { bool opEquals(T)(T) const { return true; } }
auto tm4 = tuple(Equ4.init);
const tc4 = tuple(Equ4.init);
static assert( is(typeof(tm4 == tm4)));
static assert( is(typeof(tm4 == tc4)));
static assert( is(typeof(tc4 == tm4)));
static assert( is(typeof(tc4 == tc4)));
}
// opCmp
{
struct Cmp1 { int opCmp(Cmp1) { return 0; } }
auto tm1 = tuple(Cmp1.init);
const tc1 = tuple(Cmp1.init);
static assert( is(typeof(tm1 < tm1)));
static assert(!is(typeof(tm1 < tc1)));
static assert(!is(typeof(tc1 < tm1)));
static assert(!is(typeof(tc1 < tc1)));
struct Cmp2 { int opCmp(const Cmp2) const { return 0; } }
auto tm2 = tuple(Cmp2.init);
const tc2 = tuple(Cmp2.init);
static assert( is(typeof(tm2 < tm2)));
static assert( is(typeof(tm2 < tc2)));
static assert( is(typeof(tc2 < tm2)));
static assert( is(typeof(tc2 < tc2)));
struct Cmp3 { int opCmp(T)(T) { return 0; } }
auto tm3 = tuple(Cmp3.init);
const tc3 = tuple(Cmp3.init);
static assert( is(typeof(tm3 < tm3)));
static assert( is(typeof(tm3 < tc3)));
static assert(!is(typeof(tc3 < tm3)));
static assert(!is(typeof(tc3 < tc3)));
struct Cmp4 { int opCmp(T)(T) const { return 0; } }
auto tm4 = tuple(Cmp4.init);
const tc4 = tuple(Cmp4.init);
static assert( is(typeof(tm4 < tm4)));
static assert( is(typeof(tm4 < tc4)));
static assert( is(typeof(tc4 < tm4)));
static assert( is(typeof(tc4 < tc4)));
}
{
int[2] ints = [ 1, 2 ];
Tuple!(int, int) t = ints;
assert(t[0] == 1 && t[1] == 2);