You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

354 lines
11 KiB

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