test_sequences_and_iterators.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. tests/test_sequences_and_iterators.cpp -- supporting Pythons' sequence protocol, iterators,
  3. etc.
  4. Copyright (c) 2016 Wenzel Jakob <[email protected]>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #include "pybind11_tests.h"
  9. #include "constructor_stats.h"
  10. #include <pybind11/operators.h>
  11. #include <pybind11/stl.h>
  12. template<typename T>
  13. class NonZeroIterator {
  14. const T* ptr_;
  15. public:
  16. NonZeroIterator(const T* ptr) : ptr_(ptr) {}
  17. const T& operator*() const { return *ptr_; }
  18. NonZeroIterator& operator++() { ++ptr_; return *this; }
  19. };
  20. class NonZeroSentinel {};
  21. template<typename A, typename B>
  22. bool operator==(const NonZeroIterator<std::pair<A, B>>& it, const NonZeroSentinel&) {
  23. return !(*it).first || !(*it).second;
  24. }
  25. template <typename PythonType>
  26. py::list test_random_access_iterator(PythonType x) {
  27. if (x.size() < 5)
  28. throw py::value_error("Please provide at least 5 elements for testing.");
  29. auto checks = py::list();
  30. auto assert_equal = [&checks](py::handle a, py::handle b) {
  31. auto result = PyObject_RichCompareBool(a.ptr(), b.ptr(), Py_EQ);
  32. if (result == -1) { throw py::error_already_set(); }
  33. checks.append(result != 0);
  34. };
  35. auto it = x.begin();
  36. assert_equal(x[0], *it);
  37. assert_equal(x[0], it[0]);
  38. assert_equal(x[1], it[1]);
  39. assert_equal(x[1], *(++it));
  40. assert_equal(x[1], *(it++));
  41. assert_equal(x[2], *it);
  42. assert_equal(x[3], *(it += 1));
  43. assert_equal(x[2], *(--it));
  44. assert_equal(x[2], *(it--));
  45. assert_equal(x[1], *it);
  46. assert_equal(x[0], *(it -= 1));
  47. assert_equal(it->attr("real"), x[0].attr("real"));
  48. assert_equal((it + 1)->attr("real"), x[1].attr("real"));
  49. assert_equal(x[1], *(it + 1));
  50. assert_equal(x[1], *(1 + it));
  51. it += 3;
  52. assert_equal(x[1], *(it - 2));
  53. checks.append(static_cast<std::size_t>(x.end() - x.begin()) == x.size());
  54. checks.append((x.begin() + static_cast<std::ptrdiff_t>(x.size())) == x.end());
  55. checks.append(x.begin() < x.end());
  56. return checks;
  57. }
  58. TEST_SUBMODULE(sequences_and_iterators, m) {
  59. // test_sequence
  60. class Sequence {
  61. public:
  62. Sequence(size_t size) : m_size(size) {
  63. print_created(this, "of size", m_size);
  64. m_data = new float[size];
  65. memset(m_data, 0, sizeof(float) * size);
  66. }
  67. Sequence(const std::vector<float> &value) : m_size(value.size()) {
  68. print_created(this, "of size", m_size, "from std::vector");
  69. m_data = new float[m_size];
  70. memcpy(m_data, &value[0], sizeof(float) * m_size);
  71. }
  72. Sequence(const Sequence &s) : m_size(s.m_size) {
  73. print_copy_created(this);
  74. m_data = new float[m_size];
  75. memcpy(m_data, s.m_data, sizeof(float)*m_size);
  76. }
  77. Sequence(Sequence &&s) : m_size(s.m_size), m_data(s.m_data) {
  78. print_move_created(this);
  79. s.m_size = 0;
  80. s.m_data = nullptr;
  81. }
  82. ~Sequence() { print_destroyed(this); delete[] m_data; }
  83. Sequence &operator=(const Sequence &s) {
  84. if (&s != this) {
  85. delete[] m_data;
  86. m_size = s.m_size;
  87. m_data = new float[m_size];
  88. memcpy(m_data, s.m_data, sizeof(float)*m_size);
  89. }
  90. print_copy_assigned(this);
  91. return *this;
  92. }
  93. Sequence &operator=(Sequence &&s) {
  94. if (&s != this) {
  95. delete[] m_data;
  96. m_size = s.m_size;
  97. m_data = s.m_data;
  98. s.m_size = 0;
  99. s.m_data = nullptr;
  100. }
  101. print_move_assigned(this);
  102. return *this;
  103. }
  104. bool operator==(const Sequence &s) const {
  105. if (m_size != s.size()) return false;
  106. for (size_t i = 0; i < m_size; ++i)
  107. if (m_data[i] != s[i])
  108. return false;
  109. return true;
  110. }
  111. bool operator!=(const Sequence &s) const { return !operator==(s); }
  112. float operator[](size_t index) const { return m_data[index]; }
  113. float &operator[](size_t index) { return m_data[index]; }
  114. bool contains(float v) const {
  115. for (size_t i = 0; i < m_size; ++i)
  116. if (v == m_data[i])
  117. return true;
  118. return false;
  119. }
  120. Sequence reversed() const {
  121. Sequence result(m_size);
  122. for (size_t i = 0; i < m_size; ++i)
  123. result[m_size - i - 1] = m_data[i];
  124. return result;
  125. }
  126. size_t size() const { return m_size; }
  127. const float *begin() const { return m_data; }
  128. const float *end() const { return m_data+m_size; }
  129. private:
  130. size_t m_size;
  131. float *m_data;
  132. };
  133. py::class_<Sequence>(m, "Sequence")
  134. .def(py::init<size_t>())
  135. .def(py::init<const std::vector<float>&>())
  136. /// Bare bones interface
  137. .def("__getitem__", [](const Sequence &s, size_t i) {
  138. if (i >= s.size()) throw py::index_error();
  139. return s[i];
  140. })
  141. .def("__setitem__", [](Sequence &s, size_t i, float v) {
  142. if (i >= s.size()) throw py::index_error();
  143. s[i] = v;
  144. })
  145. .def("__len__", &Sequence::size)
  146. /// Optional sequence protocol operations
  147. .def("__iter__", [](const Sequence &s) { return py::make_iterator(s.begin(), s.end()); },
  148. py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
  149. .def("__contains__", [](const Sequence &s, float v) { return s.contains(v); })
  150. .def("__reversed__", [](const Sequence &s) -> Sequence { return s.reversed(); })
  151. /// Slicing protocol (optional)
  152. .def("__getitem__", [](const Sequence &s, py::slice slice) -> Sequence* {
  153. size_t start, stop, step, slicelength;
  154. if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))
  155. throw py::error_already_set();
  156. Sequence *seq = new Sequence(slicelength);
  157. for (size_t i = 0; i < slicelength; ++i) {
  158. (*seq)[i] = s[start]; start += step;
  159. }
  160. return seq;
  161. })
  162. .def("__setitem__", [](Sequence &s, py::slice slice, const Sequence &value) {
  163. size_t start, stop, step, slicelength;
  164. if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))
  165. throw py::error_already_set();
  166. if (slicelength != value.size())
  167. throw std::runtime_error("Left and right hand size of slice assignment have different sizes!");
  168. for (size_t i = 0; i < slicelength; ++i) {
  169. s[start] = value[i]; start += step;
  170. }
  171. })
  172. /// Comparisons
  173. .def(py::self == py::self)
  174. .def(py::self != py::self)
  175. // Could also define py::self + py::self for concatenation, etc.
  176. ;
  177. // test_map_iterator
  178. // Interface of a map-like object that isn't (directly) an unordered_map, but provides some basic
  179. // map-like functionality.
  180. class StringMap {
  181. public:
  182. StringMap() = default;
  183. StringMap(std::unordered_map<std::string, std::string> init)
  184. : map(std::move(init)) {}
  185. void set(std::string key, std::string val) { map[key] = val; }
  186. std::string get(std::string key) const { return map.at(key); }
  187. size_t size() const { return map.size(); }
  188. private:
  189. std::unordered_map<std::string, std::string> map;
  190. public:
  191. decltype(map.cbegin()) begin() const { return map.cbegin(); }
  192. decltype(map.cend()) end() const { return map.cend(); }
  193. };
  194. py::class_<StringMap>(m, "StringMap")
  195. .def(py::init<>())
  196. .def(py::init<std::unordered_map<std::string, std::string>>())
  197. .def("__getitem__", [](const StringMap &map, std::string key) {
  198. try { return map.get(key); }
  199. catch (const std::out_of_range&) {
  200. throw py::key_error("key '" + key + "' does not exist");
  201. }
  202. })
  203. .def("__setitem__", &StringMap::set)
  204. .def("__len__", &StringMap::size)
  205. .def("__iter__", [](const StringMap &map) { return py::make_key_iterator(map.begin(), map.end()); },
  206. py::keep_alive<0, 1>())
  207. .def("items", [](const StringMap &map) { return py::make_iterator(map.begin(), map.end()); },
  208. py::keep_alive<0, 1>())
  209. ;
  210. // test_generalized_iterators
  211. class IntPairs {
  212. public:
  213. IntPairs(std::vector<std::pair<int, int>> data) : data_(std::move(data)) {}
  214. const std::pair<int, int>* begin() const { return data_.data(); }
  215. private:
  216. std::vector<std::pair<int, int>> data_;
  217. };
  218. py::class_<IntPairs>(m, "IntPairs")
  219. .def(py::init<std::vector<std::pair<int, int>>>())
  220. .def("nonzero", [](const IntPairs& s) {
  221. return py::make_iterator(NonZeroIterator<std::pair<int, int>>(s.begin()), NonZeroSentinel());
  222. }, py::keep_alive<0, 1>())
  223. .def("nonzero_keys", [](const IntPairs& s) {
  224. return py::make_key_iterator(NonZeroIterator<std::pair<int, int>>(s.begin()), NonZeroSentinel());
  225. }, py::keep_alive<0, 1>())
  226. ;
  227. #if 0
  228. // Obsolete: special data structure for exposing custom iterator types to python
  229. // kept here for illustrative purposes because there might be some use cases which
  230. // are not covered by the much simpler py::make_iterator
  231. struct PySequenceIterator {
  232. PySequenceIterator(const Sequence &seq, py::object ref) : seq(seq), ref(ref) { }
  233. float next() {
  234. if (index == seq.size())
  235. throw py::stop_iteration();
  236. return seq[index++];
  237. }
  238. const Sequence &seq;
  239. py::object ref; // keep a reference
  240. size_t index = 0;
  241. };
  242. py::class_<PySequenceIterator>(seq, "Iterator")
  243. .def("__iter__", [](PySequenceIterator &it) -> PySequenceIterator& { return it; })
  244. .def("__next__", &PySequenceIterator::next);
  245. On the actual Sequence object, the iterator would be constructed as follows:
  246. .def("__iter__", [](py::object s) { return PySequenceIterator(s.cast<const Sequence &>(), s); })
  247. #endif
  248. // test_python_iterator_in_cpp
  249. m.def("object_to_list", [](py::object o) {
  250. auto l = py::list();
  251. for (auto item : o) {
  252. l.append(item);
  253. }
  254. return l;
  255. });
  256. m.def("iterator_to_list", [](py::iterator it) {
  257. auto l = py::list();
  258. while (it != py::iterator::sentinel()) {
  259. l.append(*it);
  260. ++it;
  261. }
  262. return l;
  263. });
  264. // Make sure that py::iterator works with std algorithms
  265. m.def("count_none", [](py::object o) {
  266. return std::count_if(o.begin(), o.end(), [](py::handle h) { return h.is_none(); });
  267. });
  268. m.def("find_none", [](py::object o) {
  269. auto it = std::find_if(o.begin(), o.end(), [](py::handle h) { return h.is_none(); });
  270. return it->is_none();
  271. });
  272. m.def("count_nonzeros", [](py::dict d) {
  273. return std::count_if(d.begin(), d.end(), [](std::pair<py::handle, py::handle> p) {
  274. return p.second.cast<int>() != 0;
  275. });
  276. });
  277. m.def("tuple_iterator", &test_random_access_iterator<py::tuple>);
  278. m.def("list_iterator", &test_random_access_iterator<py::list>);
  279. m.def("sequence_iterator", &test_random_access_iterator<py::sequence>);
  280. // test_iterator_passthrough
  281. // #181: iterator passthrough did not compile
  282. m.def("iterator_passthrough", [](py::iterator s) -> py::iterator {
  283. return py::make_iterator(std::begin(s), std::end(s));
  284. });
  285. // test_iterator_rvp
  286. // #388: Can't make iterators via make_iterator() with different r/v policies
  287. static std::vector<int> list = { 1, 2, 3 };
  288. m.def("make_iterator_1", []() { return py::make_iterator<py::return_value_policy::copy>(list); });
  289. m.def("make_iterator_2", []() { return py::make_iterator<py::return_value_policy::automatic>(list); });
  290. }