Skip to content

Commit

Permalink
Handle Array.with_capacity with negative sizes
Browse files Browse the repository at this point in the history
This adds an explicit check in Array.with_capacity to disallow negative
sizes, instead of relying on the raw allocation failing.

Changelog: fixed
  • Loading branch information
yorickpeterse committed Jul 29, 2023
1 parent 00dd2fd commit 59f65dd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 9 additions & 3 deletions std/src/std/array.inko
Expand Up @@ -117,11 +117,17 @@ class builtin Array[T] {
# Returns a new `Array` with enough space for at least `amount` values.
#
# The actual capacity may be greater than the given value.
fn pub static with_capacity(amount: Int) -> Array[T] {
#
# # Panics
#
# This method panics of `size` if less than zero.
fn pub static with_capacity(size: Int) -> Array[T] {
if size < 0 { panic('The capacity must be greater than or equal to zero') }

let buffer = alloc_imp
.resize(0x0 as Pointer[UInt8], size: amount * VALUE_SIZE)
.resize(0x0 as Pointer[UInt8], size: size * VALUE_SIZE)

Array { @size = 0, @capacity = amount, @buffer = buffer }
Array { @size = 0, @capacity = size, @buffer = buffer }
}

# Returns an array filled with a certain amount of values.
Expand Down
4 changes: 4 additions & 0 deletions std/test/std/test_array.inko
Expand Up @@ -46,6 +46,10 @@ fn pub tests(t: mut Tests) {
t.equal(ary2.capacity, 2)
}

t.panic('Array.with_capacity with an invalid size') fn {
Array.with_capacity(-4) as Array[Int]
}

t.test('Array.filled') fn (t) {
t.equal(Array.filled(with: 1, times: 0), [])
t.equal(Array.filled(with: 1, times: 1), [1])
Expand Down

0 comments on commit 59f65dd

Please sign in to comment.