forked from dlang/phobos
/
array.d
2621 lines (2295 loc) · 72.5 KB
/
array.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.
/**
Functions and types that manipulate built-in arrays.
Copyright: Copyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB erdani.org, Andrei Alexandrescu) and Jonathan M Davis
Source: $(PHOBOSSRC std/_array.d)
*/
module std.array;
import core.memory, core.bitop;
import std.algorithm, std.ascii, std.conv, std.exception, std.range, std.string,
std.traits, std.typecons, std.typetuple, std.uni, std.utf;
import std.c.string : memcpy;
version(unittest) import core.exception, std.stdio;
/**
Returns a newly-allocated dynamic array consisting of a copy of the
input range, static array, dynamic array, or class or struct with an
$(D opApply) function $(D r). Note that narrow strings are handled as
a special case in an overload.
Example:
$(D_RUN_CODE
$(ARGS
----
auto a = array([1, 2, 3, 4, 5][]);
assert(a == [ 1, 2, 3, 4, 5 ]);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
ForeachType!Range[] array(Range)(Range r)
if (isIterable!Range && !isNarrowString!Range)
{
alias ForeachType!Range E;
static if (hasLength!Range)
{
if(r.length == 0) return null;
auto result = uninitializedArray!(Unqual!(E)[])(r.length);
size_t i = 0;
foreach (e; r)
{
// hacky
static if (is(typeof(e.opAssign(e))))
{
// this should be in-place construction
emplace!E(result.ptr + i, e);
}
else
{
result[i] = e;
}
i++;
}
return cast(E[])result;
}
else
{
auto a = appender!(E[])();
foreach (e; r)
{
a.put(e);
}
return a.data;
}
}
/**
Convert a narrow string to an array type that fully supports random access.
This is handled as a special case and always returns a $(D dchar[]),
$(D const(dchar)[]), or $(D immutable(dchar)[]) depending on the constness of
the input.
*/
ElementType!String[] array(String)(String str) if (isNarrowString!String)
{
return to!(typeof(return))(str);
}
unittest
{
static struct TestArray { int x; string toString() { return .to!string(x); } }
static struct OpAssign
{
uint num;
this(uint num) { this.num = num; }
// Templating opAssign to make sure the bugs with opAssign being
// templated are fixed.
void opAssign(T)(T rhs) { this.num = rhs.num; }
}
static struct OpApply
{
int opApply(int delegate(ref int) dg)
{
int res;
foreach(i; 0..10)
{
res = dg(i);
if(res) break;
}
return res;
}
}
auto a = array([1, 2, 3, 4, 5][]);
//writeln(a);
assert(a == [ 1, 2, 3, 4, 5 ]);
auto b = array([TestArray(1), TestArray(2)][]);
//writeln(b);
class C
{
int x;
this(int y) { x = y; }
override string toString() const { return .to!string(x); }
}
auto c = array([new C(1), new C(2)][]);
//writeln(c);
auto d = array([1.0, 2.2, 3][]);
assert(is(typeof(d) == double[]));
//writeln(d);
auto e = [OpAssign(1), OpAssign(2)];
auto f = array(e);
assert(e == f);
assert(array(OpApply.init) == [0,1,2,3,4,5,6,7,8,9]);
assert(array("ABC") == "ABC"d);
assert(array("ABC".dup) == "ABC"d.dup);
}
//Bug# 8233
unittest
{
assert(array("hello world"d) == "hello world"d);
immutable a = [1, 2, 3, 4, 5];
assert(array(a) == a);
const b = a;
assert(array(b) == a);
//To verify that the opAssign branch doesn't get screwed up by using Unqual.
struct S
{
ref S opAssign(S)(const ref S rhs)
{
i = rhs.i;
return this;
}
int i;
}
foreach(T; TypeTuple!(S, const S, immutable S))
{
auto arr = [T(1), T(2), T(3), T(4)];
assert(array(arr) == arr);
}
}
private template blockAttribute(T)
{
static if (hasIndirections!(T) || is(T == void))
{
enum blockAttribute = 0;
}
else
{
enum blockAttribute = GC.BlkAttr.NO_SCAN;
}
}
unittest {
static assert(!(blockAttribute!void & GC.BlkAttr.NO_SCAN));
}
// Returns the number of dimensions in an array T.
private template nDimensions(T)
{
static if(isArray!T)
{
enum nDimensions = 1 + nDimensions!(typeof(T.init[0]));
}
else
{
enum nDimensions = 0;
}
}
unittest {
static assert(nDimensions!(uint[]) == 1);
static assert(nDimensions!(float[][]) == 2);
}
/**
Returns a new array of type $(D T) allocated on the garbage collected heap
without initializing its elements. This can be a useful optimization if every
element will be immediately initialized. $(D T) may be a multidimensional
array. In this case sizes may be specified for any number of dimensions from 1
to the number in $(D T).
Examples:
$(D_RUN_CODE
$(ARGS
---
double[] arr = uninitializedArray!(double[])(100);
assert(arr.length == 100);
double[][] matrix = uninitializedArray!(double[][])(42, 31);
assert(matrix.length == 42);
assert(matrix[0].length == 31);
---
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
auto uninitializedArray(T, I...)(I sizes)
if(allSatisfy!(isIntegral, I))
{
return arrayAllocImpl!(false, T, I)(sizes);
}
unittest
{
double[] arr = uninitializedArray!(double[])(100);
assert(arr.length == 100);
double[][] matrix = uninitializedArray!(double[][])(42, 31);
assert(matrix.length == 42);
assert(matrix[0].length == 31);
}
/**
Returns a new array of type $(D T) allocated on the garbage collected heap.
Initialization is guaranteed only for pointers, references and slices,
for preservation of memory safety.
*/
auto minimallyInitializedArray(T, I...)(I sizes) @trusted
if(allSatisfy!(isIntegral, I))
{
return arrayAllocImpl!(true, T, I)(sizes);
}
unittest
{
double[] arr = minimallyInitializedArray!(double[])(100);
assert(arr.length == 100);
double[][] matrix = minimallyInitializedArray!(double[][])(42);
assert(matrix.length == 42);
foreach(elem; matrix)
{
assert(elem.ptr is null);
}
}
private auto arrayAllocImpl(bool minimallyInitialized, T, I...)(I sizes)
if(allSatisfy!(isIntegral, I))
{
static assert(sizes.length >= 1,
"Cannot allocate an array without the size of at least the first " ~
" dimension.");
static assert(sizes.length <= nDimensions!T,
to!string(sizes.length) ~ " dimensions specified for a " ~
to!string(nDimensions!T) ~ " dimensional array.");
alias typeof(T.init[0]) E;
auto ptr = cast(E*) GC.malloc(sizes[0] * E.sizeof, blockAttribute!(E));
auto ret = ptr[0..sizes[0]];
static if(sizes.length > 1)
{
foreach(ref elem; ret)
{
elem = uninitializedArray!(E)(sizes[1..$]);
}
}
else static if(minimallyInitialized && hasIndirections!E)
{
ret[] = E.init;
}
return ret;
}
/**
Implements the range interface primitive $(D empty) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.empty) is
equivalent to $(D empty(array)).
Example:
$(D_RUN_CODE
$(ARGS
----
auto a = [ 1, 2, 3 ];
assert(!a.empty);
assert(a[3 .. $].empty);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
@property bool empty(T)(in T[] a) @safe pure nothrow
{
return !a.length;
}
unittest
{
auto a = [ 1, 2, 3 ];
assert(!a.empty);
assert(a[3 .. $].empty);
}
/**
Implements the range interface primitive $(D save) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.save) is
equivalent to $(D save(array)). The function does not duplicate the
content of the array, it simply returns its argument.
Example:
$(D_RUN_CODE
$(ARGS
----
auto a = [ 1, 2, 3 ];
auto b = a.save;
assert(b is a);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
@property T[] save(T)(T[] a) @safe pure nothrow
{
return a;
}
/**
Implements the range interface primitive $(D popFront) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.popFront) is
equivalent to $(D popFront(array)). For $(GLOSSARY narrow strings),
$(D popFront) automaticaly advances to the next $(GLOSSARY code
point).
Example:
$(D_RUN_CODE
$(ARGS
----
int[] a = [ 1, 2, 3 ];
a.popFront();
assert(a == [ 2, 3 ]);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
void popFront(A)(ref A a)
if (!isNarrowString!A && isDynamicArray!A && isMutable!A && !is(A == void[]))
{
assert(a.length, "Attempting to popFront() past the end of an array of "
~ typeof(a[0]).stringof);
a = a[1 .. $];
}
unittest
{
auto a = [ 1, 2, 3 ];
a.popFront();
assert(a == [ 2, 3 ]);
static assert(!__traits(compiles, popFront!(immutable int[])()));
static assert(!__traits(compiles, popFront!(void[])()));
}
// Specialization for narrow strings. The necessity of
// !isStaticArray!A suggests a compiler @@@BUG@@@.
void popFront(S)(ref S str) @trusted pure nothrow
if (isNarrowString!S && isMutable!S && !isStaticArray!S)
{
alias ElementEncodingType!S C;
assert(str.length, "Attempting to popFront() past the end of an array of " ~ C.stringof);
static if(is(Unqual!C == char))
{
immutable c = str[0];
if(c < 0x80)
{
if(__ctfe)
{
//The ptr trick doesn't work in CTFE.
str = str[1 .. $];
}
else
{
//ptr is used to avoid unnnecessary bounds checking.
str = str.ptr[1 .. str.length];
}
}
else
{
import core.bitop;
auto msbs = 7 - bsr(~c);
if((msbs < 2) | (msbs > 6))
{
//Invalid UTF-8
msbs = 1;
}
str = str[msbs .. $];
}
}
else static if(is(Unqual!C == wchar))
{
immutable u = str[0];
str = str[1 + (u >= 0xD800 && u <= 0xDBFF) .. $];
}
else static assert(0, "Bad template constraint.");
}
version(unittest) C[] _eatString(C)(C[] str)
{
while(!str.empty)
str.popFront();
return str;
}
unittest
{
string s1 = "\xC2\xA9hello";
s1.popFront();
assert(s1 == "hello");
wstring s2 = "\xC2\xA9hello";
s2.popFront();
assert(s2 == "hello");
string s3 = "\u20AC100";
foreach(S; TypeTuple!(string, wstring, dstring))
{
S str = "hello\U00010143\u0100\U00010143";
foreach(dchar c; ['h', 'e', 'l', 'l', 'o', '\U00010143', '\u0100', '\U00010143'])
{
assert(str.front == c);
str.popFront();
}
assert(str.empty);
}
static assert(!is(typeof(popFront!(immutable string))));
static assert(!is(typeof(popFront!(char[4]))));
enum checkCTFE = _eatString("ウェブサイト@La_Verité.com");
static assert(checkCTFE.empty);
enum checkCTFEW = _eatString("ウェブサイト@La_Verité.com"w);
static assert(checkCTFEW.empty);
}
/**
Implements the range interface primitive $(D popBack) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.popBack) is
equivalent to $(D popBack(array)). For $(GLOSSARY narrow strings), $(D
popFront) automaticaly eliminates the last $(GLOSSARY code point).
Example:
$(D_RUN_CODE
$(ARGS
----
int[] a = [ 1, 2, 3 ];
a.popBack();
assert(a == [ 1, 2 ]);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
void popBack(A)(ref A a)
if (isDynamicArray!A && !isNarrowString!A && isMutable!A && !is(A == void[]))
{
assert(a.length);
a = a[0 .. $ - 1];
}
unittest
{
auto a = [ 1, 2, 3 ];
a.popBack();
assert(a == [ 1, 2 ]);
static assert(!__traits(compiles, popBack!(immutable int[])));
static assert(!__traits(compiles, popBack!(void[])));
}
// Specialization for arrays of char
@trusted void popBack(A)(ref A a)
if(isNarrowString!A && isMutable!A)
{
assert(a.length, "Attempting to popBack() past the front of an array of " ~
typeof(a[0]).stringof);
a = a[0 .. $ - std.utf.strideBack(a, a.length)];
}
unittest
{
foreach(S; TypeTuple!(string, wstring, dstring))
{
S s = "hello\xE2\x89\xA0";
s.popBack();
assert(s == "hello");
S s3 = "\xE2\x89\xA0";
auto c = s3.back;
assert(c == cast(dchar)'\u2260');
s3.popBack();
assert(s3 == "");
S str = "\U00010143\u0100\U00010143hello";
foreach(dchar ch; ['o', 'l', 'l', 'e', 'h', '\U00010143', '\u0100', '\U00010143'])
{
assert(str.back == ch);
str.popBack();
}
assert(str.empty);
static assert(!__traits(compiles, popBack!(immutable S)));
}
}
/**
Implements the range interface primitive $(D front) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.front) is
equivalent to $(D front(array)). For $(GLOSSARY narrow strings), $(D
front) automaticaly returns the first $(GLOSSARY code point) as a $(D
dchar).
Example:
$(D_RUN_CODE
$(ARGS
----
int[] a = [ 1, 2, 3 ];
assert(a.front == 1);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
@property ref T front(T)(T[] a)
if (!isNarrowString!(T[]) && !is(T[] == void[]))
{
assert(a.length, "Attempting to fetch the front of an empty array of " ~
typeof(a[0]).stringof);
return a[0];
}
@property dchar front(A)(A a) if (isNarrowString!A)
{
assert(a.length, "Attempting to fetch the front of an empty array of " ~
typeof(a[0]).stringof);
size_t i = 0;
return decode(a, i);
}
unittest
{
auto a = [ 1, 2 ];
a.front = 4;
assert(a.front == 4);
assert(a == [ 4, 2 ]);
immutable b = [ 1, 2 ];
assert(b.front == 1);
}
/**
Implements the range interface primitive $(D back) for built-in
arrays. Due to the fact that nonmember functions can be called with
the first argument using the dot notation, $(D array.back) is
equivalent to $(D back(array)). For $(GLOSSARY narrow strings), $(D
back) automaticaly returns the last $(GLOSSARY code point) as a $(D
dchar).
Example:
$(D_RUN_CODE
$(ARGS
----
int[] a = [ 1, 2, 3 ];
assert(a.back == 3);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
@property ref T back(T)(T[] a) if (!isNarrowString!(T[]))
{
assert(a.length, "Attempting to fetch the back of an empty array of " ~
typeof(a[0]).stringof);
return a[$ - 1];
}
unittest
{
int[] a = [ 1, 2, 3 ];
assert(a.back == 3);
a.back += 4;
assert(a.back == 7);
immutable b = [ 1, 2, 3 ];
assert(b.back == 3);
}
// Specialization for strings
@property dchar back(A)(A a)
if(isDynamicArray!A && isNarrowString!A)
{
assert(a.length, "Attempting to fetch the back of an empty array of " ~
typeof(a[0]).stringof);
size_t i = a.length - std.utf.strideBack(a, a.length);
return decode(a, i);
}
// overlap
/*
Returns the overlapping portion, if any, of two arrays. Unlike $(D
equal), $(D overlap) only compares the pointers in the ranges, not the
values referred by them. If $(D r1) and $(D r2) have an overlapping
slice, returns that slice. Otherwise, returns the null slice.
Example:
$(D_RUN_CODE
$(ARGS
----
int[] a = [ 10, 11, 12, 13, 14 ];
int[] b = a[1 .. 3];
assert(overlap(a, b) == [ 11, 12 ]);
b = b.dup;
// overlap disappears even though the content is the same
assert(overlap(a, b).empty);
----
), $(ARGS), $(ARGS), $(ARGS import std.array;))
*/
inout(T)[] overlap(T)(inout(T)[] r1, inout(T)[] r2) @trusted pure nothrow
{
alias inout(T) U;
static U* max(U* a, U* b) nothrow { return a > b ? a : b; }
static U* min(U* a, U* b) nothrow { return a < b ? a : b; }
auto b = max(r1.ptr, r2.ptr);
auto e = min(r1.ptr + r1.length, r2.ptr + r2.length);
return b < e ? b[0 .. e - b] : null;
}
unittest
{
static void test(L, R)(L l, R r)
{
scope(failure) writeln("Types: L %s R %s", L.stringof, R.stringof);
assert(overlap(l, r) == [ 100, 12 ]);
assert(overlap(l, l[0 .. 2]) is l[0 .. 2]);
assert(overlap(l, l[3 .. 5]) is l[3 .. 5]);
assert(overlap(l[0 .. 2], l) is l[0 .. 2]);
assert(overlap(l[3 .. 5], l) is l[3 .. 5]);
}
int[] a = [ 10, 11, 12, 13, 14 ];
int[] b = a[1 .. 3];
a[1] = 100;
immutable int[] c = a.idup;
immutable int[] d = c[1 .. 3];
test(a, b);
assert(overlap(a, b.dup).empty);
test(c, d);
assert(overlap(c, d.idup).empty);
}
/+
Commented out until the insert which has been deprecated has been removed.
I'd love to just remove it in favor of insertInPlace, but then code would then
use this version of insert and silently break. So, it's here so that it can
be used once insert has not only been deprecated but removed, but until then,
it's commented out.
/++
Creates a new array which is a copy of $(D array) with $(D stuff) (which
must be an input range or a single item) inserted at position $(D pos).
Examples:
$(D_RUN_CODE
$(ARGS
--------------------
int[] a = [ 1, 2, 3, 4 ];
auto b = a.insert(2, [ 1, 2 ]);
assert(a == [ 1, 2, 3, 4 ]);
assert(b == [ 1, 2, 1, 2, 3, 4 ]);
--------------------
), $(ARGS), $(ARGS), $(ARGS import std.array;))
+/
T[] insert(T, Range)(T[] array, size_t pos, Range stuff)
if(isInputRange!Range &&
(is(ElementType!Range : T) ||
isSomeString!(T[]) && is(ElementType!Range : dchar)))
{
static if(hasLength!Range && is(ElementEncodingType!Range : T))
{
auto retval = new Unqual!(T)[](array.length + stuff.length);
retval[0 .. pos] = array[0 .. pos];
copy(stuff, retval[pos .. pos + stuff.length]);
retval[pos + stuff.length .. $] = array[pos .. $];
return cast(T[])retval;
}
else
{
auto app = appender!(T[])();
app.put(array[0 .. pos]);
app.put(stuff);
app.put(array[pos .. $]);
return app.data;
}
}
/++ Ditto +/
T[] insert(T)(T[] array, size_t pos, T stuff)
{
auto retval = new T[](array.length + 1);
retval[0 .. pos] = array[0 .. pos];
retval[pos] = stuff;
retval[pos + 1 .. $] = array[pos .. $];
return retval;
}
//Verify Example.
unittest
{
int[] a = [ 1, 2, 3, 4 ];
auto b = a.insert(2, [ 1, 2 ]);
assert(a == [ 1, 2, 3, 4 ]);
assert(b == [ 1, 2, 1, 2, 3, 4 ]);
}
unittest
{
auto a = [1, 2, 3, 4];
assert(a.insert(0, [6, 7]) == [6, 7, 1, 2, 3, 4]);
assert(a.insert(2, [6, 7]) == [1, 2, 6, 7, 3, 4]);
assert(a.insert(a.length, [6, 7]) == [1, 2, 3, 4, 6, 7]);
assert(a.insert(0, filter!"true"([6, 7])) == [6, 7, 1, 2, 3, 4]);
assert(a.insert(2, filter!"true"([6, 7])) == [1, 2, 6, 7, 3, 4]);
assert(a.insert(a.length, filter!"true"([6, 7])) == [1, 2, 3, 4, 6, 7]);
assert(a.insert(0, 22) == [22, 1, 2, 3, 4]);
assert(a.insert(2, 22) == [1, 2, 22, 3, 4]);
assert(a.insert(a.length, 22) == [1, 2, 3, 4, 22]);
assert(a == [1, 2, 3, 4]);
auto testStr(T, U)(string file = __FILE__, size_t line = __LINE__)
{
auto l = to!T("hello");
auto r = to!U(" world");
enforce(insert(l, 0, r) == " worldhello",
new AssertError("testStr failure 1", file, line));
enforce(insert(l, 3, r) == "hel worldlo",
new AssertError("testStr failure 2", file, line));
enforce(insert(l, l.length, r) == "hello world",
new AssertError("testStr failure 3", file, line));
enforce(insert(l, 0, filter!"true"(r)) == " worldhello",
new AssertError("testStr failure 4", file, line));
enforce(insert(l, 3, filter!"true"(r)) == "hel worldlo",
new AssertError("testStr failure 5", file, line));
enforce(insert(l, l.length, filter!"true"(r)) == "hello world",
new AssertError("testStr failure 6", file, line));
}
testStr!(string, string)();
testStr!(string, wstring)();
testStr!(string, dstring)();
testStr!(wstring, string)();
testStr!(wstring, wstring)();
testStr!(wstring, dstring)();
testStr!(dstring, string)();
testStr!(dstring, wstring)();
testStr!(dstring, dstring)();
}
+/
/++
Inserts $(D stuff) (which must be an input range or any number of
implicitly convertible items) in $(D array) at position $(D pos).
Example:
$(D_RUN_CODE
$(ARGS
---
int[] a = [ 1, 2, 3, 4 ];
a.insertInPlace(2, [ 1, 2 ]);
assert(a == [ 1, 2, 1, 2, 3, 4 ]);
a.insertInPlace(3, 10u, 11);
assert(a == [ 1, 2, 1, 10, 11, 2, 3, 4]);
---
), $(ARGS), $(ARGS), $(ARGS import std.array;))
+/
void insertInPlace(T, Range)(ref T[] array, size_t pos, Range stuff)
if(isInputRange!Range &&
(is(ElementType!Range : T) ||
isSomeString!(T[]) && is(ElementType!Range : dchar)))
{
insertInPlaceImpl(array, pos, stuff);
}
/++ Ditto +/
void insertInPlace(T, U...)(ref T[] array, size_t pos, U stuff)
if(isSomeString!(T[]) && allSatisfy!(isCharOrString, U))
{
dchar[staticConvertible!(dchar, U)] stackSpace = void;
auto range = chain(makeRangeTuple(stackSpace[], stuff).expand);
insertInPlaceImpl(array, pos, range);
}
/++ Ditto +/
void insertInPlace(T, U...)(ref T[] array, size_t pos, U stuff)
if(!isSomeString!(T[]) && allSatisfy!(isInputRangeOrConvertible!T, U))
{
T[staticConvertible!(T, U)] stackSpace = void;
auto range = chain(makeRangeTuple(stackSpace[], stuff).expand);
insertInPlaceImpl(array, pos, range);
}
// returns number of consecutive elements at front of U that are convertible to E
private template staticFrontConvertible(E, U...)
{
static if(U.length == 0)
enum staticFrontConvertible = 0;
else static if(isImplicitlyConvertible!(U[0],E))
enum staticFrontConvertible = 1 + staticFrontConvertible!(E, U[1..$]);
else
enum staticFrontConvertible = 0;
}
// returns total number of elements in U that are convertible to E
private template staticConvertible(E, U...)
{
static if (U.length == 0)
enum staticConvertible = 0;
else static if(isImplicitlyConvertible!(U[0], E))
enum staticConvertible = 1 + staticConvertible!(E, U[1..$]);
else
enum staticConvertible = staticConvertible!(E, U[1..$]);
}
private template isCharOrString(T)
{
enum isCharOrString = isSomeString!T || isSomeChar!T;
}
private template isInputRangeOrConvertible(E)
{
template isInputRangeOrConvertible(R)
{
enum isInputRangeOrConvertible =
(isInputRange!R && is(ElementType!R : E)) || is(R : E);
}
}
//packs individual convertible elements into provided slack array,
//and chains them with the rest into a tuple
private auto makeRangeTuple(E, U...)(E[] place, U stuff)
if(U.length > 0 && is(U[0] : E) )
{
enum toPack = staticFrontConvertible!(E, U);
foreach(i, v; stuff[0..toPack])
emplace!E(&place[i], v);
assert(place.length >= toPack);
static if(U.length != staticFrontConvertible!(E,U))
return tuple(place[0..toPack],
makeRangeTuple(place[toPack..$], stuff[toPack..$]).expand);
else
return tuple(place[0..toPack]);
}
//ditto
private auto makeRangeTuple(E, U...)(E[] place, U stuff)
if(U.length > 0 && isInputRange!(U[0]) && is(ElementType!(U[0]) : E))
{
static if(U.length == 1)
return tuple(stuff[0]);
else
return tuple(stuff[0],makeRangeTuple(place, stuff[1..$]).expand);
}
private void insertInPlaceImpl(T, Range)(ref T[] array, size_t pos, Range stuff)
if(isInputRange!Range &&
(is(ElementType!Range : T) ||
isSomeString!(T[]) && is(ElementType!Range : dchar)))
{
auto app = appender!(T[])();
app.put(array[0 .. pos]);
app.put(stuff);
app.put(array[pos .. $]);
array = app.data;
}
//Verify Example.
unittest
{
int[] a = [ 1, 2, 3, 4 ];
a.insertInPlace(2, [ 1, 2 ]);
assert(a == [ 1, 2, 1, 2, 3, 4 ]);
a.insertInPlace(3, 10u, 11);
assert(a == [ 1, 2, 1, 10, 11, 2, 3, 4]);
}
unittest
{
bool test(T, U, V)(T orig, size_t pos, U toInsert, V result,
string file = __FILE__, size_t line = __LINE__)
{
{
static if(is(T == typeof(T.dup)))
auto a = orig.dup;
else
auto a = orig.idup;
a.insertInPlace(pos, toInsert);
if(!std.algorithm.equal(a, result))
return false;
}
static if(isInputRange!U)
{
orig.insertInPlace(pos, filter!"true"(toInsert));
return std.algorithm.equal(orig, result);
}
else
return true;
}
assert(test([1, 2, 3, 4], 0, [6, 7], [6, 7, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 2, [8, 9], [1, 2, 8, 9, 3, 4]));
assert(test([1, 2, 3, 4], 4, [10, 11], [1, 2, 3, 4, 10, 11]));
assert(test([1, 2, 3, 4], 0, 22, [22, 1, 2, 3, 4]));
assert(test([1, 2, 3, 4], 2, 23, [1, 2, 23, 3, 4]));
assert(test([1, 2, 3, 4], 4, 24, [1, 2, 3, 4, 24]));
auto testStr(T, U)(string file = __FILE__, size_t line = __LINE__)
{
auto l = to!T("hello");
auto r = to!U(" world");
enforce(test(l, 0, r, " worldhello"),
new AssertError("testStr failure 1", file, line));
enforce(test(l, 3, r, "hel worldlo"),
new AssertError("testStr failure 2", file, line));
enforce(test(l, l.length, r, "hello world"),
new AssertError("testStr failure 3", file, line));
}
testStr!(string, string)();
testStr!(string, wstring)();
testStr!(string, dstring)();
testStr!(wstring, string)();
testStr!(wstring, wstring)();
testStr!(wstring, dstring)();
testStr!(dstring, string)();
testStr!(dstring, wstring)();
testStr!(dstring, dstring)();
// variadic version
bool testVar(T, U...)(T orig, size_t pos, U args)
{
static if(is(T == typeof(T.dup)))
auto a = orig.dup;
else
auto a = orig.idup;
auto result = args[$-1];
a.insertInPlace(pos, args[0..$-1]);
if(!std.algorithm.equal(a, result))
return false;
return true;
}
assert(testVar([1, 2, 3, 4], 0, 6, 7u, [6, 7, 1, 2, 3, 4]));
assert(testVar([1L, 2, 3, 4], 2, 8, 9L, [1, 2, 8, 9, 3, 4]));
assert(testVar([1L, 2, 3, 4], 4, 10L, 11, [1, 2, 3, 4, 10, 11]));
assert(testVar([1L, 2, 3, 4], 4, [10, 11], 40L, 42L,
[1, 2, 3, 4, 10, 11, 40, 42]));
assert(testVar([1L, 2, 3, 4], 4, 10, 11, [40L, 42],
[1, 2, 3, 4, 10, 11, 40, 42]));
assert(testVar("t".idup, 1, 'e', 's', 't', "test"));