Debian Codegraph @

src/containers/dynamicarray.d

raw
1 /**
2 * Dynamic Array
3 * Copyright: © 2015 Economic Modeling Specialists, Intl.
4 * Authors: Brian Schott
5 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
6 */
7
8 module containers.dynamicarray;
9
10 private import core.lifetime : move, moveEmplace, copyEmplace, emplace;
11 private import std.traits : isCopyable;
12 private import containers.internal.node : shouldAddGCRange;
13 private import std.experimental.allocator.mallocator : Mallocator;
14
15 /**
16 * Array that is able to grow itself when items are appended to it. Uses
17 * malloc/free/realloc to manage its storage.
18 *
19 * Params:
20 * T = the array element type
21 * Allocator = the allocator to use. Defaults to `Mallocator`.
22 * supportGC = true if the container should support holding references to
23 * GC-allocated memory.
24 */
25 struct DynamicArray(T, Allocator = Mallocator, bool supportGC = shouldAddGCRange!T)
26 {
27 this(this) @disable;
28
29 private import std.experimental.allocator.common : stateSize;
30
31 static if (is(typeof((T[] a, const T[] b) => a[0 .. b.length] = b[0 .. $])))
32 {
33 /// Either `const(T)` or `T`.
34 alias AppendT = const(T);
35
36 /// Either `const(typeof(this))` or `typeof(this)`.
37 alias AppendTypeOfThis = const(typeof(this));
38 }
39 else
40 {
41 alias AppendT = T;
42 alias AppendTypeOfThis = typeof(this);
43 }
44
45 static if (stateSize!Allocator != 0)
46 {
47 /// No default construction if an allocator must be provided.
48 this() @disable;
49
50 /**
51 * Use the given `allocator` for allocations.
52 */
53 this(Allocator allocator)
54 in
55 {
56 assert(allocator !is null, "Allocator must not be null");
57 }
58 do
59 {
60 this.allocator = allocator;
61 }
62 }
63
64 ~this()
65 {
66 import std.experimental.allocator.mallocator : Mallocator;
67 import containers.internal.node : shouldAddGCRange;
68
69 if (arr is null)
70 return;
71
72 static if ((is(T == struct) || is(T == union))
73 && __traits(hasMember, T, "__xdtor"))
74 {
75 foreach (ref item; arr[0 .. l])
76 {
77 item.__xdtor();
78 }
79 }
80 static if (useGC)
81 {
82 import core.memory : GC;
83 GC.removeRange(arr.ptr);
84 }
85 allocator.deallocate(arr);
86 }
87
88 /// Slice operator overload
89 pragma(inline, true)
90 auto opSlice(this This)() @nogc
91 {
92 return opSlice!(This)(0, l);
93 }
94
95 /// ditto
96 pragma(inline, true)
97 auto opSlice(this This)(size_t a, size_t b) @nogc
98 {
99 alias ET = ContainerElementType!(This, T);
100 return cast(ET[]) arr[a .. b];
101 }
102
103 /// Index operator overload
104 pragma(inline, true)
105 ref auto opIndex(this This)(size_t i) @nogc
106 {
107 return opSlice!(This)(i, i + 1)[0];
108 }
109
110 /**
111 * Inserts the given value into the end of the array.
112 */
113 void insertBack(T value)
114 {
115 import std.experimental.allocator.mallocator : Mallocator;
116 import containers.internal.node : shouldAddGCRange;
117
118 if (arr.length == 0)
119 {
120 arr = cast(typeof(arr)) allocator.allocate(T.sizeof * 4);
121 static if (useGC)
122 {
123 import core.memory: GC;
124 GC.addRange(arr.ptr, arr.length * T.sizeof);
125 }
126 }
127 else if (l >= arr.length)
128 {
129 immutable size_t c = arr.length > 512 ? arr.length + 1024 : arr.length << 1;
130 static if (useGC)
131 void* oldPtr = arr.ptr;
132 void[] a = cast(void[]) arr;
133 import std.experimental.allocator.common : reallocate;
134 allocator.reallocate(a, c * T.sizeof);
135 arr = cast(typeof(arr)) a;
136 static if (useGC)
137 {
138 import core.memory: GC;
139 GC.removeRange(oldPtr);
140 GC.addRange(arr.ptr, arr.length * T.sizeof);
141 }
142 }
143 moveEmplace(*cast(ContainerStorageType!T*)&value, arr[l++]);
144 }
145
146 /// ditto
147 alias insert = insertBack;
148
149 /// ditto
150 alias insertAnywhere = insertBack;
151
152 /// ditto
153 alias put = insertBack;
154
155 /**
156 * ~= operator overload
157 */
158 scope ref typeof(this) opOpAssign(string op)(T value) if (op == "~")
159 {
160 insert(value);
161 return this;
162 }
163
164 /**
165 * ~= operator overload for an array of items
166 */
167 scope ref typeof(this) opOpAssign(string op, bool checkForOverlap = true)(AppendT[] rhs)
168 if (op == "~" && !is(T == AppendT[]))
169 {
170 // Disabling checkForOverlap when this function is called from opBinary!"~"
171 // is not just for efficiency, but to avoid circular function calls that
172 // would prevent inference of @nogc, etc.
173 static if (checkForOverlap)
174 if ((() @trusted => arr.ptr <= rhs.ptr && arr.ptr + arr.length > rhs.ptr)())
175 {
176 // Special case where rhs is a slice of this array.
177 this = this ~ rhs;
178 return this;
179 }
180 reserve(l + rhs.length);
181 import std.traits: hasElaborateAssign, hasElaborateDestructor;
182 static if (is(T == struct) && (hasElaborateAssign!T || hasElaborateDestructor!T))
183 {
184 foreach (ref value; rhs)
185 copyEmplace(value, arr[l++]);
186 }
187 else
188 {
189 arr[l .. l + rhs.length] = rhs[0 .. rhs.length];
190 l += rhs.length;
191 }
192 return this;
193 }
194
195 /// ditto
196 scope ref typeof(this) opOpAssign(string op)(ref AppendTypeOfThis rhs)
197 if (op == "~")
198 {
199 return this ~= rhs.arr[0 .. rhs.l];
200 }
201
202 /**
203 * ~ operator overload
204 */
205 typeof(this) opBinary(string op)(ref AppendTypeOfThis other) if (op == "~")
206 {
207 typeof(this) ret;
208 ret.reserve(l + other.l);
209 ret.opOpAssign!("~", false)(arr[0 .. l]);
210 ret.opOpAssign!("~", false)(other.arr[0 .. other.l]);
211 return ret;
212 }
213
214 /// ditto
215 typeof(this) opBinary(string op)(AppendT[] values) if (op == "~")
216 {
217 typeof(this) ret;
218 ret.reserve(l + values.length);
219 ret.opOpAssign!("~", false)(arr[0 .. l]);
220 ret.opOpAssign!("~", false)(values);
221 return ret;
222 }
223
224 /**
225 * Ensures sufficient capacity to accommodate `n` elements.
226 */
227 void reserve(size_t n)
228 {
229 if (arr.length >= n)
230 return;
231 if (arr.ptr is null)
232 {
233 size_t c = 4;
234 if (c < n)
235 c = n;
236 arr = cast(typeof(arr)) allocator.allocate(T.sizeof * c);
237 static if (useGC)
238 {
239 import core.memory: GC;
240 GC.addRange(arr.ptr, arr.length * T.sizeof);
241 }
242 }
243 else
244 {
245 size_t c = arr.length > 512 ? arr.length + 1024 : arr.length << 1;
246 if (c < n)
247 c = n;
248 static if (useGC)
249 void* oldPtr = arr.ptr;
250 void[] a = cast(void[]) arr;
251 import std.experimental.allocator.common : reallocate;
252 allocator.reallocate(a, c * T.sizeof);
253 arr = cast(typeof(arr)) a;
254 static if (useGC)
255 {
256 import core.memory: GC;
257 GC.removeRange(oldPtr);
258 GC.addRange(arr.ptr, arr.length * T.sizeof);
259 }
260 }
261 }
262
263 /**
264 * Change the array length.
265 * When growing, initialize new elements to the default value.
266 */
267 static if (is(typeof({static T value;}))) // default construction is allowed
268 void resize(size_t n)
269 {
270 import std.traits: hasElaborateAssign, hasElaborateDestructor;
271 auto toFill = resizeStorage(n);
272 static if (is(T == struct) && hasElaborateDestructor!T)
273 {
274 foreach (ref target; toFill)
275 emplace(&target);
276 }
277 else
278 toFill[] = T.init;
279 }
280
281 /**
282 * Change the array length.
283 * When growing, initialize new elements to the given value.
284 */
285 static if (isCopyable!T)
286 void resize(size_t n, T value)
287 {
288 import std.traits: hasElaborateAssign, hasElaborateDestructor;
289 auto toFill = resizeStorage(n);
290 static if (is(T == struct) && (hasElaborateAssign!T || hasElaborateDestructor!T))
291 {
292 foreach (ref target; toFill)
293 copyEmplace(value, target);
294 }
295 else
296 toFill[] = value;
297 }
298
299 // Resizes storage only, and returns slice of new memory to fill.
300 private ContainerStorageType!T[] resizeStorage(size_t n)
301 {
302 ContainerStorageType!T[] toFill = null;
303
304 if (arr.length < n)
305 reserve(n);
306
307 if (l < n) // Growing?
308 {
309 toFill = arr[l..n];
310 }
311 else
312 {
313 static if ((is(T == struct) || is(T == union))
314 && __traits(hasMember, T, "__xdtor"))
315 {
316 foreach (i; n..l)
317 arr[i].__xdtor();
318 }
319 }
320
321 l = n;
322 return toFill;
323 }
324
325 /**
326 * Remove the item at the given index from the array.
327 */
328 void remove(const size_t i)
329 {
330 if (i < this.l)
331 {
332 auto next = i + 1;
333 while (next < this.l)
334 {
335 move(arr[next], arr[next - 1]);
336 ++next;
337 }
338
339 --l;
340 static if ((is(T == struct) || is(T == union))
341 && __traits(hasMember, T, "__xdtor"))
342 {
343 arr[l].__xdtor();
344 }
345 }
346 else
347 {
348 import core.exception : RangeError;
349 throw new RangeError("Out of range index used to remove element");
350 }
351 }
352
353 /**
354 * Removes the last element from the array.
355 */
356 void removeBack()
357 {
358 this.remove(this.length - 1);
359 }
360
361 /// Index assignment support
362 void opIndexAssign(T value, size_t i) @nogc
363 {
364 arr[i] = move(*cast(ContainerStorageType!T*)&value);
365 }
366
367 /// Slice assignment support
368 static if (isCopyable!T)
369 void opSliceAssign(T value) @nogc
370 {
371 arr[0 .. l] = value;
372 }
373
374 /// ditto
375 static if (isCopyable!T)
376 void opSliceAssign(T value, size_t i, size_t j) @nogc
377 {
378 arr[i .. j] = value;
379 }
380
381 /// Returns: the number of items in the array
382 size_t length() const nothrow pure @property @safe @nogc { return l; }
383
384 /// Ditto
385 alias opDollar = length;
386
387 /// Returns: whether or not the DynamicArray is empty.
388 bool empty() const nothrow pure @property @safe @nogc { return l == 0; }
389
390 /**
391 * Returns: a slice to the underlying array.
392 *
393 * As the memory of the array may be freed, access to this array is
394 * highly unsafe.
395 */
396 auto ptr(this This)() @nogc @property
397 {
398 alias ET = ContainerElementType!(This, T);
399 return cast(ET*) arr.ptr;
400 }
401
402 /// Returns: the front element of the DynamicArray.
403 auto ref T front() pure @property
404 {
405 return arr[0];
406 }
407
408 /// Returns: the back element of the DynamicArray.
409 auto ref T back() pure @property
410 {
411 return arr[l - 1];
412 }
413
414 private:
415
416 import containers.internal.storage_type : ContainerStorageType;
417 import containers.internal.element_type : ContainerElementType;
418 import containers.internal.mixins : AllocatorState;
419
420 enum bool useGC = supportGC && shouldAddGCRange!T;
421 mixin AllocatorState!Allocator;
422 ContainerStorageType!(T)[] arr;
423 size_t l;
424 }
425
426 version(emsi_containers_unittest) unittest
427 {
428 import std.algorithm : equal;
429 import std.range : iota;
430 DynamicArray!int ints;
431 assert(ints.empty);
432 foreach (i; 0 .. 100)
433 {
434 ints.insert(i);
435 assert(ints.front == 0);
436 assert(ints.back == i);
437 }
438
439 assert (equal(ints[], iota(100)));
440 assert (ints.length == 100);
441 ints[0] = 100;
442 assert (ints[0] == 100);
443 ints[0 .. 5] = 20;
444 foreach (i; ints[0 .. 5])
445 assert (i == 20);
446 ints[] = 432;
447 foreach (i; ints[])
448 assert (i == 432);
449
450 auto arr = ints.ptr;
451 arr[0] = 1337;
452 assert(arr[0] == 1337);
453 assert(ints[0] == 1337);
454 }
455
456 version(emsi_containers_unittest)
457 {
458 class Cls
459 {
460 int* a;
461
462 this(int* a)
463 {
464 this.a = a;
465 }
466
467 ~this()
468 {
469 ++(*a);
470 }
471 }
472 }
473
474 version(emsi_containers_unittest) unittest
475 {
476 int* a = new int;
477 {
478 DynamicArray!(Cls) arr;
479 arr.insert(new Cls(a));
480 }
481 assert(*a == 0); // Destructor not called.
482 }
483
484 version(emsi_containers_unittest) unittest
485 {
486 import std.exception : assertThrown;
487 import core.exception : RangeError;
488 DynamicArray!int empty;
489 assertThrown!RangeError(empty.remove(1337));
490 assert(empty.length == 0);
491
492 DynamicArray!int one;
493 one.insert(0);
494 assert(one.length == 1);
495 assertThrown!RangeError(one.remove(1337));
496 assert(one.length == 1);
497 one.remove(0);
498 assert(one.length == 0);
499
500 DynamicArray!int two;
501 two.insert(0);
502 two.insert(1);
503 assert(two.length == 2);
504 assertThrown!RangeError(two.remove(1337));
505 assert(two.length == 2);
506 two.remove(0);
507 assert(two.length == 1);
508 assert(two[0] == 1);
509 two.remove(0);
510 assert(two.length == 0);
511
512 two.insert(0);
513 two.insert(1);
514 assert(two.length == 2);
515
516 two.remove(1);
517 assert(two.length == 1);
518 assert(two[0] == 0);
519 assertThrown!RangeError(two.remove(1));
520 assert(two.length == 1);
521 assert(two[0] == 0);
522 two.remove(0);
523 assert(two.length == 0);
524 }
525
526 version(emsi_containers_unittest) unittest
527 {
528 int* a = new int;
529 DynamicArray!(Cls, Mallocator, true) arr;
530 arr.insert(new Cls(a));
531
532 arr.remove(0);
533 assert(*a == 0); // Destructor not called.
534 }
535
536 version(emsi_containers_unittest) unittest
537 {
538 DynamicArray!(int*, Mallocator, true) arr;
539
540 foreach (i; 0 .. 4)
541 arr.insert(new int(i));
542
543 assert (arr.length == 4);
544
545 int*[] slice = arr[1 .. $ - 1];
546 assert (slice.length == 2);
547 assert (*slice[0] == 1);
548 assert (*slice[1] == 2);
549 }
550
551 version(emsi_containers_unittest) unittest
552 {
553 import std.format : format;
554
555 DynamicArray!int arr;
556 foreach (int i; 0 .. 10)
557 arr ~= i;
558 assert(arr.length == 10, "arr.length = %d".format(arr.length));
559
560 auto arr2 = arr ~ arr;
561 assert(arr2.length == 20);
562 auto arr3 = arr2 ~ [100, 99, 98];
563 assert(arr3.length == 23);
564
565 while(!arr3.empty)
566 arr3.removeBack();
567 assert(arr3.empty);
568
569 }
570
571 version(emsi_containers_unittest) @system unittest
572 {
573 DynamicArray!int a;
574 a.reserve(1000);
575 assert(a.length == 0);
576 assert(a.empty);
577 assert(a.arr.length >= 1000);
578 int* p = a[].ptr;
579 foreach (i; 0 .. 1000)
580 {
581 a.insert(i);
582 }
583 assert(p is a[].ptr);
584 }
585
586 version(emsi_containers_unittest) unittest
587 {
588 // Ensure that Array.insert doesn't call the destructor for
589 // a struct whose state is uninitialized memory.
590 static struct S
591 {
592 int* a;
593 ~this() @nogc nothrow
594 {
595 if (a !is null)
596 ++(*a);
597 }
598 }
599 int* a = new int;
600 {
601 DynamicArray!S arr;
602 // This next line may segfault if destructors are called
603 // on structs in invalid states.
604 arr.insert(S(a));
605 }
606 assert(*a == 1);
607 }
608
609 version(emsi_containers_unittest) @nogc unittest
610 {
611 struct HStorage
612 {
613 import containers.dynamicarray: DynamicArray;
614 DynamicArray!int storage;
615 }
616 auto hs = HStorage();
617 }
618
619 version(emsi_containers_unittest) @nogc unittest
620 {
621 DynamicArray!char a;
622 const DynamicArray!char b = a ~ "def";
623 a ~= "abc";
624 a ~= b;
625 assert(a[] == "abcdef");
626 a ~= a;
627 assert(a[] == "abcdefabcdef");
628 }
629
630 version(emsi_containers_unittest) unittest
631 {
632 enum initialValue = 0x69FF5705DAD1AB6CUL;
633 enum payloadValue = 0x495343303356D18CUL;
634
635 static struct S
636 {
637 ulong value = initialValue;
638 @nogc:
639 @disable this();
640 this(ulong value) { this.value = value; }
641 ~this() { assert(value == initialValue || value == payloadValue); }
642 }
643
644 auto s = S(payloadValue);
645
646 DynamicArray!S arr;
647 arr.insertBack(s);
648 arr ~= [s];
649 }
650
651 version(emsi_containers_unittest) @nogc unittest
652 {
653 DynamicArray!int a;
654 a.resize(5, 42);
655 assert(a.length == 5);
656 assert(a[2] == 42);
657 a.resize(3, 17);
658 assert(a.length == 3);
659 assert(a[2] == 42);
660
661 struct Counter
662 {
663 @nogc:
664 static int count;
665 @disable this();
666 this(int) { count++; }
667 this(this) { count++; }
668 ~this() { count--; }
669 }
670
671 DynamicArray!Counter b;
672 assert(Counter.count == 0);
673 static assert(!is(typeof(b.resize(5))));
674 b.resize(5, Counter(0));
675 assert(Counter.count == 5);
676 b.resize(3, Counter(0));
677 assert(Counter.count == 3);
678 }
679
680 version(emsi_containers_unittest) @nogc unittest
681 {
682 struct S { int i = 42; @disable this(this); }
683 DynamicArray!S a;
684 a.resize(1);
685 assert(a[0].i == 42);
686 }
687
688 version(emsi_containers_unittest) unittest
689 {
690 import std.experimental.allocator.building_blocks.region : Region;
691 auto region = Region!Mallocator(1024);
692
693 auto arr = DynamicArray!(int, Region!(Mallocator)*, true)(&region);
694 // reserve and insert back call the common form of reallocate
695 arr.reserve(10);
696 arr.insertBack(1);
697 assert(arr[0] == 1);
698 }