gemini-code-assist[bot] commented on code in PR #375:
URL: https://github.com/apache/tvm-ffi/pull/375#discussion_r2656440448
##########
include/tvm/ffi/container/tensor.h:
##########
@@ -325,7 +325,12 @@ class Tensor : public ObjectRef {
*/
int64_t size(int64_t idx) const {
const TensorObj* ptr = get();
- return ptr->shape[idx >= 0 ? idx : (ptr->ndim + idx)];
+ int64_t adjusted_idx = idx >= 0 ? idx : (ptr->ndim + idx);
+ if (adjusted_idx < 0 || adjusted_idx >= ptr->ndim) {
+ TVM_FFI_THROW(IndexError) << "Index " << idx << " out of bounds for
tensor with " << ptr->ndim
+ << " dimensions";
+ }
+ return ptr->shape[adjusted_idx];
}
Review Comment:

The index adjustment and bounds checking logic is duplicated in
`Tensor::size`, `Tensor::stride`, `TensorView::size`, and `TensorView::stride`.
To improve maintainability and reduce code duplication, consider extracting
this logic into a common helper function.
For example, you could add a free helper function in a `details` namespace:
```cpp
namespace tvm {
namespace ffi {
namespace details {
inline int64_t CheckAndAdjustTensorIndex(int64_t idx, int32_t ndim) {
int64_t adjusted_idx = idx >= 0 ? idx : (ndim + idx);
if (adjusted_idx < 0 || adjusted_idx >= ndim) {
TVM_FFI_THROW(IndexError) << "Index " << idx << " out of bounds for
tensor with " << ndim
<< " dimensions";
}
return adjusted_idx;
}
} // namespace details
} // namespace ffi
} // namespace tvm
```
Then `Tensor::size` and `TensorView::size` could be simplified to:
```cpp
// Tensor::size
int64_t size(int64_t idx) const {
const TensorObj* ptr = get();
return ptr->shape[details::CheckAndAdjustTensorIndex(idx, ptr->ndim)];
}
// TensorView::size
int64_t size(int64_t idx) const {
return tensor_.shape[details::CheckAndAdjustTensorIndex(idx,
tensor_.ndim)];
}
```
A similar simplification would apply to the `stride` methods.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]