Skip to content

Commit 987f783

Browse files
committed
Handle invalid indexes in ByteArray.copy_from
ByteArray.copy_from didn't check if the `at` argument was out of bounds or not, resulting in a Rust/runtime panic when using such an index. Changelog: fixed
1 parent d4b4fd1 commit 987f783

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

std/src/std/byte_array.inko

+5
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,10 @@ type builtin ByteArray {
451451
# The return value is the number of bytes copied. This value may be less than
452452
# `size` if there are fewer bytes in `bytes`.
453453
#
454+
# # Panics
455+
#
456+
# This method panics if `at` is out of bounds.
457+
#
454458
# # Examples
455459
#
456460
# ```inko
@@ -462,6 +466,7 @@ type builtin ByteArray {
462466
# b # => ByteArray.from_array([1, 2])
463467
# ```
464468
fn pub mut copy_from(bytes: ref ByteArray, at: Int, size: Int) -> Int {
469+
bounds_check(at, bytes.size)
465470
inko_byte_array_copy_from(self, bytes.to_pointer, bytes.size, at, size)
466471
}
467472

std/test/std/test_byte_array.inko

+18
Original file line numberDiff line numberDiff line change
@@ -349,13 +349,31 @@ fn pub tests(t: mut Tests) {
349349
t.test('ByteArray.copy_from', fn (t) {
350350
let a = ByteArray.from_array([1, 2, 3, 4])
351351
let b = ByteArray.new
352+
let c = ByteArray.new
352353

353354
t.equal(b.copy_from(a, at: 0, size: 2), 2)
354355
t.equal(a, ByteArray.from_array([1, 2, 3, 4]))
355356
t.equal(b, ByteArray.from_array([1, 2]))
356357

357358
t.equal(b.copy_from(b, at: 0, size: 2), 2)
358359
t.equal(b, ByteArray.from_array([1, 2, 1, 2]))
360+
361+
t.equal(c.copy_from(a, at: 3, size: 1), 1)
362+
t.equal(c, ByteArray.from_array([4]))
363+
})
364+
365+
t.panic('ByteArray.copy_from with an index that is too great', fn {
366+
let a = ByteArray.from_array([1, 2, 3, 4])
367+
let b = ByteArray.new
368+
369+
b.copy_from(a, at: 10, size: 2)
370+
})
371+
372+
t.panic('ByteArray.copy_from with an index that is too small', fn {
373+
let a = ByteArray.from_array([1, 2, 3, 4])
374+
let b = ByteArray.new
375+
376+
b.copy_from(a, at: -3, size: 2)
359377
})
360378

361379
t.test('ByteArray.resize', fn (t) {

0 commit comments

Comments
 (0)