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