@@ -417,6 +417,10 @@ class DynamicArrayBase<ProvableValue = any, Value = any> {
417417 * Shifts all elements of the array to the right by n positions, increasing
418418 * the length by n, which must result in less than or equal to the capacity.
419419 * The new elements on the left are set to NULL values.
420+ *
421+ * **Warning**: This does not extend the capacity of the array, so if the
422+ * array cannot be extended with `n` elements, it will fail. Consider copying
423+ * the array into a new one that has larger capacity first.
420424 *
421425 * @param n
422426 */
@@ -436,13 +440,25 @@ class DynamicArrayBase<ProvableValue = any, Value = any> {
436440 }
437441
438442 /**
439- * @returns a new DynamicArray instance with the same values as the current
443+ * Copies the current dynamic array, returning a new instance with the same
444+ * values and length. Optionally, one can specify a different `capacity` to
445+ * set the new array's capacity. If it is larger than the current capacity,
446+ * the copy can be done without failing. If it is smaller, the current length
447+ * must be less than or equal to the new capacity.
448+ *
449+ * @returns a new DynamicArray instance with the same values as the current.
450+ *
440451 */
441- copy ( ) : this {
442- let newArr = new ( < any > this . constructor ) ( ) ;
443- newArr . array = this . array . slice ( ) ;
444- newArr . length = this . length ;
445- return newArr ;
452+ copy ( capacity ?: number ) : DynamicArray < ProvableValue , Value > {
453+ const newCapacity = capacity ?? this . capacity ;
454+
455+ if ( newCapacity < this . capacity ) {
456+ this . length . assertLessThanOrEqual ( new Field ( newCapacity ) ) ;
457+ }
458+
459+ const CopiedArray = DynamicArray ( this . innerType , { capacity : newCapacity } ) ;
460+
461+ return new CopiedArray ( this . array , this . length ) ;
446462 }
447463
448464 /**
0 commit comments