-
-
Notifications
You must be signed in to change notification settings - Fork 706
/
Copy pathtypecons.d
8164 lines (7216 loc) · 221 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.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Tuple) $(TD
$(LREF isTuple)
$(LREF Tuple)
$(LREF tuple)
$(LREF reverse)
))
$(TR $(TD Flags) $(TD
$(LREF BitFlags)
$(LREF isBitFlagEnum)
$(LREF Flag)
$(LREF No)
$(LREF Yes)
))
$(TR $(TD Memory allocation) $(TD
$(LREF RefCounted)
$(LREF refCounted)
$(LREF RefCountedAutoInitialize)
$(LREF scoped)
$(LREF Unique)
))
$(TR $(TD Code generation) $(TD
$(LREF AutoImplement)
$(LREF BlackHole)
$(LREF generateAssertTrap)
$(LREF generateEmptyFunction)
$(LREF WhiteHole)
))
$(TR $(TD Nullable) $(TD
$(LREF Nullable)
$(LREF nullable)
$(LREF NullableRef)
$(LREF nullableRef)
))
$(TR $(TD Proxies) $(TD
$(LREF Proxy)
$(LREF rebindable)
$(LREF Rebindable)
$(LREF ReplaceType)
$(LREF unwrap)
$(LREF wrap)
))
$(TR $(TD Types) $(TD
$(LREF alignForSize)
$(LREF Ternary)
$(LREF Typedef)
$(LREF TypedefType)
$(LREF UnqualRef)
))
)
Copyright: Copyright the respective authors, 2008-
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Source: $(PHOBOSSRC std/_typecons.d)
Authors: $(HTTP erdani.org, Andrei Alexandrescu),
$(HTTP bartoszmilewski.wordpress.com, Bartosz Milewski),
Don Clugston,
Shin Fujishiro,
Kenji Hara
*/
module std.typecons;
import core.stdc.stdint : uintptr_t;
import std.meta; // : AliasSeq, allSatisfy;
import std.traits;
///
@safe unittest
{
// value tuples
alias Coord = Tuple!(int, "x", int, "y", int, "z");
Coord c;
c[1] = 1; // access by index
c.z = 1; // access by given name
assert(c == Coord(0, 1, 1));
// names can be omitted
alias DicEntry = Tuple!(string, string);
// tuples can also be constructed on instantiation
assert(tuple(2, 3, 4)[1] == 3);
// construction on instantiation works with names too
assert(tuple!("x", "y", "z")(2, 3, 4).y == 3);
// Rebindable references to const and immutable objects
{
class Widget { void foo() const @safe {} }
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;
}
}
/**
Encapsulates unique ownership of a resource.
When a $(D Unique!T) goes out of scope it will call $(D destroy)
on the resource $(D T) that it manages, unless it is transferred.
One important consequence of $(D destroy) is that it will call the
destructor of the resource $(D T). GC-managed references are not
guaranteed to be valid during a destructor call, but other members of
$(D T), such as file handles or pointers to $(D malloc) memory, will
still be valid during the destructor call. This allows the resource
$(D T) to deallocate or clean up any non-GC resources.
If it is desirable to persist a $(D Unique!T) outside of its original
scope, then it can be transferred. The transfer can be explicit, by
calling $(D release), or implicit, when returning Unique from a
function. The resource $(D T) can be a polymorphic class object or
instance of an interface, in which case Unique behaves polymorphically
too.
If $(D T) is a value type, then $(D Unique!T) will be implemented
as a reference to a $(D T).
*/
struct Unique(T)
{
/** Represents a reference to $(D T). Resolves to $(D T*) if $(D T) is a value type. */
static if (is(T == class) || is(T == interface))
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)))
{
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)
{
_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;
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))
{
_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))
{
// first delete any resource we own
destroy(this);
_p = u._p;
u._p = null;
}
~this()
{
if (_p !is null)
{
destroy(_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.
Same as calling std.algorithm.move on it.
*/
Unique release()
{
import std.algorithm.mutation : move;
return this.move;
}
/** Forwards member access to contents. */
mixin Proxy!_p;
/**
Postblit operator is undefined to prevent the cloning of $(D Unique) objects.
*/
@disable this(this);
private:
RefT _p;
}
///
@safe 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);
}
@system 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);
}
@system unittest
{
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);}));
auto ub2 = g(ub.release);
assert(ub.isEmpty);
assert(!ub2.isEmpty);
}
@system unittest
{
interface Bar
{
int val() const;
}
class BarImpl : Bar
{
static int count;
this()
{
count++;
}
~this()
{
count--;
}
int val() const { return 4; }
}
alias UBar = Unique!Bar;
UBar g(UBar u)
{
debug(Unique) writeln("inside g");
return u.release;
}
void consume(UBar u)
{
assert(u.val() == 4);
// Resource automatically deleted here
}
auto ub = UBar(new BarImpl);
assert(BarImpl.count == 1);
assert(!ub.isEmpty);
assert(ub.val == 4);
static assert(!__traits(compiles, {auto ub3 = g(ub);}));
auto ub2 = g(ub.release);
assert(ub.isEmpty);
assert(!ub2.isEmpty);
consume(ub2.release);
assert(BarImpl.count == 0);
}
@safe unittest
{
struct Foo
{
~this() { }
int val() const { return 3; }
@disable this(this);
}
alias UFoo = Unique!(Foo);
UFoo f(UFoo u)
{
return u.release;
}
auto uf = UFoo(new Foo);
assert(!uf.isEmpty);
assert(uf.val == 3);
static assert(!__traits(compiles, {auto uf3 = f(uf);}));
auto uf2 = f(uf.release);
assert(uf.isEmpty);
assert(!uf2.isEmpty);
}
// ensure Unique behaves correctly through const access paths
@system unittest
{
struct Bar {int val;}
struct Foo
{
Unique!Bar bar = new Bar;
}
Foo foo;
foo.bar.val = 6;
const Foo* ptr = &foo;
static assert(is(typeof(ptr) == const(Foo*)));
static assert(is(typeof(ptr.bar) == const(Unique!Bar)));
static assert(is(typeof(ptr.bar.val) == const(int)));
assert(ptr.bar.val == 6);
foo.bar.val = 7;
assert(ptr.bar.val == 7);
}
// Used in Tuple.toString
private template sharedToString(alias field)
if (is(typeof(field) == shared))
{
static immutable sharedToString = typeof(field).stringof;
}
private template sharedToString(alias field)
if (!is(typeof(field) == shared))
{
alias sharedToString = field;
}
private enum bool distinctFieldNames(names...) = __traits(compiles,
{
static foreach (name; names)
static if (is(typeof(name) : string))
mixin("enum int" ~ name ~ " = 0;");
});
@safe unittest
{
static assert(!distinctFieldNames!(string, "abc", string, "abc"));
static assert(distinctFieldNames!(string, "abc", int, "abd"));
static assert(!distinctFieldNames!(int, "abc", string, "abd", int, "abc"));
}
/**
_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. $(REF AliasSeq, std,meta) iteration), all of which use
zero-based indexing.
See_Also: $(LREF tuple).
Params:
Specs = A list of types (and optionally, member names) that the `Tuple` contains.
*/
template Tuple(Specs...)
if (distinctFieldNames!(Specs))
{
import std.meta : 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 = AliasSeq!();
}
else static if (is(Specs[0]))
{
static if (is(typeof(Specs[1]) : string))
{
alias parseSpecs =
AliasSeq!(FieldSpec!(Specs[0 .. 2]),
parseSpecs!(Specs[2 .. $]));
}
else
{
alias parseSpecs =
AliasSeq!(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 = "";
static foreach (i, val; fieldSpecs)
{{
immutable si = i.stringof;
decl ~= "alias _" ~ si ~ " = Identity!(field[" ~ si ~ "]);";
if (val.name.length != 0)
{
decl ~= "alias " ~ val.name ~ " = _" ~ si ~ ";";
}
}}
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 = AliasSeq!(spec.Type);
}
else
{
alias expandSpec = AliasSeq!(spec.Type, spec.name);
}
}
enum areCompatibleTuples(Tup1, Tup2, string op) = isTuple!Tup2 && is(typeof(
(ref Tup1 tup1, ref Tup2 tup2)
{
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;
static if (op == "=")
lhs = rhs;
else
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 types of the `Tuple`'s components.
*/
alias Types = staticMap!(extractType, fieldSpecs);
///
static if (Specs.length == 0) @safe unittest
{
alias Fields = Tuple!(int, "id", string, float);
static assert(is(Fields.Types == AliasSeq!(int, string, float)));
}
/**
* The names of the `Tuple`'s components. Unnamed fields have empty names.
*/
alias fieldNames = staticMap!(extractName, fieldSpecs);
///
static if (Specs.length == 0) @safe unittest
{
alias Fields = Tuple!(int, "id", string, float);
static assert(Fields.fieldNames == AliasSeq!("id", "", ""));
}
/**
* 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`'s components
* were listed as a list of values. (Ordinarily, a $(D Tuple) acts as a
* single value.)
*/
Types expand;
mixin(injectNamedFields());
///
static if (Specs.length == 0) @safe unittest
{
auto t1 = tuple(1, " hello ", 'a');
assert(t1.toString() == `Tuple!(int, string, char)(1, " hello ", 'a')`);
void takeSeveralTypes(int n, string s, bool b)
{
assert(n == 4 && s == "test" && b == false);
}
auto t2 = tuple(4, "test", false);
//t.expand acting as a list of values
takeSeveralTypes(t2.expand);
}
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.
*
* Params:
* values = A list of values that are either the same
* types as those given by the `Types` field
* of this `Tuple`, or can implicitly convert
* to those types. They must be in the same
* order as they appear in `Types`.
*/
static if (Types.length > 0)
{
this(Types values)
{
field[] = values[];
}
}
///
static if (Specs.length == 0) @safe unittest
{
alias ISD = Tuple!(int, string, double);
auto tup = ISD(1, "test", 3.2);
assert(tup.toString() == `Tuple!(int, string, double)(1, "test", 3.2)`);
}
/**
* Constructor taking a compatible array.
*
* Params:
* values = A compatible static array to build the `Tuple` from.
* Array slices are not supported.
*/
this(U, size_t n)(U[n] values)
if (n == Types.length && allSatisfy!(isBuildableFrom!U, Types))
{
foreach (i, _; Types)
{
field[i] = values[i];
}
}
///
static if (Specs.length == 0) @safe unittest
{
int[2] ints;
Tuple!(int, int) t = ints;
}
/**
* Constructor taking a compatible `Tuple`. Two `Tuple`s are compatible
* $(B iff) they are both of the same length, and, for each type `T` on the
* left-hand side, the corresponding type `U` on the right-hand side can
* implicitly convert to `T`.
*
* Params:
* another = A compatible `Tuple` to build from. Its type must be
* compatible with the target `Tuple`'s type.
*/
this(U)(U another)
if (areBuildCompatibleTuples!(typeof(this), U))
{
field[] = another.field[];
}
///
static if (Specs.length == 0) @safe unittest
{
alias IntVec = Tuple!(int, int, int);
alias DubVec = Tuple!(double, double, double);
IntVec iv = tuple(1, 1, 1);
//Ok, int can implicitly convert to double
DubVec dv = iv;
//Error: double cannot implicitly convert to int
//IntVec iv2 = dv;
}
/**
* Comparison for equality. Two `Tuple`s are considered equal
* $(B iff) they fulfill the following criteria:
*
* $(UL
* $(LI Each `Tuple` is the same length.)
* $(LI For each type `T` on the left-hand side and each type
* `U` on the right-hand side, values of type `T` can be
* compared with values of type `U`.)
* $(LI For each value `v1` on the left-hand side and each value
* `v2` on the right-hand side, the expression `v1 == v2` is
* true.))
*
* Params:
* rhs = The `Tuple` to compare against. It must meeting the criteria
* for comparison between `Tuple`s.
*
* Returns:
* true if both `Tuple`s are equal, otherwise false.
*/
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[];
}
///
static if (Specs.length == 0) @safe unittest
{
Tuple!(int, string) t1 = tuple(1, "test");
Tuple!(double, string) t2 = tuple(1.0, "test");
//Ok, int can be compared with double and
//both have a value of 1
assert(t1 == t2);
}
/**
* Comparison for ordering.
*
* Params:
* rhs = The `Tuple` to compare against. It must meet the criteria
* for comparison between `Tuple`s.
*
* Returns:
* For any values `v1` on the right-hand side and `v2` on the
* left-hand side:
*
* $(UL
* $(LI A negative integer if the expression `v1 < v2` is true.)
* $(LI A positive integer if the expression `v1 > v2` is true.)
* $(LI 0 if the expression `v1 == v2` is true.))
*/
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;
}
/**
The first `v1` for which `v1 > v2` is true determines
the result. This could lead to unexpected behaviour.
*/
static if (Specs.length == 0) @safe unittest
{
auto tup1 = tuple(1, 1, 1);
auto tup2 = tuple(1, 100, 100);
assert(tup1 < tup2);
//Only the first result matters for comparison
tup1[0] = 2;
assert(tup1 > tup2);
}
/**
* Assignment from another `Tuple`.
*
* Params:
* rhs = The source `Tuple` to assign from. Each element of the
* source `Tuple` must be implicitly assignable to each
* respective element of the target `Tuple`.
*/
ref Tuple opAssign(R)(auto ref R rhs)
if (areCompatibleTuples!(typeof(this), R, "="))
{
import std.algorithm.mutation : 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[];
}
return this;
}
/**
* Renames the elements of a $(LREF Tuple).
*
* `rename` uses the passed `names` and returns a new
* $(LREF Tuple) using these names, with the content
* unchanged.
* If fewer names are passed than there are members
* of the $(LREF Tuple) then those trailing members are unchanged.
* An empty string will remove the name for that member.
* It is an compile-time error to pass more names than
* there are members of the $(LREF Tuple).
*/
ref rename(names...)() return
if (names.length == 0 || allSatisfy!(isSomeString, typeof(names)))
{
import std.algorithm.comparison : equal;
// to circumvent bug 16418
static if (names.length == 0 || equal([names], [fieldNames]))
return this;
else
{
enum nT = Types.length;
enum nN = names.length;
static assert(nN <= nT, "Cannot have more names than tuple members");
alias allNames = AliasSeq!(names, fieldNames[nN .. $]);
template GetItem(size_t idx)
{
import std.array : empty;
static if (idx < nT)
alias GetItem = Alias!(Types[idx]);
else static if (allNames[idx - nT].empty)
alias GetItem = AliasSeq!();
else
alias GetItem = Alias!(allNames[idx - nT]);
}
import std.range : roundRobin, iota;
alias NewTupleT = Tuple!(staticMap!(GetItem, aliasSeqOf!(
roundRobin(iota(nT), iota(nT, 2*nT)))));
return *(() @trusted => cast(NewTupleT*)&this)();
}
}
///
static if (Specs.length == 0) @safe unittest
{
auto t0 = tuple(4, "hello");
auto t0Named = t0.rename!("val", "tag");
assert(t0Named.val == 4);
assert(t0Named.tag == "hello");
Tuple!(float, "dat", size_t[2], "pos") t1;
t1.pos = [2, 1];
auto t1Named = t1.rename!"height";
t1Named.height = 3.4f;
assert(t1Named.height == 3.4f);
assert(t1Named.pos == [2, 1]);
t1Named.rename!"altitude".altitude = 5;
assert(t1Named.height == 5);
Tuple!(int, "a", int, int, "c") t2;
t2 = tuple(3,4,5);
auto t2Named = t2.rename!("", "b");
// "a" no longer has a name
static assert(!hasMember!(typeof(t2Named), "a"));
assert(t2Named[0] == 3);
assert(t2Named.b == 4);
assert(t2Named.c == 5);
// not allowed to specify more names than the tuple has members
static assert(!__traits(compiles, t2.rename!("a","b","c","d")));
// use it in a range pipeline
import std.range : iota, zip;
import std.algorithm.iteration : map, sum;
auto res = zip(iota(1, 4), iota(10, 13))
.map!(t => t.rename!("a", "b"))
.map!(t => t.a * t.b)
.sum;
assert(res == 68);
}
/**
* Overload of $(LREF _rename) that takes an associative array
* `translate` as a template parameter, where the keys are
* either the names or indices of the members to be changed
* and the new names are the corresponding values.
* Every key in `translate` must be the name of a member of the
* $(LREF tuple).
* The same rules for empty strings apply as for the variadic
* template overload of $(LREF _rename).
*/
ref rename(alias translate)()
if (is(typeof(translate) : V[K], V, K) && isSomeString!V &&
(isSomeString!K || is(K : size_t)))
{
import std.range : ElementType;
static if (isSomeString!(ElementType!(typeof(translate.keys))))
{
{
import std.conv : to;
import std.algorithm.iteration : filter;
import std.algorithm.searching : canFind;
enum notFound = translate.keys
.filter!(k => fieldNames.canFind(k) == -1);
static assert(notFound.empty, "Cannot find members "
~ notFound.to!string ~ " in type "
~ typeof(this).stringof);
}
return this.rename!(aliasSeqOf!(
{
import std.array : empty;
auto names = [fieldNames];
foreach (ref n; names)
if (!n.empty)
if (auto p = n in translate)
n = *p;
return names;
}()));
}
else
{
{
import std.algorithm.iteration : filter;
import std.conv : to;
enum invalid = translate.keys.
filter!(k => k < 0 || k >= this.length);
static assert(invalid.empty, "Indices " ~ invalid.to!string