forked from dlang/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.d
3990 lines (3485 loc) · 112 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 and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE ,
$(TR $(TH Function Name) $(TH Description)
)
$(TR $(TD $(LREF array))
$(TD Returns a copy of the input in a newly allocated dynamic array.
))
$(TR $(TD $(LREF appender))
$(TD Returns a new $(LREF Appender) or $(LREF RefAppender) initialized with a given array.
))
$(TR $(TD $(LREF assocArray))
$(TD Returns a newly allocated associative array from a range of key/value tuples.
))
$(TR $(TD $(LREF byPair))
$(TD Construct a range iterating over an associative array by key/value tuples.
))
$(TR $(TD $(LREF insertInPlace))
$(TD Inserts into an existing array at a given position.
))
$(TR $(TD $(LREF join))
$(TD Concatenates a range of ranges into one array.
))
$(TR $(TD $(LREF minimallyInitializedArray))
$(TD Returns a new array of type `T`.
))
$(TR $(TD $(LREF replace))
$(TD Returns a new array with all occurrences of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceFirst))
$(TD Returns a new array with the first occurrence of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceInPlace))
$(TD Replaces all occurrences of a certain subrange and puts the result into a given array.
))
$(TR $(TD $(LREF replaceInto))
$(TD Replaces all occurrences of a certain subrange and puts the result into an output range.
))
$(TR $(TD $(LREF replaceLast))
$(TD Returns a new array with the last occurrence of a certain subrange replaced.
))
$(TR $(TD $(LREF replaceSlice))
$(TD Returns a new array with a given slice replaced.
))
$(TR $(TD $(LREF replicate))
$(TD Creates a new array out of several copies of an input array or range.
))
$(TR $(TD $(LREF sameHead))
$(TD Checks if the initial segments of two arrays refer to the same
place in memory.
))
$(TR $(TD $(LREF sameTail))
$(TD Checks if the final segments of two arrays refer to the same place
in memory.
))
$(TR $(TD $(LREF split))
$(TD Eagerly split a range or string into an array.
))
$(TR $(TD $(LREF uninitializedArray))
$(TD Returns a new array of type `T` without initializing its elements.
))
)
Copyright: Copyright Andrei Alexandrescu 2008- and Jonathan M Davis 2011-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.org, Andrei Alexandrescu) and
$(HTTP jmdavisprog.com, Jonathan M Davis)
Source: $(PHOBOSSRC std/array.d)
*/
module std.array;
import std.functional;
import std.meta;
import std.traits;
import std.range.primitives;
public import std.range.primitives : save, empty, popFront, popBack, front, back;
/**
* Allocates an array and initializes it with copies of the elements
* of range `r`.
*
* Narrow strings are handled as a special case in an overload.
*
* Params:
* r = range (or aggregate with `opApply` function) whose elements are copied into the allocated array
* Returns:
* allocated and initialized array
*/
ForeachType!Range[] array(Range)(Range r)
if (isIterable!Range && !isNarrowString!Range && !isInfinite!Range)
{
if (__ctfe)
{
// Compile-time version to avoid memcpy calls.
// Also used to infer attributes of array().
typeof(return) result;
foreach (e; r)
result ~= e;
return result;
}
alias E = ForeachType!Range;
static if (hasLength!Range)
{
auto length = r.length;
if (length == 0)
return null;
import std.conv : emplaceRef;
auto result = (() @trusted => uninitializedArray!(Unqual!E[])(length))();
// Every element of the uninitialized array must be initialized
size_t i;
foreach (e; r)
{
emplaceRef!E(result[i], e);
++i;
}
return (() @trusted => cast(E[]) result)();
}
else
{
auto a = appender!(E[])();
foreach (e; r)
{
a.put(e);
}
return a.data;
}
}
/// ditto
ForeachType!(PointerTarget!Range)[] array(Range)(Range r)
if (isPointer!Range && isIterable!(PointerTarget!Range) && !isNarrowString!Range && !isInfinite!Range)
{
return array(*r);
}
///
@safe pure nothrow unittest
{
auto a = array([1, 2, 3, 4, 5][]);
assert(a == [ 1, 2, 3, 4, 5 ]);
}
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
struct Foo
{
int a;
}
auto a = array([Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)][]);
assert(equal(a, [Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)]));
}
@safe pure nothrow unittest
{
struct MyRange
{
enum front = 123;
enum empty = true;
void popFront() {}
}
auto arr = (new MyRange).array;
assert(arr.empty);
}
@system pure nothrow unittest
{
immutable int[] a = [1, 2, 3, 4];
auto b = (&a).array;
assert(b == a);
}
@safe unittest
{
import std.algorithm.comparison : equal;
struct Foo
{
int a;
void opAssign(Foo)
{
assert(0);
}
auto opEquals(Foo foo)
{
return a == foo.a;
}
}
auto a = array([Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)][]);
assert(equal(a, [Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)]));
}
@safe unittest
{
// Issue 12315
static struct Bug12315 { immutable int i; }
enum bug12315 = [Bug12315(123456789)].array();
static assert(bug12315[0].i == 123456789);
}
@safe unittest
{
import std.range;
static struct S{int* p;}
auto a = array(immutable(S).init.repeat(5));
assert(a.length == 5);
}
/**
Convert a narrow string to an array type that fully supports random access.
This is handled as a special case and always returns an array of `dchar`
Params:
str = `isNarrowString` to be converted to an array of `dchar`
Returns:
a `dchar[]`, `const(dchar)[]`, or `immutable(dchar)[]` depending on the constness of
the input.
*/
ElementType!String[] array(String)(scope String str)
if (isNarrowString!String)
{
import std.utf : toUTF32;
auto temp = str.toUTF32;
/* Unsafe cast. Allowed because toUTF32 makes a new array
and copies all the elements.
*/
return () @trusted { return cast(ElementType!String[]) temp; } ();
}
///
@safe unittest
{
import std.range.primitives : isRandomAccessRange;
assert("Hello D".array == "Hello D"d);
static assert(isRandomAccessRange!string == false);
assert("Hello D"w.array == "Hello D"d);
static assert(isRandomAccessRange!dstring == true);
}
@safe unittest
{
import std.conv : to;
static struct TestArray { int x; string toString() @safe { 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(scope int delegate(ref int) @safe dg)
{
int res;
foreach (i; 0 .. 10)
{
res = dg(i);
if (res) break;
}
return res;
}
}
auto a = array([1, 2, 3, 4, 5][]);
assert(a == [ 1, 2, 3, 4, 5 ]);
auto b = array([TestArray(1), TestArray(2)][]);
assert(b == [TestArray(1), TestArray(2)]);
class C
{
int x;
this(int y) { x = y; }
override string toString() const @safe { return to!string(x); }
}
auto c = array([new C(1), new C(2)][]);
assert(c[0].x == 1);
assert(c[1].x == 2);
auto d = array([1.0, 2.2, 3][]);
assert(is(typeof(d) == double[]));
assert(d == [1.0, 2.2, 3]);
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
@safe 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.
//EDIT: array no longer calls opAssign.
struct S
{
ref S opAssign(S)(const ref S rhs)
{
assert(0);
}
int i;
}
static foreach (T; AliasSeq!(S, const S, immutable S))
{{
auto arr = [T(1), T(2), T(3), T(4)];
assert(array(arr) == arr);
}}
}
@safe unittest
{
//9824
static struct S
{
@disable void opAssign(S);
int i;
}
auto arr = [S(0), S(1), S(2)];
arr.array();
}
// Bugzilla 10220
@safe unittest
{
import std.algorithm.comparison : equal;
import std.exception;
import std.range : repeat;
static struct S
{
int val;
@disable this();
this(int v) { val = v; }
}
assertCTFEable!(
{
auto r = S(1).repeat(2).array();
assert(equal(r, [S(1), S(1)]));
});
}
@safe unittest
{
//Turn down infinity:
static assert(!is(typeof(
repeat(1).array()
)));
}
/**
Returns a newly allocated associative array from a range of key/value tuples.
Params:
r = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
of tuples of keys and values.
Returns: A newly allocated associative array out of elements of the input
range, which must be a range of tuples (Key, Value). Returns a null associative
array reference when given an empty range.
Duplicates: Associative arrays have unique keys. If r contains duplicate keys,
then the result will contain the value of the last pair for that key in r.
See_Also: $(REF Tuple, std,typecons), $(REF zip, std,range)
*/
auto assocArray(Range)(Range r)
if (isInputRange!Range)
{
import std.typecons : isTuple;
alias E = ElementType!Range;
static assert(isTuple!E, "assocArray: argument must be a range of tuples");
static assert(E.length == 2, "assocArray: tuple dimension must be 2");
alias KeyType = E.Types[0];
alias ValueType = E.Types[1];
static assert(isMutable!ValueType, "assocArray: value type must be mutable");
ValueType[KeyType] aa;
foreach (t; r)
aa[t[0]] = t[1];
return aa;
}
///
@safe pure /*nothrow*/ unittest
{
import std.range;
import std.typecons;
auto a = assocArray(zip([0, 1, 2], ["a", "b", "c"])); // aka zipMap
assert(is(typeof(a) == string[int]));
assert(a == [0:"a", 1:"b", 2:"c"]);
auto b = assocArray([ tuple("foo", "bar"), tuple("baz", "quux") ]);
assert(is(typeof(b) == string[string]));
assert(b == ["foo":"bar", "baz":"quux"]);
}
// @@@11053@@@ - Cannot be version(unittest) - recursive instantiation error
@safe unittest
{
import std.typecons;
static assert(!__traits(compiles, [ tuple("foo", "bar", "baz") ].assocArray()));
static assert(!__traits(compiles, [ tuple("foo") ].assocArray()));
assert([ tuple("foo", "bar") ].assocArray() == ["foo": "bar"]);
}
// Issue 13909
@safe unittest
{
import std.typecons;
auto a = [tuple!(const string, string)("foo", "bar")];
auto b = [tuple!(string, const string)("foo", "bar")];
assert(a == b);
assert(assocArray(a) == [cast(const(string)) "foo": "bar"]);
static assert(!__traits(compiles, assocArray(b)));
}
/**
Construct a range iterating over an associative array by key/value tuples.
Params:
aa = The associative array to iterate over.
Returns: A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
of Tuple's of key and value pairs from the given associative array. The members
of each pair can be accessed by name (`.key` and `.value`). or by integer
index (0 and 1 respectively).
*/
auto byPair(AA)(AA aa)
if (isAssociativeArray!AA)
{
import std.algorithm.iteration : map;
import std.typecons : tuple;
return aa.byKeyValue
.map!(pair => tuple!("key", "value")(pair.key, pair.value));
}
///
@safe unittest
{
import std.algorithm.sorting : sort;
import std.typecons : tuple, Tuple;
auto aa = ["a": 1, "b": 2, "c": 3];
Tuple!(string, int)[] pairs;
// Iteration over key/value pairs.
foreach (pair; aa.byPair)
{
if (pair.key == "b")
pairs ~= tuple("B", pair.value);
else
pairs ~= pair;
}
// Iteration order is implementation-dependent, so we should sort it to get
// a fixed order.
pairs.sort();
assert(pairs == [
tuple("B", 2),
tuple("a", 1),
tuple("c", 3)
]);
}
@safe unittest
{
import std.typecons : tuple, Tuple;
import std.meta : AliasSeq;
auto aa = ["a":2];
auto pairs = aa.byPair();
alias PT = typeof(pairs.front);
static assert(is(PT : Tuple!(string,int)));
static assert(PT.fieldNames == AliasSeq!("key", "value"));
static assert(isForwardRange!(typeof(pairs)));
assert(!pairs.empty);
assert(pairs.front == tuple("a", 2));
auto savedPairs = pairs.save;
pairs.popFront();
assert(pairs.empty);
assert(!savedPairs.empty);
assert(savedPairs.front == tuple("a", 2));
}
// Issue 17711
@safe unittest
{
const(int[string]) aa = [ "abc": 123 ];
// Ensure that byKeyValue is usable with a const AA.
auto kv = aa.byKeyValue;
assert(!kv.empty);
assert(kv.front.key == "abc" && kv.front.value == 123);
kv.popFront();
assert(kv.empty);
// Ensure byPair is instantiable with const AA.
auto r = aa.byPair;
static assert(isInputRange!(typeof(r)));
assert(!r.empty && r.front[0] == "abc" && r.front[1] == 123);
r.popFront();
assert(r.empty);
}
private template blockAttribute(T)
{
import core.memory;
static if (hasIndirections!(T) || is(T == void))
{
enum blockAttribute = 0;
}
else
{
enum blockAttribute = GC.BlkAttr.NO_SCAN;
}
}
@safe unittest
{
import core.memory : UGC = GC;
static assert(!(blockAttribute!void & UGC.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;
}
}
@safe unittest
{
static assert(nDimensions!(uint[]) == 1);
static assert(nDimensions!(float[][]) == 2);
}
/++
Returns a new array of type `T` allocated on the garbage collected heap
without initializing its elements. This can be a useful optimization if every
element will be immediately initialized. `T` may be a multidimensional
array. In this case sizes may be specified for any number of dimensions from 0
to the number in `T`.
uninitializedArray is `nothrow` and weakly `pure`.
uninitializedArray is `@system` if the uninitialized element type has pointers.
Params:
T = The type of the resulting array elements
sizes = The length dimension(s) of the resulting array
Returns:
An array of `T` with `I.length` dimensions.
+/
auto uninitializedArray(T, I...)(I sizes) nothrow @system
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && hasIndirections!(ElementEncodingType!T))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(false, T, ST)(sizes);
}
/// ditto
auto uninitializedArray(T, I...)(I sizes) nothrow @trusted
if (isDynamicArray!T && allSatisfy!(isIntegral, I) && !hasIndirections!(ElementEncodingType!T))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(false, T, ST)(sizes);
}
///
@system nothrow pure 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);
char*[] ptrs = uninitializedArray!(char*[])(100);
assert(ptrs.length == 100);
}
/++
Returns a new array of type `T` allocated on the garbage collected heap.
Partial initialization is done for types with indirections, for preservation
of memory safety. Note that elements will only be initialized to 0, but not
necessarily the element type's `.init`.
minimallyInitializedArray is `nothrow` and weakly `pure`.
Params:
T = The type of the array elements
sizes = The length dimension(s) of the resulting array
Returns:
An array of `T` with `I.length` dimensions.
+/
auto minimallyInitializedArray(T, I...)(I sizes) nothrow @trusted
if (isDynamicArray!T && allSatisfy!(isIntegral, I))
{
enum isSize_t(E) = is (E : size_t);
alias toSize_t(E) = size_t;
static assert(allSatisfy!(isSize_t, I),
"Argument types in "~I.stringof~" are not all convertible to size_t: "
~Filter!(templateNot!(isSize_t), I).stringof);
//Eagerlly transform non-size_t into size_t to avoid template bloat
alias ST = staticMap!(toSize_t, I);
return arrayAllocImpl!(true, T, ST)(sizes);
}
///
@safe pure nothrow unittest
{
import std.algorithm.comparison : equal;
import std.range : repeat;
auto arr = minimallyInitializedArray!(int[])(42);
assert(arr.length == 42);
// Elements aren't necessarily initialized to 0
assert(!arr.equal(0.repeat(42)));
}
@safe pure nothrow unittest
{
cast(void) minimallyInitializedArray!(int[][][][][])();
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) nothrow
{
static assert(I.length <= nDimensions!T,
I.length.stringof~"dimensions specified for a "~nDimensions!T.stringof~" dimensional array.");
alias E = ElementEncodingType!T;
E[] ret;
static if (I.length != 0)
{
static assert(is(I[0] == size_t));
alias size = sizes[0];
}
static if (I.length == 1)
{
if (__ctfe)
{
static if (__traits(compiles, new E[](size)))
ret = new E[](size);
else static if (__traits(compiles, ret ~= E.init))
{
try
{
//Issue: if E has an impure postblit, then all of arrayAllocImpl
//Will be impure, even during non CTFE.
foreach (i; 0 .. size)
ret ~= E.init;
}
catch (Exception e)
throw new Error(e.msg);
}
else
assert(0, "No postblit nor default init on " ~ E.stringof ~
": At least one is required for CTFE.");
}
else
{
import core.memory : GC;
import core.stdc.string : memset;
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(size, E.sizeof, overflow);
if (overflow) assert(0);
auto ptr = cast(E*) GC.malloc(nbytes, blockAttribute!E);
static if (minimallyInitialized && hasIndirections!E)
memset(ptr, 0, nbytes);
ret = ptr[0 .. size];
}
}
else static if (I.length > 1)
{
ret = arrayAllocImpl!(false, E[])(size);
foreach (ref elem; ret)
elem = arrayAllocImpl!(minimallyInitialized, E)(sizes[1..$]);
}
return ret;
}
@safe nothrow pure unittest
{
auto s1 = uninitializedArray!(int[])();
auto s2 = minimallyInitializedArray!(int[])();
assert(s1.length == 0);
assert(s2.length == 0);
}
@safe nothrow pure unittest //@@@9803@@@
{
auto a = minimallyInitializedArray!(int*[])(1);
assert(a[0] == null);
auto b = minimallyInitializedArray!(int[][])(1);
assert(b[0].empty);
auto c = minimallyInitializedArray!(int*[][])(1, 1);
assert(c[0][0] == null);
}
@safe unittest //@@@10637@@@
{
static struct S
{
static struct I{int i; alias i this;}
int* p;
this() @disable;
this(int i)
{
p = &(new I(i)).i;
}
this(this)
{
p = &(new I(*p)).i;
}
~this()
{
assert(p != null);
}
}
auto a = minimallyInitializedArray!(S[])(1);
assert(a[0].p == null);
enum b = minimallyInitializedArray!(S[])(1);
assert(b[0].p == null);
}
@safe nothrow unittest
{
static struct S1
{
this() @disable;
this(this) @disable;
}
auto a1 = minimallyInitializedArray!(S1[][])(2, 2);
assert(a1);
static struct S2
{
this() @disable;
//this(this) @disable;
}
auto a2 = minimallyInitializedArray!(S2[][])(2, 2);
assert(a2);
enum b2 = minimallyInitializedArray!(S2[][])(2, 2);
assert(b2);
static struct S3
{
//this() @disable;
this(this) @disable;
}
auto a3 = minimallyInitializedArray!(S3[][])(2, 2);
assert(a3);
enum b3 = minimallyInitializedArray!(S3[][])(2, 2);
assert(b3);
}
/++
Returns the overlapping portion, if any, of two arrays. Unlike `equal`,
`overlap` only compares the pointers and lengths in the
ranges, not the values referred by them. If `r1` and `r2` have an
overlapping slice, returns that slice. Otherwise, returns the null
slice.
Params:
a = The first array to compare
b = The second array to compare
Returns:
The overlapping portion of the two arrays.
+/
CommonType!(T[], U[]) overlap(T, U)(T[] a, U[] b) @trusted
if (is(typeof(a.ptr < b.ptr) == bool))
{
import std.algorithm.comparison : min;
auto end = min(a.ptr + a.length, b.ptr + b.length);
// CTFE requires pairing pointer comparisons, which forces a
// slightly inefficient implementation.
if (a.ptr <= b.ptr && b.ptr < a.ptr + a.length)
{
return b.ptr[0 .. end - b.ptr];
}
if (b.ptr <= a.ptr && a.ptr < b.ptr + b.length)
{
return a.ptr[0 .. end - a.ptr];
}
return null;
}
///
@safe pure nothrow unittest
{
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);
static test()() @nogc
{
auto a = "It's three o'clock"d;
auto b = a[5 .. 10];
return b.overlap(a);
}
//works at compile-time
static assert(test == "three"d);
}
@safe nothrow unittest
{
static void test(L, R)(L l, R r)
{
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);
}
@safe pure nothrow unittest // bugzilla 9836
{
// range primitives for array should work with alias this types
struct Wrapper
{
int[] data;
alias data this;
@property Wrapper save() { return this; }
}
auto w = Wrapper([1,2,3,4]);
std.array.popFront(w); // should work
static assert(isInputRange!Wrapper);
static assert(isForwardRange!Wrapper);
static assert(isBidirectionalRange!Wrapper);
static assert(isRandomAccessRange!Wrapper);
}
private void copyBackwards(T)(T[] src, T[] dest)
{
import core.stdc.string : memmove;
assert(src.length == dest.length);
if (!__ctfe || hasElaborateCopyConstructor!T)
{
/* insertInPlace relies on dest being uninitialized, so no postblits allowed,
* as this is a MOVE that overwrites the destination, not a COPY.
* BUG: insertInPlace will not work with ctfe and postblits
*/
memmove(dest.ptr, src.ptr, src.length * T.sizeof);
}
else
{
immutable len = src.length;
for (size_t i = len; i-- > 0;)
{
dest[i] = src[i];
}
}
}
/++
Inserts `stuff` (which must be an input range or any number of
implicitly convertible items) in `array` at position `pos`.
Params:
array = The array that `stuff` will be inserted into.
pos = The position in `array` to insert the `stuff`.
stuff = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives),
or any number of implicitly convertible items to insert into `array`.
+/
void insertInPlace(T, U...)(ref T[] array, size_t pos, U stuff)
if (!isSomeString!(T[])
&& allSatisfy!(isInputRangeOrConvertible!T, U) && U.length > 0)
{
static if (allSatisfy!(isInputRangeWithLengthOrConvertible!T, U))
{
import std.conv : emplaceRef;
immutable oldLen = array.length;
size_t to_insert = 0;
foreach (i, E; U)
{
static if (is(E : T)) //a single convertible value, not a range
to_insert += 1;
else
to_insert += stuff[i].length;
}
if (to_insert)
{
array.length += to_insert;
// Takes arguments array, pos, stuff
// Spread apart array[] at pos by moving elements
(() @trusted { copyBackwards(array[pos .. oldLen], array[pos+to_insert..$]); })();
// Initialize array[pos .. pos+to_insert] with stuff[]
auto j = 0;
foreach (i, E; U)
{
static if (is(E : T))