Skip to content
Open
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
7 changes: 5 additions & 2 deletions include/gridtools/storage/adapter/nanobind_adapter.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#pragma once

#include <algorithm>
#include <cstddef>
#include <stdexcept>

#include <nanobind/nanobind.h>
Expand Down Expand Up @@ -53,10 +54,12 @@ namespace gridtools {
if constexpr (SpecValue == dynamic_size) {
return dyn_value;
} else {
if (SpecValue != dyn_value) {
if (static_cast<std::size_t>(SpecValue) != dyn_value) {
throw std::invalid_argument("static stride in stride specification doesn't match dynamic stride");
}
return gridtools::integral_constant<std::size_t, SpecValue>{};
// 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<std::ptrdiff_t, SpecValue>{};

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see above you defined array_size_t. Should I define a type like below?

#if NB_VERSION_MAJOR >= 2
        using array_stride_t = nanobind::ssize_t;
#else
        using array_stride_t = std::ptrdiff_t;
#endif

}
}

Expand Down
18 changes: 18 additions & 0 deletions tests/unit_tests/storage/adapter/test_nanobind_adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include <Python.h>
#include <array>
#include <type_traits>
#include <gridtools/common/integral_constant.hpp>
#include <gridtools/sid/concept.hpp>

Expand Down Expand Up @@ -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<std::size_t, ndim> shape = {3, 4};
constexpr std::array<std::intptr_t, ndim> strides = {1, 3};
nb::ndarray<int, nb::shape<-1, -1>> 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<typename decltype(stride)::value_type>);

// 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<int, -1>());
EXPECT_EQ(ptr, data + 1);
}

TEST_F(python_init_fixture, NanobindAdapterStaticStridesMismatch) {
const auto data = reinterpret_cast<void *>(0xDEADBEEF);
constexpr int ndim = 2;
Expand Down
Loading