File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed
Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change 22// Use of this source code is governed by a BSD 3-Clause
33// license that can be found in the LICENSE file.
44
5+ use "std/runtime"
6+
57// Reports whether slices are the same length and contains same elements.
68// The nil slices considered as zero-length slices.
79// The floating-point NaNs are not considered equal.
@@ -75,4 +77,20 @@ fn Reverse[S: ~[]E, E](mut s: S) {
7577 for i < j; i, j = i+1, j-1 {
7678 s[i], s[j] = s[j], s[i]
7779 }
80+ }
81+
82+ // Increases the slice's capacity, if necessary, to guarantee space for
83+ // another n elements. After Grow(n), at least n elements can be appended
84+ // to the slice without another allocation. If n is negative or too large to
85+ // allocate the memory, Grow panics.
86+ fn Grow[S: ~[]E, E](mut s: S, mut n: int): S {
87+ if n < 0 {
88+ panic("cannot be negative")
89+ }
90+ n -= cap(s) - len(s)
91+ if n > 0 {
92+ // Use runtime implementation to grow properly like `append` calls.
93+ runtime::prememappend(&s, n)
94+ }
95+ ret s
7896}
Original file line number Diff line number Diff line change @@ -96,4 +96,13 @@ fn testReverse(t: &testing::T) {
9696 rs3 := [2, 1]
9797 Reverse(s3)
9898 t.Assert(Equal(s3, rs3), "s3 != rs3")
99+ }
100+
101+ #test
102+ fn testGrow(t: &testing::T) {
103+ mut buf := make([]byte, 128)
104+ appendTest := append(buf, make([]byte, 1024)...)
105+ buf = Grow(buf, 1024)
106+ t.Assert(cap(buf) == cap(appendTest), "cap(buf) != cap(appendtest)")
107+ t.Assert(cap(buf) >= 128+1024, "cap(buf) < 128+1024")
99108}
You can’t perform that action at this time.
0 commit comments