Skip to content

Commit

Permalink
ignore duplicate bind_vector/bind_map declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
wjakob committed Jun 3, 2023
1 parent f3b0e6c commit 2c9124b
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/api_extra.rst
Expand Up @@ -243,6 +243,9 @@ include directive:
not comparable or copy-assignable, some of these functions will not be
generated.

The binding operation is a no-op if the vector type has already been
registered with nanobind.

.. _map_bindings:

STL map bindings
Expand Down Expand Up @@ -308,6 +311,9 @@ nanobind API and require an additional include directive:
* - ``items(self, arg: Map) -> Map.ItemView``
- Returns an iterable view of the map's items

The binding operation is a no-op if the map type has already been
registered with nanobind.

Unique pointer deleter
----------------------

Expand Down
6 changes: 6 additions & 0 deletions include/nanobind/stl/bind_map.h
Expand Up @@ -42,6 +42,12 @@ class_<Map> bind_map(handle scope, const char *name, Args &&...args) {
using Key = typename Map::key_type;
using Value = typename Map::mapped_type;

handle cl_cur = type<Map>();
if (cl_cur.is_valid()) {
// Binding already exists, don't re-create
return borrow<class_<Map>>(cl_cur);
}

auto cl = class_<Map>(scope, name, std::forward<Args>(args)...)
.def(init<>(),
"Default constructor")
Expand Down
6 changes: 6 additions & 0 deletions include/nanobind/stl/bind_vector.h
Expand Up @@ -48,6 +48,12 @@ class_<Vector> bind_vector(handle scope, const char *name, Args &&...args) {
using ValueRef = typename detail::iterator_access<typename Vector::iterator>::result_type;
using Value = std::decay_t<ValueRef>;

handle cl_cur = type<Vector>();
if (cl_cur.is_valid()) {
// Binding already exists, don't re-create
return borrow<class_<Vector>>(cl_cur);
}

auto cl = class_<Vector>(scope, name, std::forward<Args>(args)...)
.def(init<>(), "Default constructor")

Expand Down
3 changes: 3 additions & 0 deletions tests/test_stl_bind_vector.cpp
Expand Up @@ -8,6 +8,9 @@ NB_MODULE(test_bind_vector_ext, m) {
nb::bind_vector<std::vector<unsigned int>>(m, "VectorInt");
nb::bind_vector<std::vector<bool>>(m, "VectorBool");

// Ensure that a repeated binding call is ignored
nb::bind_vector<std::vector<bool>>(m, "VectorBool");

struct El {
explicit El(int v) : a(v) {}
int a;
Expand Down

0 comments on commit 2c9124b

Please sign in to comment.