Fix negative dim indexing (#2994)

Co-authored-by: KD2YCU <me@kd2ycu.com>
Co-authored-by: Awni Hannun <awni@apple.com>
This commit is contained in:
Dan Anderson
2026-01-20 09:24:33 -05:00
committed by GitHub
parent 65b42c8476
commit 83bb7891db
2 changed files with 30 additions and 2 deletions
+28
View File
@@ -1,5 +1,8 @@
// Copyright © 2023 Apple Inc.
#include <cassert>
#include <climits>
#include <stdexcept>
#include <vector>
#include "doctest/doctest.h"
@@ -633,3 +636,28 @@ TEST_CASE("test make array from user buffer") {
// deleter should always get called
CHECK_EQ(count, 1);
}
TEST_CASE("test negative indexing for shape/strides") {
// 2D array: shape = {2, 3}
std::vector<float> data(6, 1.0f);
array a(data.begin(), Shape{2, 3});
// Valid negative indexing
CHECK_EQ(a.shape(-1), a.shape(1));
CHECK_EQ(a.shape(-2), a.shape(0));
CHECK_EQ(a.shape(-1), 3);
CHECK_EQ(a.shape(-2), 2);
CHECK_EQ(a.strides(-1), a.strides(1));
CHECK_EQ(a.strides(-2), a.strides(0));
CHECK_EQ(a.strides(-1), 1);
CHECK_EQ(a.strides(-2), 3);
// Invalid: too negative
CHECK_THROWS_AS(a.shape(-3), std::out_of_range);
CHECK_THROWS_AS(a.strides(-3), std::out_of_range);
// Invalid: too positive
CHECK_THROWS_AS(a.shape(2), std::out_of_range);
CHECK_THROWS_AS(a.strides(2), std::out_of_range);
}