Skip to content

Commit e2b834e

Browse files
committed
Add slice example & rationale; mention assumeSafeAppend
1 parent 2d540ca commit e2b834e

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

spec/arrays.dd

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -763,14 +763,32 @@ $(H3 $(LNAME2 capacity-reserve, `capacity` and `reserve`))
763763
GC-allocated memory, the capacity will be zero.
764764
The spare capacity for an array *a* is `a.capacity - a.length`.)
765765

766+
$(P By default, `capacity` will be zero if an element has been stored after the slice.)
767+
768+
$(SPEC_RUNNABLE_EXAMPLE_RUN
769+
---
770+
int[] a;
771+
assert(a.capacity == 0);
772+
a.length = 3; // may allocate spare capacity too
773+
assert(a.capacity >= 3);
774+
auto b = a[1..3];
775+
assert(b.capacity >= 2); // either a or b can append into any spare capacity
776+
b = a[0..2];
777+
assert(b.capacity == 0);
778+
---
779+
)
780+
781+
$(RATIONALE This behaviour helps prevent accidental overwriting of
782+
elements in another slice. It is also necessary to protect immutable
783+
elements from being overwritten.)
784+
766785
$(P The $(D reserve)
767786
function expands an array's capacity for use by the
768787
$(RELATIVE_LINK2 array-appending, append operator) or `.length` assignment.)
769788

770789
$(SPEC_RUNNABLE_EXAMPLE_RUN
771790
---------
772791
int[] array;
773-
assert(array.capacity == 0);
774792
const size_t cap = array.reserve(10); // request
775793
assert(cap >= 10); // allocated may be more than request
776794
assert(array.ptr != null);
@@ -791,21 +809,24 @@ assert(copy.ptr != array.ptr);
791809
is the address of `array[0]`. So `copy.capacity` will be zero to
792810
prevent any appending to `copy` from overwriting elements in `array`.)
793811

794-
$(NOTE The runtime uses the number of elements appended to track the
812+
$(NOTE The runtime uses the number of appended elements to track the
795813
start of the spare capacity for the memory allocation.)
796814

797815
$(P When an array with spare capacity has its length reduced, or is
798816
assigned a slice of itself that ends before the previous last element,
799817
the capacity will be zero.)
800818

819+
$(P The `@system` function $(REF1 assumeSafeAppend, object) allows the
820+
capacity to be regained, but care must be taken not to overwrite
821+
immutable elements that may exist in a longer slice.)
822+
801823
$(SPEC_RUNNABLE_EXAMPLE_RUN
802824
---
803825
int[] a = [1, 2, 3];
804-
a.reserve(2);
805-
a = a[];
806-
assert(a.capacity > 0);
807-
a = a[0..2];
826+
a.length--;
808827
assert(a.capacity == 0);
828+
a.assumeSafeAppend();
829+
assert(a.capacity >= 3);
809830
---
810831
)
811832

0 commit comments

Comments
 (0)