Skip to content

Commit c1695d0

Browse files
authored
fix(stdlib): Remove intermediate resizes in Buffer.autogrow (#1125)
1 parent 3d7fc57 commit c1695d0

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

stdlib/buffer.gr

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,24 @@ let getSize = ptr => WasmI32.load(ptr, _SIZE_OFFSET)
4949

5050
/* Doubles the size of buffer's underlying byte sequence, if the given size is larger than the size of a buffer's underlying byte sequence */
5151
let autogrow = (len, buf) => {
52-
while (buf.len + len > Bytes.length(buf.data)) {
53-
let mut n = Bytes.length(buf.data)
54-
if (n == 0) n = 4
55-
// Make sure bytes of 0 length grow too
56-
buf.data = Bytes.resize(0, n, buf.data)
52+
let requiredMinimumSize = buf.len + len
53+
let currentSize = Bytes.length(buf.data)
54+
55+
if (requiredMinimumSize > currentSize) {
56+
let mut newSize = if (currentSize > 0) {
57+
currentSize
58+
} else {
59+
// Make sure bytes of 0 length grow too
60+
4
61+
}
62+
63+
while (newSize < requiredMinimumSize) {
64+
newSize *= 2
65+
}
66+
67+
let growBy = newSize - currentSize
68+
69+
buf.data = Bytes.resize(0, growBy, buf.data)
5770
}
5871
}
5972

0 commit comments

Comments
 (0)