Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions include/tvm/ffi/container/array.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class ArrayObj : public Object, public details::InplaceArrayBase<ArrayObj, TVMFF
* \return the i-th element.
*/
const Any& operator[](int64_t i) const {
if (i >= size_) {
if (i < 0 || i >= size_) {
TVM_FFI_THROW(IndexError) << "Index " << i << " out of bounds " << size_;
}
return static_cast<Any*>(data_)[i];
Expand All @@ -91,7 +91,7 @@ class ArrayObj : public Object, public details::InplaceArrayBase<ArrayObj, TVMFF
* \param item The value to be set
*/
void SetItem(int64_t i, Any item) {
if (i >= size_) {
if (i < 0 || i >= size_) {
TVM_FFI_THROW(IndexError) << "Index " << i << " out of bounds " << size_;
}
static_cast<Any*>(data_)[i] = std::move(item);
Expand Down
31 changes: 31 additions & 0 deletions tests/cpp/test_array.cc
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,35 @@ TEST(Array, Contains) {
EXPECT_FALSE(f(str_arr, String("foo")).cast<bool>());
}

TEST(Array, NegativeIndexThrows) {
Array<int> arr = {1, 2, 3};
// Directly test ArrayObj methods, which are the ones modified in this PR.
// The Array<T> wrapper methods already had negative index checks.
ArrayObj* arr_obj = arr.GetArrayObj();

// Test ArrayObj::at (which calls operator[])
EXPECT_THROW(
{
try {
[[maybe_unused]] const auto& val = arr_obj->at(-1);
} catch (const Error& error) {
EXPECT_EQ(error.kind(), "IndexError");
throw;
}
},
::tvm::ffi::Error);

// Test ArrayObj::SetItem
EXPECT_THROW(
{
try {
arr_obj->SetItem(-1, Any(42));
} catch (const Error& error) {
EXPECT_EQ(error.kind(), "IndexError");
throw;
}
},
::tvm::ffi::Error);
}

} // namespace