Skip to content

Commit d7c72c5

Browse files
committed
std/slices: add Grow
1 parent 7905650 commit d7c72c5

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

std/slices/slices.jule

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
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
}

std/slices/slices_test.jule

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)