-
-
Notifications
You must be signed in to change notification settings - Fork 693
/
array.d
2641 lines (2377 loc) · 67.8 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
/**
* This module provides an `Array` type with deterministic memory usage not
* reliant on the GC, as an alternative to the built-in arrays.
*
* This module is a submodule of $(MREF std, container).
*
* Source: $(PHOBOSSRC std/container/array.d)
*
* Copyright: 2010- Andrei Alexandrescu. All rights reserved by the respective holders.
*
* License: Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at $(HTTP
* boost.org/LICENSE_1_0.txt)).
*
* Authors: $(HTTP erdani.com, Andrei Alexandrescu)
*
* $(SCRIPT inhibitQuickIndex = 1;)
*/
module std.container.array;
import core.exception : RangeError;
import std.range.primitives;
import std.traits;
public import std.container.util;
///
pure @system unittest
{
auto arr = Array!int(0, 2, 3);
assert(arr[0] == 0);
assert(arr.front == 0);
assert(arr.back == 3);
// reserve space
arr.reserve(1000);
assert(arr.length == 3);
assert(arr.capacity >= 1000);
// insertion
arr.insertBefore(arr[1..$], 1);
assert(arr.front == 0);
assert(arr.length == 4);
arr.insertBack(4);
assert(arr.back == 4);
assert(arr.length == 5);
// set elements
arr[1] *= 42;
assert(arr[1] == 42);
}
///
pure @system unittest
{
import std.algorithm.comparison : equal;
auto arr = Array!int(1, 2, 3);
// concat
auto b = Array!int(11, 12, 13);
arr ~= b;
assert(arr.length == 6);
// slicing
assert(arr[1 .. 3].equal([2, 3]));
// remove
arr.linearRemove(arr[1 .. 3]);
assert(arr[0 .. 2].equal([1, 11]));
}
/// `Array!bool` packs together values efficiently by allocating one bit per element
pure @system unittest
{
auto arr = Array!bool([true, true, false, true, false]);
assert(arr.length == 5);
}
private struct RangeT(A)
{
/* Workaround for https://issues.dlang.org/show_bug.cgi?id=13629
See also: http://forum.dlang.org/post/vbmwhzvawhnkoxrhbnyb@forum.dlang.org
*/
private A[1] _outer_;
private @property ref inout(A) _outer() inout { return _outer_[0]; }
private size_t _a, _b;
/* E is different from T when A is more restrictively qualified than T:
immutable(Array!int) => T == int, E = immutable(int) */
alias E = typeof(_outer_[0]._data._payload[0]);
private this(ref A data, size_t a, size_t b)
{
_outer_ = data;
_a = a;
_b = b;
}
@property RangeT save()
{
return this;
}
@property bool empty() @safe pure nothrow const
{
return _a >= _b;
}
@property size_t length() @safe pure nothrow const
{
return _b - _a;
}
alias opDollar = length;
@property ref inout(E) front() inout
{
assert(!empty, "Attempting to access the front of an empty Array");
return _outer[_a];
}
@property ref inout(E) back() inout
{
assert(!empty, "Attempting to access the back of an empty Array");
return _outer[_b - 1];
}
void popFront() @safe @nogc pure nothrow
{
assert(!empty, "Attempting to popFront an empty Array");
++_a;
}
void popBack() @safe @nogc pure nothrow
{
assert(!empty, "Attempting to popBack an empty Array");
--_b;
}
static if (isMutable!A)
{
import std.algorithm.mutation : move;
E moveFront()
{
assert(!empty, "Attempting to moveFront an empty Array");
assert(_a < _outer.length,
"Attempting to moveFront using an out of bounds low index on an Array");
return move(_outer._data._payload[_a]);
}
E moveBack()
{
assert(!empty, "Attempting to moveBack an empty Array");
assert(_b - 1 < _outer.length,
"Attempting to moveBack using an out of bounds high index on an Array");
return move(_outer._data._payload[_b - 1]);
}
E moveAt(size_t i)
{
assert(_a + i < _b,
"Attempting to moveAt using an out of bounds index on an Array");
assert(_a + i < _outer.length,
"Cannot move past the end of the array");
return move(_outer._data._payload[_a + i]);
}
}
ref inout(E) opIndex(size_t i) inout
{
assert(_a + i < _b,
"Attempting to fetch using an out of bounds index on an Array");
return _outer[_a + i];
}
RangeT opSlice()
{
return typeof(return)(_outer, _a, _b);
}
RangeT opSlice(size_t i, size_t j)
{
assert(i <= j && _a + j <= _b,
"Attempting to slice using an out of bounds indices on an Array");
return typeof(return)(_outer, _a + i, _a + j);
}
RangeT!(const(A)) opSlice() const
{
return typeof(return)(_outer, _a, _b);
}
RangeT!(const(A)) opSlice(size_t i, size_t j) const
{
assert(i <= j && _a + j <= _b,
"Attempting to slice using an out of bounds indices on an Array");
return typeof(return)(_outer, _a + i, _a + j);
}
static if (isMutable!A)
{
void opSliceAssign(E value)
{
assert(_b <= _outer.length,
"Attempting to assign using an out of bounds indices on an Array");
_outer[_a .. _b] = value;
}
void opSliceAssign(E value, size_t i, size_t j)
{
assert(_a + j <= _b,
"Attempting to slice assign using an out of bounds indices on an Array");
_outer[_a + i .. _a + j] = value;
}
void opSliceUnary(string op)()
if (op == "++" || op == "--")
{
assert(_b <= _outer.length,
"Attempting to slice using an out of bounds indices on an Array");
mixin(op~"_outer[_a .. _b];");
}
void opSliceUnary(string op)(size_t i, size_t j)
if (op == "++" || op == "--")
{
assert(_a + j <= _b,
"Attempting to slice using an out of bounds indices on an Array");
mixin(op~"_outer[_a + i .. _a + j];");
}
void opSliceOpAssign(string op)(E value)
{
assert(_b <= _outer.length,
"Attempting to slice using an out of bounds indices on an Array");
mixin("_outer[_a .. _b] "~op~"= value;");
}
void opSliceOpAssign(string op)(E value, size_t i, size_t j)
{
assert(_a + j <= _b,
"Attempting to slice using an out of bounds indices on an Array");
mixin("_outer[_a + i .. _a + j] "~op~"= value;");
}
}
}
/**
* _Array type with deterministic control of memory. The memory allocated
* for the array is reclaimed as soon as possible; there is no reliance
* on the garbage collector. `Array` uses `malloc`, `realloc` and `free`
* for managing its own memory.
*
* This means that pointers to elements of an `Array` will become
* dangling as soon as the element is removed from the `Array`. On the other hand
* the memory allocated by an `Array` will be scanned by the GC and
* GC managed objects referenced from an `Array` will be kept alive.
*
* Note:
*
* When using `Array` with range-based functions like those in `std.algorithm`,
* `Array` must be sliced to get a range (for example, use `array[].map!`
* instead of `array.map!`). The container itself is not a range.
*/
struct Array(T)
if (!is(immutable T == immutable bool))
{
import core.memory : free = pureFree;
import std.internal.memory : enforceMalloc, enforceRealloc;
import core.stdc.string : memcpy, memmove, memset;
import core.memory : GC;
import std.exception : enforce;
import std.typecons : RefCounted, RefCountedAutoInitialize;
// This structure is not copyable.
private struct Payload
{
size_t _capacity;
T[] _payload;
this(T[] p) { _capacity = p.length; _payload = p; }
// Destructor releases array memory
~this()
{
// Warning: destroy would destroy also class instances.
// The hasElaborateDestructor protects us here.
static if (hasElaborateDestructor!T)
foreach (ref e; _payload)
.destroy(e);
static if (hasIndirections!T)
GC.removeRange(_payload.ptr);
free(_payload.ptr);
}
this(this) @disable;
void opAssign(Payload rhs) @disable;
@property size_t length() const
{
return _payload.length;
}
@property void length(size_t newLength)
{
import std.algorithm.mutation : initializeAll;
if (length >= newLength)
{
// shorten
static if (hasElaborateDestructor!T)
foreach (ref e; _payload.ptr[newLength .. _payload.length])
.destroy(e);
_payload = _payload.ptr[0 .. newLength];
return;
}
immutable startEmplace = length;
if (_capacity < newLength)
{
// enlarge
static if (T.sizeof == 1)
{
const nbytes = newLength;
}
else
{
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(newLength, T.sizeof, overflow);
if (overflow)
assert(false, "Overflow");
}
static if (hasIndirections!T)
{
auto newPayloadPtr = cast(T*) enforceMalloc(nbytes);
auto newPayload = newPayloadPtr[0 .. newLength];
memcpy(newPayload.ptr, _payload.ptr, startEmplace * T.sizeof);
memset(newPayload.ptr + startEmplace, 0,
(newLength - startEmplace) * T.sizeof);
GC.addRange(newPayload.ptr, nbytes);
GC.removeRange(_payload.ptr);
free(_payload.ptr);
_payload = newPayload;
}
else
{
_payload = (cast(T*) enforceRealloc(_payload.ptr,
nbytes))[0 .. newLength];
}
_capacity = newLength;
}
else
{
_payload = _payload.ptr[0 .. newLength];
}
initializeAll(_payload.ptr[startEmplace .. newLength]);
}
@property size_t capacity() const
{
return _capacity;
}
void reserve(size_t elements)
{
if (elements <= capacity) return;
static if (T.sizeof == 1)
{
const sz = elements;
}
else
{
import core.checkedint : mulu;
bool overflow;
const sz = mulu(elements, T.sizeof, overflow);
if (overflow)
assert(false, "Overflow");
}
static if (hasIndirections!T)
{
/* Because of the transactional nature of this
* relative to the garbage collector, ensure no
* threading bugs by using malloc/copy/free rather
* than realloc.
*/
immutable oldLength = length;
auto newPayloadPtr = cast(T*) enforceMalloc(sz);
auto newPayload = newPayloadPtr[0 .. oldLength];
// copy old data over to new array
memcpy(newPayload.ptr, _payload.ptr, T.sizeof * oldLength);
// Zero out unused capacity to prevent gc from seeing false pointers
memset(newPayload.ptr + oldLength,
0,
(elements - oldLength) * T.sizeof);
GC.addRange(newPayload.ptr, sz);
GC.removeRange(_payload.ptr);
free(_payload.ptr);
_payload = newPayload;
}
else
{
// These can't have pointers, so no need to zero unused region
auto newPayloadPtr = cast(T*) enforceRealloc(_payload.ptr, sz);
auto newPayload = newPayloadPtr[0 .. length];
_payload = newPayload;
}
_capacity = elements;
}
// Insert one item
size_t insertBack(Elem)(Elem elem)
if (isImplicitlyConvertible!(Elem, T))
{
import core.lifetime : emplace;
if (_capacity == length)
{
reserve(1 + capacity * 3 / 2);
}
assert(capacity > length && _payload.ptr,
"Failed to reserve memory");
emplace(_payload.ptr + _payload.length, elem);
_payload = _payload.ptr[0 .. _payload.length + 1];
return 1;
}
// Insert a range of items
size_t insertBack(Range)(Range r)
if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range, T))
{
static if (hasLength!Range)
{
immutable oldLength = length;
reserve(oldLength + r.length);
}
size_t result;
foreach (item; r)
{
insertBack(item);
++result;
}
static if (hasLength!Range)
{
assert(length == oldLength + r.length,
"Failed to insertBack range");
}
return result;
}
}
private alias Data = RefCounted!(Payload, RefCountedAutoInitialize.no);
private Data _data;
/**
* Constructor taking a number of items.
*/
this(U)(U[] values...)
if (isImplicitlyConvertible!(U, T))
{
import core.lifetime : emplace;
static if (T.sizeof == 1)
{
const nbytes = values.length;
}
else
{
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(values.length, T.sizeof, overflow);
if (overflow)
assert(false, "Overflow");
}
auto p = cast(T*) enforceMalloc(nbytes);
// Before it is added to the gc, initialize the newly allocated memory
foreach (i, e; values)
{
emplace(p + i, e);
}
static if (hasIndirections!T)
{
if (p)
GC.addRange(p, T.sizeof * values.length);
}
_data = Data(p[0 .. values.length]);
}
/**
* Constructor taking an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
*/
this(Range)(Range r)
if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range, T) && !is(Range == T[]))
{
insertBack(r);
}
/**
* Comparison for equality.
*/
bool opEquals(const Array rhs) const
{
return opEquals(rhs);
}
/// ditto
bool opEquals(ref const Array rhs) const
{
if (empty) return rhs.empty;
if (rhs.empty) return false;
return _data._payload == rhs._data._payload;
}
/**
* Defines the array's primary range, which is a random-access range.
*
* `ConstRange` is a variant with `const` elements.
* `ImmutableRange` is a variant with `immutable` elements.
*/
alias Range = RangeT!Array;
/// ditto
alias ConstRange = RangeT!(const Array);
/// ditto
alias ImmutableRange = RangeT!(immutable Array);
/**
* Duplicates the array. The elements themselves are not transitively
* duplicated.
*
* Complexity: $(BIGOH length).
*/
@property Array dup()
{
if (!_data.refCountedStore.isInitialized) return this;
return Array(_data._payload);
}
/**
* Returns: `true` if and only if the array has no elements.
*
* Complexity: $(BIGOH 1)
*/
@property bool empty() const
{
return !_data.refCountedStore.isInitialized || _data._payload.empty;
}
/**
* Returns: The number of elements in the array.
*
* Complexity: $(BIGOH 1).
*/
@property size_t length() const
{
return _data.refCountedStore.isInitialized ? _data._payload.length : 0;
}
/// ditto
size_t opDollar() const
{
return length;
}
/**
* Returns: The maximum number of elements the array can store without
* reallocating memory and invalidating iterators upon insertion.
*
* Complexity: $(BIGOH 1)
*/
@property size_t capacity()
{
return _data.refCountedStore.isInitialized ? _data._capacity : 0;
}
/**
* Ensures sufficient capacity to accommodate `e` _elements.
* If `e < capacity`, this method does nothing.
*
* Postcondition: `capacity >= e`
*
* Note: If the capacity is increased, one should assume that all
* iterators to the elements are invalidated.
*
* Complexity: at most $(BIGOH length) if `e > capacity`, otherwise $(BIGOH 1).
*/
void reserve(size_t elements)
{
if (!_data.refCountedStore.isInitialized)
{
if (!elements) return;
static if (T.sizeof == 1)
{
const sz = elements;
}
else
{
import core.checkedint : mulu;
bool overflow;
const sz = mulu(elements, T.sizeof, overflow);
if (overflow)
assert(false, "Overflow");
}
auto p = enforceMalloc(sz);
static if (hasIndirections!T)
{
// Zero out unused capacity to prevent gc from seeing false pointers
memset(p, 0, sz);
GC.addRange(p, sz);
}
_data = Data(cast(T[]) p[0 .. 0]);
_data._capacity = elements;
}
else
{
_data.reserve(elements);
}
}
/**
* Returns: A range that iterates over elements of the array in
* forward order.
*
* Complexity: $(BIGOH 1)
*/
Range opSlice()
{
return typeof(return)(this, 0, length);
}
ConstRange opSlice() const
{
return typeof(return)(this, 0, length);
}
ImmutableRange opSlice() immutable
{
return typeof(return)(this, 0, length);
}
/**
* Returns: A range that iterates over elements of the array from
* index `i` up to (excluding) index `j`.
*
* Precondition: `i <= j && j <= length`
*
* Complexity: $(BIGOH 1)
*/
Range opSlice(size_t i, size_t j)
{
assert(i <= j && j <= length, "Invalid slice bounds");
return typeof(return)(this, i, j);
}
ConstRange opSlice(size_t i, size_t j) const
{
assert(i <= j && j <= length, "Invalid slice bounds");
return typeof(return)(this, i, j);
}
ImmutableRange opSlice(size_t i, size_t j) immutable
{
assert(i <= j && j <= length, "Invalid slice bounds");
return typeof(return)(this, i, j);
}
/**
* Returns: The first element of the array.
*
* Precondition: `empty == false`
*
* Complexity: $(BIGOH 1)
*/
@property ref inout(T) front() inout
{
assert(_data.refCountedStore.isInitialized,
"Cannot get front of empty range");
return _data._payload[0];
}
/**
* Returns: The last element of the array.
*
* Precondition: `empty == false`
*
* Complexity: $(BIGOH 1)
*/
@property ref inout(T) back() inout
{
assert(_data.refCountedStore.isInitialized,
"Cannot get back of empty range");
return _data._payload[$ - 1];
}
/**
* Returns: The element or a reference to the element at the specified index.
*
* Precondition: `i < length`
*
* Complexity: $(BIGOH 1)
*/
ref inout(T) opIndex(size_t i) inout
{
assert(_data.refCountedStore.isInitialized,
"Cannot index empty range");
return _data._payload[i];
}
/**
* Slicing operators executing the specified operation on the entire slice.
*
* Precondition: `i < j && j < length`
*
* Complexity: $(BIGOH slice.length)
*/
void opSliceAssign(T value)
{
if (!_data.refCountedStore.isInitialized) return;
_data._payload[] = value;
}
/// ditto
void opSliceAssign(T value, size_t i, size_t j)
{
auto slice = _data.refCountedStore.isInitialized ?
_data._payload :
T[].init;
slice[i .. j] = value;
}
/// ditto
void opSliceUnary(string op)()
if (op == "++" || op == "--")
{
if (!_data.refCountedStore.isInitialized) return;
mixin(op~"_data._payload[];");
}
/// ditto
void opSliceUnary(string op)(size_t i, size_t j)
if (op == "++" || op == "--")
{
auto slice = _data.refCountedStore.isInitialized ? _data._payload : T[].init;
mixin(op~"slice[i .. j];");
}
/// ditto
void opSliceOpAssign(string op)(T value)
{
if (!_data.refCountedStore.isInitialized) return;
mixin("_data._payload[] "~op~"= value;");
}
/// ditto
void opSliceOpAssign(string op)(T value, size_t i, size_t j)
{
auto slice = _data.refCountedStore.isInitialized ? _data._payload : T[].init;
mixin("slice[i .. j] "~op~"= value;");
}
private enum hasSliceWithLength(T) = is(typeof({ T t = T.init; t[].length; }));
/**
* Returns: A new array which is a concatenation of `this` and its argument.
*
* Complexity:
* $(BIGOH length + m), where `m` is the number of elements in `stuff`.
*/
Array opBinary(string op, Stuff)(Stuff stuff)
if (op == "~")
{
Array result;
static if (hasLength!Stuff || isNarrowString!Stuff)
result.reserve(length + stuff.length);
else static if (hasSliceWithLength!Stuff)
result.reserve(length + stuff[].length);
else static if (isImplicitlyConvertible!(Stuff, T))
result.reserve(length + 1);
result.insertBack(this[]);
result ~= stuff;
return result;
}
/**
* Forwards to `insertBack`.
*/
void opOpAssign(string op, Stuff)(auto ref Stuff stuff)
if (op == "~")
{
static if (is(typeof(stuff[])) && isImplicitlyConvertible!(typeof(stuff[0]), T))
{
insertBack(stuff[]);
}
else
{
insertBack(stuff);
}
}
/**
* Removes all the elements from the array and releases allocated memory.
*
* Postcondition: `empty == true && capacity == 0`
*
* Complexity: $(BIGOH length)
*/
void clear()
{
_data = Data.init;
}
/**
* Sets the number of elements in the array to `newLength`. If `newLength`
* is greater than `length`, the new elements are added to the end of the
* array and initialized with `T.init`.
*
* Complexity:
* Guaranteed $(BIGOH abs(length - newLength)) if `capacity >= newLength`.
* If `capacity < newLength` the worst case is $(BIGOH newLength).
*
* Postcondition: `length == newLength`
*/
@property void length(size_t newLength)
{
_data.refCountedStore.ensureInitialized();
_data.length = newLength;
}
/**
* Removes the last element from the array and returns it.
* Both stable and non-stable versions behave the same and guarantee
* that ranges iterating over the array are never invalidated.
*
* Precondition: `empty == false`
*
* Returns: The element removed.
*
* Complexity: $(BIGOH 1).
*
* Throws: `Exception` if the array is empty.
*/
T removeAny()
{
auto result = back;
removeBack();
return result;
}
/// ditto
alias stableRemoveAny = removeAny;
/**
* Inserts the specified elements at the back of the array. `stuff` can be
* a value convertible to `T` or a range of objects convertible to `T`.
*
* Returns: The number of elements inserted.
*
* Complexity:
* $(BIGOH length + m) if reallocation takes place, otherwise $(BIGOH m),
* where `m` is the number of elements in `stuff`.
*/
size_t insertBack(Stuff)(Stuff stuff)
if (isImplicitlyConvertible!(Stuff, T) ||
isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T))
{
_data.refCountedStore.ensureInitialized();
return _data.insertBack(stuff);
}
/// ditto
alias insert = insertBack;
/**
* Removes the value from the back of the array. Both stable and non-stable
* versions behave the same and guarantee that ranges iterating over the
* array are never invalidated.
*
* Precondition: `empty == false`
*
* Complexity: $(BIGOH 1).
*
* Throws: `Exception` if the array is empty.
*/
void removeBack()
{
enforce(!empty);
static if (hasElaborateDestructor!T)
.destroy(_data._payload[$ - 1]);
_data._payload = _data._payload[0 .. $ - 1];
}
/// ditto
alias stableRemoveBack = removeBack;
/**
* Removes `howMany` values from the back of the array.
* Unlike the unparameterized versions above, these functions
* do not throw if they could not remove `howMany` elements. Instead,
* if `howMany > n`, all elements are removed. The returned value is
* the effective number of elements removed. Both stable and non-stable
* versions behave the same and guarantee that ranges iterating over
* the array are never invalidated.
*
* Returns: The number of elements removed.
*
* Complexity: $(BIGOH howMany).
*/
size_t removeBack(size_t howMany)
{
if (howMany > length) howMany = length;
static if (hasElaborateDestructor!T)
foreach (ref e; _data._payload[$ - howMany .. $])
.destroy(e);
_data._payload = _data._payload[0 .. $ - howMany];
return howMany;
}
/// ditto
alias stableRemoveBack = removeBack;
/**
* Inserts `stuff` before, after, or instead range `r`, which must
* be a valid range previously extracted from this array. `stuff`
* can be a value convertible to `T` or a range of objects convertible
* to `T`. Both stable and non-stable version behave the same and
* guarantee that ranges iterating over the array are never invalidated.
*
* Returns: The number of values inserted.
*
* Complexity: $(BIGOH length + m), where `m` is the length of `stuff`.
*
* Throws: `Exception` if `r` is not a range extracted from this array.
*/
size_t insertBefore(Stuff)(Range r, Stuff stuff)
if (isImplicitlyConvertible!(Stuff, T))
{
import core.lifetime : emplace;
enforce(r._outer._data is _data && r._a <= length);
reserve(length + 1);
assert(_data.refCountedStore.isInitialized,
"Failed to allocate capacity to insertBefore");
// Move elements over by one slot
memmove(_data._payload.ptr + r._a + 1,
_data._payload.ptr + r._a,
T.sizeof * (length - r._a));
emplace(_data._payload.ptr + r._a, stuff);
_data._payload = _data._payload.ptr[0 .. _data._payload.length + 1];
return 1;
}
/// ditto
size_t insertBefore(Stuff)(Range r, Stuff stuff)
if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T))
{
import core.lifetime : emplace;
enforce(r._outer._data is _data && r._a <= length);
static if (isForwardRange!Stuff)
{
// Can find the length in advance
auto extra = walkLength(stuff);
if (!extra) return 0;
reserve(length + extra);
assert(_data.refCountedStore.isInitialized,
"Failed to allocate capacity to insertBefore");
// Move elements over by extra slots
memmove(_data._payload.ptr + r._a + extra,
_data._payload.ptr + r._a,
T.sizeof * (length - r._a));
foreach (p; _data._payload.ptr + r._a ..
_data._payload.ptr + r._a + extra)
{
emplace(p, stuff.front);
stuff.popFront();
}
_data._payload =
_data._payload.ptr[0 .. _data._payload.length + extra];
return extra;
}
else
{
import std.algorithm.mutation : bringToFront;
enforce(_data);
immutable offset = r._a;
enforce(offset <= length);
auto result = insertBack(stuff);
bringToFront(this[offset .. length - result],
this[length - result .. length]);