@@ -267,6 +267,51 @@ struct DynamicArray(T, Allocator = Mallocator, bool supportGC = shouldAddGCRange
267267 }
268268 }
269269
270+ static if (is (typeof ({T value;}))) // default construction is allowed
271+ {
272+ /**
273+ * Change the array length.
274+ * When growing, initialize new elements to the default value.
275+ */
276+ void resize (size_t n)
277+ {
278+ resize(n, T.init);
279+ }
280+ }
281+
282+ /**
283+ * Change the array length.
284+ * When growing, initialize new elements to the given value.
285+ */
286+ void resize (size_t n, T value)
287+ {
288+ if (arr.length < n)
289+ reserve (n);
290+
291+ if (l < n) // Growing?
292+ {
293+ import std.traits : hasElaborateAssign, hasElaborateDestructor;
294+ static if (is (T == struct ) && (hasElaborateAssign! T || hasElaborateDestructor! T))
295+ {
296+ foreach (i; l.. n)
297+ emplace(arr[l], value);
298+ }
299+ else
300+ arr[l.. n] = value;
301+ }
302+ else
303+ {
304+ static if ((is (T == struct ) || is (T == union ))
305+ && __traits(hasMember, T, " __xdtor" ))
306+ {
307+ foreach (i; n.. l)
308+ arr[i].__xdtor();
309+ }
310+ }
311+
312+ l = n;
313+ }
314+
270315 /**
271316 * Remove the item at the given index from the array.
272317 */
@@ -592,3 +637,32 @@ version(emsi_containers_unittest) unittest
592637 arr.insertBack(s);
593638 arr ~= [s];
594639}
640+
641+ version (emsi_containers_unittest) @nogc unittest
642+ {
643+ DynamicArray! int a;
644+ a.resize(5 , 42 );
645+ assert (a.length == 5 );
646+ assert (a[2 ] == 42 );
647+ a.resize(3 , 17 );
648+ assert (a.length == 3 );
649+ assert (a[2 ] == 42 );
650+
651+ struct Counter
652+ {
653+ @nogc :
654+ static int count;
655+ @disable this ();
656+ this (int ) { count++ ; }
657+ this (this ) { count++ ; }
658+ ~this () { count-- ; }
659+ }
660+
661+ DynamicArray! Counter b;
662+ assert (Counter.count == 0 );
663+ static assert (! is (typeof (b.resize(5 ))));
664+ b.resize(5 , Counter (0 ));
665+ assert (Counter.count == 5 );
666+ b.resize(3 , Counter (0 ));
667+ assert (Counter.count == 3 );
668+ }
0 commit comments