diff --git a/include/gridtools/storage/adapter/nanobind_adapter.hpp b/include/gridtools/storage/adapter/nanobind_adapter.hpp index 4ce1a9fe3..c05296ca8 100644 --- a/include/gridtools/storage/adapter/nanobind_adapter.hpp +++ b/include/gridtools/storage/adapter/nanobind_adapter.hpp @@ -10,6 +10,7 @@ #pragma once #include +#include #include #include @@ -53,10 +54,12 @@ namespace gridtools { if constexpr (SpecValue == dynamic_size) { return dyn_value; } else { - if (SpecValue != dyn_value) { + if (static_cast(SpecValue) != dyn_value) { throw std::invalid_argument("static stride in stride specification doesn't match dynamic stride"); } - return gridtools::integral_constant{}; + // A signed type is needed: with an unsigned static stride, a compile-time shift + // by a negative offset overflows and no `sid::shift` overload is viable. + return gridtools::integral_constant{}; } } diff --git a/tests/unit_tests/storage/adapter/test_nanobind_adapter.cpp b/tests/unit_tests/storage/adapter/test_nanobind_adapter.cpp index 786d178b4..7e6067572 100644 --- a/tests/unit_tests/storage/adapter/test_nanobind_adapter.cpp +++ b/tests/unit_tests/storage/adapter/test_nanobind_adapter.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -76,6 +77,23 @@ TEST_F(python_init_fixture, NanobindAdapterStaticStridesMatch) { EXPECT_EQ(strides[1], gridtools::get<1>(s_strides)); } +TEST_F(python_init_fixture, NanobindAdapterStaticStridesNegativeShift) { + int data[12] = {}; + constexpr int ndim = 2; + constexpr std::array shape = {3, 4}; + constexpr std::array strides = {1, 3}; + nb::ndarray> ndarray{data, ndim, shape.data(), nb::handle{}, strides.data()}; + + const auto sid = gridtools::nanobind::as_sid(ndarray, gridtools::nanobind::stride_spec<1, -1>{}); + const auto stride = gridtools::get<0>(sid_get_strides(sid)); + static_assert(std::is_signed_v); + + // static stride and static negative offset: the shift is computed at compile time + auto ptr = sid_get_origin(sid)() + 2; + gridtools::sid::shift(ptr, stride, gridtools::integral_constant()); + EXPECT_EQ(ptr, data + 1); +} + TEST_F(python_init_fixture, NanobindAdapterStaticStridesMismatch) { const auto data = reinterpret_cast(0xDEADBEEF); constexpr int ndim = 2;