/
array.d
2304 lines (2028 loc) · 58.3 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 $(D 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 std.range.primitives;
import std.traits;
import core.exception : RangeError;
public import std.container.util;
///
@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);
}
///
@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
@system unittest
{
Array!bool arr;
arr.insert([true, true, false, true, false]);
assert(arr.length == 5);
}
private struct RangeT(A)
{
/* Workaround for Issue 13629 at 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 && _a < _outer.length);
return move(_outer._data._payload[_a]);
}
E moveBack()
{
assert(!empty && _b <= _outer.length);
return move(_outer._data._payload[_b - 1]);
}
E moveAt(size_t i)
{
assert(_a + i < _b && _a + i < _outer.length);
return move(_outer._data._payload[_a + i]);
}
}
ref inout(E) opIndex(size_t i) inout
{
assert(_a + i < _b);
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);
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);
return typeof(return)(_outer, _a + i, _a + j);
}
static if (isMutable!A)
{
void opSliceAssign(E value)
{
assert(_b <= _outer.length);
_outer[_a .. _b] = value;
}
void opSliceAssign(E value, size_t i, size_t j)
{
assert(_a + j <= _b);
_outer[_a + i .. _a + j] = value;
}
void opSliceUnary(string op)()
if (op == "++" || op == "--")
{
assert(_b <= _outer.length);
mixin(op~"_outer[_a .. _b];");
}
void opSliceUnary(string op)(size_t i, size_t j)
if (op == "++" || op == "--")
{
assert(_a + j <= _b);
mixin(op~"_outer[_a + i .. _a + j];");
}
void opSliceOpAssign(string op)(E value)
{
assert(_b <= _outer.length);
mixin("_outer[_a .. _b] "~op~"= value;");
}
void opSliceOpAssign(string op)(E value, size_t i, size_t j)
{
assert(_a + j <= _b);
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. $(D Array) uses $(D malloc) and $(D free)
for managing its own memory.
This means that pointers to elements of an $(D Array) will become
dangling as soon as the element is removed from the $(D Array). On the other hand
the memory allocated by an $(D Array) will be scanned by the GC and
GC managed objects referenced from an $(D Array) will be kept alive.
Note:
When using $(D Array) with range-based functions like those in $(D std.algorithm),
$(D Array) must be sliced to get a range (for example, use $(D array[].map!)
instead of $(D array.map!)). The container itself is not a range.
*/
struct Array(T)
if (!is(Unqual!T == bool))
{
import core.stdc.stdlib : malloc, realloc, free;
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;
// Convenience constructor
this(T[] p) { _capacity = p.length; _payload = p; }
// Destructor releases array memory
~this()
{
//Warning: destroy will also destroy 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)
{
assert(0);
}
void opAssign(Payload rhs)
{
assert(false);
}
// Duplicate data
// @property Payload dup()
// {
// Payload result;
// result._payload = _payload.dup;
// // Conservatively assume initial capacity == length
// result._capacity = result._payload.length;
// return result;
// }
// length
@property size_t length() const
{
return _payload.length;
}
// 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;
}
// enlarge
auto startEmplace = length;
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(newLength, T.sizeof, overflow);
if (overflow) assert(0);
_payload = (cast(T*) realloc(_payload.ptr,
nbytes))[0 .. newLength];
initializeAll(_payload.ptr[startEmplace .. length]);
_capacity = newLength;
}
// capacity
@property size_t capacity() const
{
return _capacity;
}
// reserve
void reserve(size_t elements)
{
if (elements <= capacity) return;
import core.checkedint : mulu;
bool overflow;
const sz = mulu(elements, T.sizeof, overflow);
if (overflow) assert(0);
static if (hasIndirections!T) // should use hasPointers instead
{
/* 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*) malloc(sz);
newPayloadPtr || assert(false, "std.container.Array.reserve failed to allocate memory");
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*) realloc(_payload.ptr, sz);
newPayloadPtr || assert(false, "std.container.Array.reserve failed to allocate memory");
auto newPayload = newPayloadPtr[0 .. length];
_payload = newPayload;
}
_capacity = elements;
}
// Insert one item
size_t insertBack(Stuff)(Stuff stuff)
if (isImplicitlyConvertible!(Stuff, T))
{
import std.conv : emplace;
if (_capacity == length)
{
reserve(1 + capacity * 3 / 2);
}
assert(capacity > length && _payload.ptr);
emplace(_payload.ptr + _payload.length, stuff);
_payload = _payload.ptr[0 .. _payload.length + 1];
return 1;
}
/// Insert a range of items
size_t insertBack(Stuff)(Stuff stuff)
if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T))
{
static if (hasLength!Stuff)
{
immutable oldLength = length;
reserve(oldLength + stuff.length);
}
size_t result;
foreach (item; stuff)
{
insertBack(item);
++result;
}
static if (hasLength!Stuff)
{
assert(length == oldLength + stuff.length);
}
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 std.conv : emplace;
import core.checkedint : mulu;
bool overflow;
const nbytes = mulu(values.length, T.sizeof, overflow);
if (overflow) assert(0);
auto p = cast(T*) malloc(nbytes);
static if (hasIndirections!T)
{
if (p)
GC.addRange(p, T.sizeof * values.length);
}
foreach (i, e; values)
{
emplace(p + i, e);
}
_data = Data(p[0 .. values.length]);
}
/**
Constructor taking an input range
*/
this(Stuff)(Stuff stuff)
if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T) && !is(Stuff == T[]))
{
insertBack(stuff);
}
/**
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 container'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;
alias ConstRange = RangeT!(const Array); /// ditto
alias ImmutableRange = RangeT!(immutable Array); /// ditto
/**
Duplicates the container. The elements themselves are not transitively
duplicated.
Complexity: $(BIGOH n).
*/
@property Array dup()
{
if (!_data.refCountedStore.isInitialized) return this;
return Array(_data._payload);
}
/**
Property returning $(D true) if and only if the container has no
elements.
Complexity: $(BIGOH 1)
*/
@property bool empty() const
{
return !_data.refCountedStore.isInitialized || _data._payload.empty;
}
/**
Returns the number of elements in the container.
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 container can store without
(a) allocating memory, (b) invalidating iterators upon insertion.
Complexity: $(BIGOH 1)
*/
@property size_t capacity()
{
return _data.refCountedStore.isInitialized ? _data._capacity : 0;
}
/**
Ensures sufficient capacity to accommodate $(D e) elements.
Postcondition: $(D capacity >= e)
Complexity: $(BIGOH 1)
*/
void reserve(size_t elements)
{
if (!_data.refCountedStore.isInitialized)
{
if (!elements) return;
import core.checkedint : mulu;
bool overflow;
const sz = mulu(elements, T.sizeof, overflow);
if (overflow) assert(0);
auto p = malloc(sz);
p || assert(false, "std.container.Array.reserve failed to allocate memory");
static if (hasIndirections!T)
{
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 container, 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 container from
index $(D i) up to (excluding) index $(D j).
Precondition: $(D i <= j && j <= length)
Complexity: $(BIGOH 1)
*/
Range opSlice(size_t i, size_t j)
{
assert(i <= j && j <= length);
return typeof(return)(this, i, j);
}
ConstRange opSlice(size_t i, size_t j) const
{
assert(i <= j && j <= length);
return typeof(return)(this, i, j);
}
ImmutableRange opSlice(size_t i, size_t j) immutable
{
assert(i <= j && j <= length);
return typeof(return)(this, i, j);
}
/**
Forward to $(D opSlice().front) and $(D opSlice().back), respectively.
Precondition: $(D !empty)
Complexity: $(BIGOH 1)
*/
@property ref inout(T) front() inout
{
assert(_data.refCountedStore.isInitialized);
return _data._payload[0];
}
/// ditto
@property ref inout(T) back() inout
{
assert(_data.refCountedStore.isInitialized);
return _data._payload[$ - 1];
}
/**
Indexing operators yield or modify the value at a specified index.
Precondition: $(D i < length)
Complexity: $(BIGOH 1)
*/
ref inout(T) opIndex(size_t i) inout
{
assert(_data.refCountedStore.isInitialized);
return _data._payload[i];
}
/**
Slicing operations execute an operation on an entire slice.
Precondition: $(D 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;");
}
/**
Returns a new container that's the concatenation of $(D this) and its
argument. $(D opBinaryRight) is only defined if $(D Stuff) does not
define $(D opBinary).
Complexity: $(BIGOH n + m), where m is the number of elements in $(D
stuff)
*/
Array opBinary(string op, Stuff)(Stuff stuff)
if (op == "~")
{
// TODO: optimize
Array result;
result ~= this[];
assert(result.length == length);
result ~= stuff[];
return result;
}
/**
Forwards to $(D insertBack(stuff)).
*/
void opOpAssign(string op, Stuff)(Stuff stuff)
if (op == "~")
{
static if (is(typeof(stuff[])))
{
insertBack(stuff[]);
}
else
{
insertBack(stuff);
}
}
/**
Removes all contents from the container. The container decides how $(D
capacity) is affected.
Postcondition: $(D empty)
Complexity: $(BIGOH n)
*/
void clear()
{
_data = Data.init;
}
/**
Sets the number of elements in the container to $(D newSize). If $(D
newSize) is greater than $(D length), the added elements are added to
unspecified positions in the container and initialized with $(D
T.init).
Complexity: $(BIGOH abs(n - newLength))
Postcondition: $(D length == newLength)
*/
@property void length(size_t newLength)
{
_data.refCountedStore.ensureInitialized();
_data.length = newLength;
}
/**
Picks one value in an unspecified position in the container, removes
it from the container, and returns it. The stable version behaves the same,
but guarantees that ranges iterating over the container are never invalidated.
Precondition: $(D !empty)
Returns: The element removed.
Complexity: $(BIGOH log(n)).
*/
T removeAny()
{
auto result = back;
removeBack();
return result;
}
/// ditto
alias stableRemoveAny = removeAny;
/**
Inserts $(D value) to the front or back of the container. $(D stuff)
can be a value convertible to $(D T) or a range of objects convertible
to $(D T). The stable version behaves the same, but guarantees that
ranges iterating over the container are never invalidated.
Returns: The number of elements inserted
Complexity: $(BIGOH m * log(n)), where $(D m) is the number of
elements in $(D 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 at the back of the container. The stable version
behaves the same, but guarantees that ranges iterating over the
container are never invalidated.
Precondition: $(D !empty)
Complexity: $(BIGOH log(n)).
*/
void removeBack()
{
enforce(!empty);
static if (hasElaborateDestructor!T)
.destroy(_data._payload[$ - 1]);
_data._payload = _data._payload[0 .. $ - 1];
}
/// ditto
alias stableRemoveBack = removeBack;
/**
Removes $(D howMany) values at the front or back of the
container. Unlike the unparameterized versions above, these functions
do not throw if they could not remove $(D howMany) elements. Instead,
if $(D howMany > n), all elements are removed. The returned value is
the effective number of elements removed. The stable version behaves
the same, but guarantees that ranges iterating over the container 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 $(D stuff) before, after, or instead range $(D r), which must
be a valid range previously extracted from this container. $(D stuff)
can be a value convertible to $(D T) or a range of objects convertible
to $(D T). The stable version behaves the same, but guarantees that
ranges iterating over the container are never invalidated.
Returns: The number of values inserted.
Complexity: $(BIGOH n + m), where $(D m) is the length of $(D stuff)
*/
size_t insertBefore(Stuff)(Range r, Stuff stuff)
if (isImplicitlyConvertible!(Stuff, T))
{
import std.conv : emplace;
enforce(r._outer._data is _data && r._a <= length);
reserve(length + 1);
assert(_data.refCountedStore.isInitialized);
// 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 std.conv : 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);
// 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]);
return result;
}
}
/// ditto
size_t insertAfter(Stuff)(Range r, Stuff stuff)
{
import std.algorithm.mutation : bringToFront;
enforce(r._outer._data is _data);
// TODO: optimize
immutable offset = r._b;
enforce(offset <= length);
auto result = insertBack(stuff);
bringToFront(this[offset .. length - result],
this[length - result .. length]);
return result;
}
/// ditto
size_t replace(Stuff)(Range r, Stuff stuff)
if (isInputRange!Stuff && isImplicitlyConvertible!(ElementType!Stuff, T))
{
enforce(r._outer._data is _data);
size_t result;
for (; !stuff.empty; stuff.popFront())
{
if (r.empty)
{
// insert the rest
return result + insertBefore(r, stuff);
}
r.front = stuff.front;
r.popFront();
++result;
}
// Remove remaining stuff in r
linearRemove(r);
return result;
}
/// ditto
size_t replace(Stuff)(Range r, Stuff stuff)
if (isImplicitlyConvertible!(Stuff, T))
{
enforce(r._outer._data is _data);
if (r.empty)
{
insertBefore(r, stuff);
}
else
{
r.front = stuff;
r.popFront();
linearRemove(r);
}
return 1;
}
/**
Removes all elements belonging to $(D r), which must be a range
obtained originally from this container. The stable version behaves
the same, but guarantees that ranges iterating over the container are
never invalidated.
Returns: A range spanning the remaining elements in the container that
initially were right after $(D r).
Complexity: $(BIGOH n - m), where $(D m) is the number of elements in
$(D r)
*/
Range linearRemove(Range r)
{
import std.algorithm.mutation : copy;
enforce(r._outer._data is _data);
enforce(_data.refCountedStore.isInitialized);
enforce(r._a <= r._b && r._b <= length);
immutable offset1 = r._a;
immutable offset2 = r._b;
immutable tailLength = length - offset2;
// Use copy here, not a[] = b[] because the ranges may overlap
copy(this[offset2 .. length], this[offset1 .. offset1 + tailLength]);
length = offset1 + tailLength;
return this[length - tailLength .. length];
}
}