μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_stl.cpp
Go to the documentation of this file.
1/*
2 tests/test_stl.cpp -- STL type casters
3
4 Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#include <pybind11/stl.h>
11
12#include "constructor_stats.h"
13#include "pybind11_tests.h"
14
15#ifndef PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL
16# define PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL
17#endif
18#include <pybind11/stl/filesystem.h>
19
20#include <string>
21#include <vector>
22
23#if defined(PYBIND11_TEST_BOOST)
24# include <boost/optional.hpp>
25
26namespace pybind11 {
27namespace detail {
28template <typename T>
29struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};
30
31template <>
32struct type_caster<boost::none_t> : void_caster<boost::none_t> {};
33} // namespace detail
34} // namespace pybind11
35#endif
36
37// Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14
38#if defined(PYBIND11_HAS_VARIANT)
39using std::variant;
40#elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910)
41# include <boost/variant.hpp>
42# define PYBIND11_HAS_VARIANT 1
43using boost::variant;
44
45namespace pybind11 {
46namespace detail {
47template <typename... Ts>
48struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
49
50template <>
51struct visit_helper<boost::variant> {
52 template <typename... Args>
53 static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
54 return boost::apply_visitor(args...);
55 }
56};
57} // namespace detail
58} // namespace pybind11
59#endif
60
61PYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>);
62
65 template <typename T>
66 explicit TplCtorClass(const T &) {}
67 bool operator==(const TplCtorClass &) const { return true; }
68};
69
70namespace std {
71template <>
73 size_t operator()(const TplCtorClass &) const { return 0; }
74};
75} // namespace std
76
77template <template <typename> class OptionalImpl, typename T>
79 // NOLINTNEXTLINE(modernize-use-equals-default): breaks GCC 4.8
81 bool member_initialized() const { return member && member->initialized; }
82 OptionalImpl<T> member = T{};
83};
84
85enum class EnumType {
86 kSet = 42,
87 kUnset = 85,
88};
89
90// This is used to test that return-by-ref and return-by-copy policies are
91// handled properly for optional types. This is a regression test for a dangling
92// reference issue. The issue seemed to require the enum value type to
93// reproduce - it didn't seem to happen if the value type is just an integer.
94template <template <typename> class OptionalImpl>
96public:
97 using OptionalEnumValue = OptionalImpl<EnumType>;
98
101 // Reset value to detect use-after-destruction.
102 // This is set to a specific value rather than nullopt to ensure that
103 // the memory that contains the value gets re-written.
104 value = EnumType::kUnset;
105 }
106
109
110private:
112};
113
114// This type mimics aspects of boost::optional from old versions of Boost,
115// which exposed a dangling reference bug in Pybind11. Recent versions of
116// boost::optional, as well as libstdc++'s std::optional, don't seem to be
117// affected by the same issue. This is meant to be a minimal implementation
118// required to reproduce the issue, not fully standard-compliant.
119// See issue #3330 for more details.
120template <typename T>
122public:
123 using value_type = T;
124
126 // NOLINTNEXTLINE(google-explicit-constructor)
128 // NOLINTNEXTLINE(google-explicit-constructor)
131 storage = {value};
132 return *this;
133 }
135 storage = {std::move(value)};
136 return *this;
137 }
138
139 template <typename... Args>
140 T &emplace(Args &&...args) {
141 storage.clear();
142 storage.emplace_back(std::forward<Args>(args)...);
143 return storage.back();
144 }
145
146 const T &value() const noexcept {
147 assert(!storage.empty());
148 return storage[0];
149 }
150
151 const T &operator*() const noexcept { return value(); }
152
153 const T *operator->() const noexcept { return &value(); }
154
155 explicit operator bool() const noexcept { return !storage.empty(); }
156
157private:
158 std::vector<T> storage;
159};
160
161namespace pybind11 {
162namespace detail {
163template <typename T>
165 : optional_caster<ReferenceSensitiveOptional<T>> {};
166} // namespace detail
167} // namespace pybind11
168
170 // test_vector
171 m.def("cast_vector", []() { return std::vector<int>{1}; });
172 m.def("load_vector", [](const std::vector<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });
173 // `std::vector<bool>` is special because it returns proxy objects instead of references
174 m.def("cast_bool_vector", []() { return std::vector<bool>{true, false}; });
175 m.def("load_bool_vector",
176 [](const std::vector<bool> &v) { return v.at(0) == true && v.at(1) == false; });
177 // Unnumbered regression (caused by #936): pointers to stl containers aren't castable
178 static std::vector<RValueCaster> lvv{2};
179 m.def("cast_ptr_vector", []() { return &lvv; });
180
181 // test_deque
182 m.def("cast_deque", []() { return std::deque<int>{1}; });
183 m.def("load_deque", [](const std::deque<int> &v) { return v.at(0) == 1 && v.at(1) == 2; });
184
185 // test_array
186 m.def("cast_array", []() { return std::array<int, 2>{{1, 2}}; });
187 m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; });
188
189 // test_valarray
190 m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; });
191 m.def("load_valarray", [](const std::valarray<int> &v) {
192 return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9;
193 });
194
195 // test_map
196 m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; });
197 m.def("load_map", [](const std::map<std::string, std::string> &map) {
198 return map.at("key") == "value" && map.at("key2") == "value2";
199 });
200
201 // test_set
202 m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; });
203 m.def("load_set", [](const std::set<std::string> &set) {
204 return (set.count("key1") != 0u) && (set.count("key2") != 0u) && (set.count("key3") != 0u);
205 });
206
207 // test_recursive_casting
208 m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; });
209 m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); });
210 // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`),
211 // casters don't typically do anything with that, which means they fall to the `const Type &`
212 // caster.
213 m.def("cast_rv_map", []() {
214 return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}};
215 });
216 m.def("cast_rv_nested", []() {
217 std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v;
218 v.emplace_back(); // add an array
219 v.back()[0].emplace_back(); // add a map to the array
220 v.back()[0].back().emplace("b", RValueCaster{});
221 v.back()[0].back().emplace("c", RValueCaster{});
222 v.back()[1].emplace_back(); // add a map to the array
223 v.back()[1].back().emplace("a", RValueCaster{});
224 return v;
225 });
226 static std::array<RValueCaster, 2> lva;
227 static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}},
228 {"b", RValueCaster{}}};
229 static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>>
230 lvn;
231 lvn["a"].emplace_back(); // add a list
232 lvn["a"].back().emplace_back(); // add an array
233 lvn["a"].emplace_back(); // another list
234 lvn["a"].back().emplace_back(); // add an array
235 lvn["b"].emplace_back(); // add a list
236 lvn["b"].back().emplace_back(); // add an array
237 lvn["b"].back().emplace_back(); // add another array
238 m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; });
239 m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; });
240 m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; });
241 m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; });
242 // #853:
243 m.def("cast_unique_ptr_vector", []() {
244 std::vector<std::unique_ptr<UserType>> v;
245 v.emplace_back(new UserType{7});
246 v.emplace_back(new UserType{42});
247 return v;
248 });
249
250 pybind11::enum_<EnumType>(m, "EnumType")
251 .value("kSet", EnumType::kSet)
252 .value("kUnset", EnumType::kUnset);
253
254 // test_move_out_container
255 struct MoveOutContainer {
256 struct Value {
257 int value;
258 };
259 std::list<Value> move_list() const { return {{0}, {1}, {2}}; }
260 };
261 py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue")
262 .def_readonly("value", &MoveOutContainer::Value::value);
263 py::class_<MoveOutContainer>(m, "MoveOutContainer")
264 .def(py::init<>())
265 .def_property_readonly("move_list", &MoveOutContainer::move_list);
266
267 // Class that can be move- and copy-constructed, but not assigned
268 struct NoAssign {
269 int value;
270
271 explicit NoAssign(int value = 0) : value(value) {}
272 NoAssign(const NoAssign &) = default;
273 NoAssign(NoAssign &&) = default;
274
275 NoAssign &operator=(const NoAssign &) = delete;
276 NoAssign &operator=(NoAssign &&) = delete;
277 };
278 py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators")
279 .def(py::init<>())
280 .def(py::init<int>());
281
282 struct MoveOutDetector {
283 MoveOutDetector() = default;
284 MoveOutDetector(const MoveOutDetector &) = default;
285 MoveOutDetector(MoveOutDetector &&other) noexcept : initialized(other.initialized) {
286 // steal underlying resource
287 other.initialized = false;
288 }
289 bool initialized = true;
290 };
291 py::class_<MoveOutDetector>(m, "MoveOutDetector", "Class with move tracking")
292 .def(py::init<>())
293 .def_readonly("initialized", &MoveOutDetector::initialized);
294
295#ifdef PYBIND11_HAS_OPTIONAL
296 // test_optional
297 m.attr("has_optional") = true;
298
299 using opt_int = std::optional<int>;
300 using opt_no_assign = std::optional<NoAssign>;
301 m.def("double_or_zero", [](const opt_int &x) -> int { return x.value_or(0) * 2; });
302 m.def("half_or_none", [](int x) -> opt_int { return x != 0 ? opt_int(x / 2) : opt_int(); });
303 m.def(
304 "test_nullopt",
305 [](opt_int x) { return x.value_or(42); },
306 py::arg_v("x", std::nullopt, "None"));
307 m.def(
308 "test_no_assign",
309 [](const opt_no_assign &x) { return x ? x->value : 42; },
310 py::arg_v("x", std::nullopt, "None"));
311
312 m.def("nodefer_none_optional", [](std::optional<int>) { return true; });
313 m.def("nodefer_none_optional", [](const py::none &) { return false; });
314
316 py::class_<opt_holder>(m, "OptionalHolder", "Class with optional member")
317 .def(py::init<>())
318 .def_readonly("member", &opt_holder::member)
319 .def("member_initialized", &opt_holder::member_initialized);
320
321 using opt_props = OptionalProperties<std::optional>;
322 pybind11::class_<opt_props>(m, "OptionalProperties")
323 .def(pybind11::init<>())
324 .def_property_readonly("access_by_ref", &opt_props::access_by_ref)
325 .def_property_readonly("access_by_copy", &opt_props::access_by_copy);
326#endif
327
328#ifdef PYBIND11_HAS_EXP_OPTIONAL
329 // test_exp_optional
330 m.attr("has_exp_optional") = true;
331
332 using exp_opt_int = std::experimental::optional<int>;
333 using exp_opt_no_assign = std::experimental::optional<NoAssign>;
334 m.def("double_or_zero_exp", [](const exp_opt_int &x) -> int { return x.value_or(0) * 2; });
335 m.def("half_or_none_exp",
336 [](int x) -> exp_opt_int { return x ? exp_opt_int(x / 2) : exp_opt_int(); });
337 m.def(
338 "test_nullopt_exp",
339 [](exp_opt_int x) { return x.value_or(42); },
340 py::arg_v("x", std::experimental::nullopt, "None"));
341 m.def(
342 "test_no_assign_exp",
343 [](const exp_opt_no_assign &x) { return x ? x->value : 42; },
344 py::arg_v("x", std::experimental::nullopt, "None"));
345
347 py::class_<opt_exp_holder>(m, "OptionalExpHolder", "Class with optional member")
348 .def(py::init<>())
349 .def_readonly("member", &opt_exp_holder::member)
350 .def("member_initialized", &opt_exp_holder::member_initialized);
351
353 pybind11::class_<opt_exp_props>(m, "OptionalExpProperties")
354 .def(pybind11::init<>())
355 .def_property_readonly("access_by_ref", &opt_exp_props::access_by_ref)
356 .def_property_readonly("access_by_copy", &opt_exp_props::access_by_copy);
357#endif
358
359#if defined(PYBIND11_TEST_BOOST)
360 // test_boost_optional
361 m.attr("has_boost_optional") = true;
362
363 using boost_opt_int = boost::optional<int>;
364 using boost_opt_no_assign = boost::optional<NoAssign>;
365 m.def("double_or_zero_boost", [](const boost_opt_int &x) -> int { return x.value_or(0) * 2; });
366 m.def("half_or_none_boost",
367 [](int x) -> boost_opt_int { return x != 0 ? boost_opt_int(x / 2) : boost_opt_int(); });
368 m.def(
369 "test_nullopt_boost",
370 [](boost_opt_int x) { return x.value_or(42); },
371 py::arg_v("x", boost::none, "None"));
372 m.def(
373 "test_no_assign_boost",
374 [](const boost_opt_no_assign &x) { return x ? x->value : 42; },
375 py::arg_v("x", boost::none, "None"));
376
378 py::class_<opt_boost_holder>(m, "OptionalBoostHolder", "Class with optional member")
379 .def(py::init<>())
380 .def_readonly("member", &opt_boost_holder::member)
381 .def("member_initialized", &opt_boost_holder::member_initialized);
382
383 using opt_boost_props = OptionalProperties<boost::optional>;
384 pybind11::class_<opt_boost_props>(m, "OptionalBoostProperties")
385 .def(pybind11::init<>())
386 .def_property_readonly("access_by_ref", &opt_boost_props::access_by_ref)
387 .def_property_readonly("access_by_copy", &opt_boost_props::access_by_copy);
388#endif
389
390 // test_refsensitive_optional
391 using refsensitive_opt_int = ReferenceSensitiveOptional<int>;
392 using refsensitive_opt_no_assign = ReferenceSensitiveOptional<NoAssign>;
393 m.def("double_or_zero_refsensitive",
394 [](const refsensitive_opt_int &x) -> int { return (x ? x.value() : 0) * 2; });
395 m.def("half_or_none_refsensitive", [](int x) -> refsensitive_opt_int {
396 return x != 0 ? refsensitive_opt_int(x / 2) : refsensitive_opt_int();
397 });
398 m.def(
399 "test_nullopt_refsensitive",
400 // NOLINTNEXTLINE(performance-unnecessary-value-param)
401 [](refsensitive_opt_int x) { return x ? x.value() : 42; },
402 py::arg_v("x", refsensitive_opt_int(), "None"));
403 m.def(
404 "test_no_assign_refsensitive",
405 [](const refsensitive_opt_no_assign &x) { return x ? x->value : 42; },
406 py::arg_v("x", refsensitive_opt_no_assign(), "None"));
407
409 py::class_<opt_refsensitive_holder>(
410 m, "OptionalRefSensitiveHolder", "Class with optional member")
411 .def(py::init<>())
412 .def_readonly("member", &opt_refsensitive_holder::member)
413 .def("member_initialized", &opt_refsensitive_holder::member_initialized);
414
415 using opt_refsensitive_props = OptionalProperties<ReferenceSensitiveOptional>;
416 pybind11::class_<opt_refsensitive_props>(m, "OptionalRefSensitiveProperties")
417 .def(pybind11::init<>())
418 .def_property_readonly("access_by_ref", &opt_refsensitive_props::access_by_ref)
419 .def_property_readonly("access_by_copy", &opt_refsensitive_props::access_by_copy);
420
421#ifdef PYBIND11_HAS_FILESYSTEM
422 // test_fs_path
423 m.attr("has_filesystem") = true;
424 m.def("parent_path", [](const std::filesystem::path &p) { return p.parent_path(); });
425#endif
426
427#ifdef PYBIND11_HAS_VARIANT
428 static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value,
429 "visitor::result_type is required by boost::variant in C++11 mode");
430
431 struct visitor {
432 using result_type = const char *;
433
434 result_type operator()(int) { return "int"; }
435 result_type operator()(const std::string &) { return "std::string"; }
436 result_type operator()(double) { return "double"; }
437 result_type operator()(std::nullptr_t) { return "std::nullptr_t"; }
438 };
439
440 // test_variant
441 m.def("load_variant", [](const variant<int, std::string, double, std::nullptr_t> &v) {
442 return py::detail::visit_helper<variant>::call(visitor(), v);
443 });
444 m.def("load_variant_2pass", [](variant<double, int> v) {
445 return py::detail::visit_helper<variant>::call(visitor(), v);
446 });
447 m.def("cast_variant", []() {
448 using V = variant<int, std::string>;
449 return py::make_tuple(V(5), V("Hello"));
450 });
451#endif
452
453 // #528: templated constructor
454 // (no python tests: the test here is that this compiles)
455 m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {});
456 m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {});
457 m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {});
458#if defined(PYBIND11_HAS_OPTIONAL)
459 m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {});
460#endif
461#if defined(PYBIND11_HAS_EXP_OPTIONAL)
462 m.def("tpl_constr_optional_exp", [](std::experimental::optional<TplCtorClass> &) {});
463#endif
464#if defined(PYBIND11_TEST_BOOST)
465 m.def("tpl_constr_optional_boost", [](boost::optional<TplCtorClass> &) {});
466#endif
467
468 // test_vec_of_reference_wrapper
469 // #171: Can't return STL structures containing reference wrapper
470 m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) {
471 static UserType p1{1}, p2{2}, p3{3};
472 return std::vector<std::reference_wrapper<UserType>>{
473 std::ref(p1), std::ref(p2), std::ref(p3), p4};
474 });
475
476 // test_stl_pass_by_pointer
477 m.def(
478 "stl_pass_by_pointer", [](std::vector<int> *v) { return *v; }, "v"_a = nullptr);
479
480 // #1258: pybind11/stl.h converts string to vector<string>
481 m.def("func_with_string_or_vector_string_arg_overload",
482 [](const std::vector<std::string> &) { return 1; });
483 m.def("func_with_string_or_vector_string_arg_overload",
484 [](const std::list<std::string> &) { return 2; });
485 m.def("func_with_string_or_vector_string_arg_overload", [](const std::string &) { return 3; });
486
487 class Placeholder {
488 public:
489 Placeholder() { print_created(this); }
490 Placeholder(const Placeholder &) = delete;
491 ~Placeholder() { print_destroyed(this); }
492 };
493 py::class_<Placeholder>(m, "Placeholder");
494
496 m.def(
497 "test_stl_ownership",
498 []() {
499 std::vector<Placeholder *> result;
500 result.push_back(new Placeholder());
501 return result;
502 },
503 py::return_value_policy::take_ownership);
504
505 m.def("array_cast_sequence", [](std::array<int, 3> x) { return x; });
506
508 struct Issue1561Inner {
509 std::string data;
510 };
511 struct Issue1561Outer {
512 std::vector<Issue1561Inner> list;
513 };
514
515 py::class_<Issue1561Inner>(m, "Issue1561Inner")
516 .def(py::init<std::string>())
517 .def_readwrite("data", &Issue1561Inner::data);
518
519 py::class_<Issue1561Outer>(m, "Issue1561Outer")
520 .def(py::init<>())
521 .def_readwrite("list", &Issue1561Outer::list);
522
523 m.def(
524 "return_vector_bool_raw_ptr",
525 []() { return new std::vector<bool>(4513); },
526 // Without explicitly specifying `take_ownership`, this function leaks.
527 py::return_value_policy::take_ownership);
528}
OptionalEnumValue & access_by_ref()
Definition: test_stl.cpp:107
OptionalEnumValue value
Definition: test_stl.cpp:111
OptionalEnumValue access_by_copy()
Definition: test_stl.cpp:108
OptionalImpl< EnumType > OptionalEnumValue
Definition: test_stl.cpp:97
const T & value() const noexcept
Definition: test_stl.cpp:146
const T * operator->() const noexcept
Definition: test_stl.cpp:153
ReferenceSensitiveOptional & operator=(const T &value)
Definition: test_stl.cpp:130
ReferenceSensitiveOptional()=default
ReferenceSensitiveOptional(T &&value)
Definition: test_stl.cpp:129
const T & operator*() const noexcept
Definition: test_stl.cpp:151
std::vector< T > storage
Definition: test_stl.cpp:158
ReferenceSensitiveOptional & operator=(T &&value)
Definition: test_stl.cpp:134
ReferenceSensitiveOptional(const T &value)
Definition: test_stl.cpp:127
T & emplace(Args &&...args)
Definition: test_stl.cpp:140
A user-defined type which is exported and can be used by any test.
Definition: pytypes.h:1776
Definition: pytypes.h:1746
Definition: pytypes.h:1783
ssize_t hash(handle obj)
Definition: pytypes.h:581
#define PYBIND11_MAKE_OPAQUE(...)
Definition: cast.h:1650
@ move
Use std::move to move the return value contents into a new instance that will be owned by Python.
void print_created(T *inst, Values &&...values)
void print_destroyed(T *inst, Values &&...values)
#define TEST_SUBMODULE(name, variable)
arr data(const arr &a, Ix... index)
EnumType
Definition: test_stl.cpp:85
EnumType
Definition: test_stl.cpp:86
OptionalImpl< T > member
Definition: test_stl.cpp:82
bool member_initialized() const
Definition: test_stl.cpp:81
Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context.
Issue #528: templated constructor.
Definition: test_stl.cpp:64
TplCtorClass(const T &)
Definition: test_stl.cpp:66
bool operator==(const TplCtorClass &) const
Definition: test_stl.cpp:67
size_t operator()(const TplCtorClass &) const
Definition: test_stl.cpp:73
Generic variant caster.
Definition: stl.h:365
Helper class which abstracts away variant's visit function.
Definition: stl.h:356