slice.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #ifndef BOOST_PYTHON_SLICE_JDB20040105_HPP
  2. #define BOOST_PYTHON_SLICE_JDB20040105_HPP
  3. // Copyright (c) 2004 Jonathan Brandmeyer
  4. // Use, modification and distribution are subject to the
  5. // Boost Software License, Version 1.0. (See accompanying file
  6. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #include <boost/python/detail/prefix.hpp>
  8. #include <boost/config.hpp>
  9. #include <boost/python/object.hpp>
  10. #include <boost/python/extract.hpp>
  11. #include <boost/python/converter/pytype_object_mgr_traits.hpp>
  12. #include <boost/iterator/iterator_traits.hpp>
  13. #include <iterator>
  14. #include <algorithm>
  15. namespace boost { namespace python {
  16. namespace detail
  17. {
  18. class BOOST_PYTHON_DECL slice_base : public object
  19. {
  20. public:
  21. // Get the Python objects associated with the slice. In principle, these
  22. // may be any arbitrary Python type, but in practice they are usually
  23. // integers. If one or more parameter is ommited in the Python expression
  24. // that created this slice, than that parameter is None here, and compares
  25. // equal to a default-constructed boost::python::object.
  26. // If a user-defined type wishes to support slicing, then support for the
  27. // special meaning associated with negative indices is up to the user.
  28. object start() const;
  29. object stop() const;
  30. object step() const;
  31. protected:
  32. explicit slice_base(PyObject*, PyObject*, PyObject*);
  33. BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(slice_base, object)
  34. };
  35. }
  36. class slice : public detail::slice_base
  37. {
  38. typedef detail::slice_base base;
  39. public:
  40. // Equivalent to slice(::)
  41. slice() : base(0,0,0) {}
  42. // Each argument must be slice_nil, or implicitly convertable to object.
  43. // They should normally be integers.
  44. template<typename Integer1, typename Integer2>
  45. slice( Integer1 start, Integer2 stop)
  46. : base( object(start).ptr(), object(stop).ptr(), 0 )
  47. {}
  48. template<typename Integer1, typename Integer2, typename Integer3>
  49. slice( Integer1 start, Integer2 stop, Integer3 stride)
  50. : base( object(start).ptr(), object(stop).ptr(), object(stride).ptr() )
  51. {}
  52. // The following algorithm is intended to automate the process of
  53. // determining a slice range when you want to fully support negative
  54. // indices and non-singular step sizes. Its functionallity is simmilar to
  55. // PySlice_GetIndicesEx() in the Python/C API, but tailored for C++ users.
  56. // This template returns a slice::range struct that, when used in the
  57. // following iterative loop, will traverse a slice of the function's
  58. // arguments.
  59. // while (start != end) {
  60. // do_foo(...);
  61. // std::advance( start, step);
  62. // }
  63. // do_foo(...); // repeat exactly once more.
  64. // Arguments: a [begin, end) pair of STL-conforming random-access iterators.
  65. // Return: slice::range, where start and stop define a _closed_ interval
  66. // that covers at most [begin, end-1] of the provided arguments, and a step
  67. // that is non-zero.
  68. // Throws: error_already_set() if any of the indices are neither None nor
  69. // integers, or the slice has a step value of zero.
  70. // std::invalid_argument if the resulting range would be empty. Normally,
  71. // you should catch this exception and return an empty sequence of the
  72. // appropriate type.
  73. // Performance: constant time for random-access iterators.
  74. // Rationale:
  75. // closed-interval: If an open interval were used, then for a non-singular
  76. // value for step, the required state for the end iterator could be
  77. // beyond the one-past-the-end postion of the specified range. While
  78. // probably harmless, the behavior of STL-conforming iterators is
  79. // undefined in this case.
  80. // exceptions on zero-length range: It is impossible to define a closed
  81. // interval over an empty range, so some other form of error checking
  82. // would have to be used by the user to prevent undefined behavior. In
  83. // the case where the user fails to catch the exception, it will simply
  84. // be translated to Python by the default exception handling mechanisms.
  85. template<typename RandomAccessIterator>
  86. struct range
  87. {
  88. RandomAccessIterator start;
  89. RandomAccessIterator stop;
  90. typename iterator_difference<RandomAccessIterator>::type step;
  91. };
  92. template<typename RandomAccessIterator>
  93. slice::range<RandomAccessIterator>
  94. get_indices( const RandomAccessIterator& begin,
  95. const RandomAccessIterator& end) const
  96. {
  97. // This is based loosely on PySlice_GetIndicesEx(), but it has been
  98. // carefully crafted to ensure that these iterators never fall out of
  99. // the range of the container.
  100. slice::range<RandomAccessIterator> ret;
  101. typedef typename iterator_difference<RandomAccessIterator>::type difference_type;
  102. difference_type max_dist = std::distance(begin, end);
  103. object slice_start = this->start();
  104. object slice_stop = this->stop();
  105. object slice_step = this->step();
  106. // Extract the step.
  107. if (slice_step == object()) {
  108. ret.step = 1;
  109. }
  110. else {
  111. ret.step = extract<long>( slice_step);
  112. if (ret.step == 0) {
  113. PyErr_SetString( PyExc_IndexError, "step size cannot be zero.");
  114. throw_error_already_set();
  115. }
  116. }
  117. // Setup the start iterator.
  118. if (slice_start == object()) {
  119. if (ret.step < 0) {
  120. ret.start = end;
  121. --ret.start;
  122. }
  123. else
  124. ret.start = begin;
  125. }
  126. else {
  127. difference_type i = extract<long>( slice_start);
  128. if (i >= max_dist && ret.step > 0)
  129. throw std::invalid_argument( "Zero-length slice");
  130. if (i >= 0) {
  131. ret.start = begin;
  132. BOOST_USING_STD_MIN();
  133. std::advance( ret.start, min BOOST_PREVENT_MACRO_SUBSTITUTION(i, max_dist-1));
  134. }
  135. else {
  136. if (i < -max_dist && ret.step < 0)
  137. throw std::invalid_argument( "Zero-length slice");
  138. ret.start = end;
  139. // Advance start (towards begin) not farther than begin.
  140. std::advance( ret.start, (-i < max_dist) ? i : -max_dist );
  141. }
  142. }
  143. // Set up the stop iterator. This one is a little trickier since slices
  144. // define a [) range, and we are returning a [] range.
  145. if (slice_stop == object()) {
  146. if (ret.step < 0) {
  147. ret.stop = begin;
  148. }
  149. else {
  150. ret.stop = end;
  151. std::advance( ret.stop, -1);
  152. }
  153. }
  154. else {
  155. difference_type i = extract<long>(slice_stop);
  156. // First, branch on which direction we are going with this.
  157. if (ret.step < 0) {
  158. if (i+1 >= max_dist || i == -1)
  159. throw std::invalid_argument( "Zero-length slice");
  160. if (i >= 0) {
  161. ret.stop = begin;
  162. std::advance( ret.stop, i+1);
  163. }
  164. else { // i is negative, but more negative than -1.
  165. ret.stop = end;
  166. std::advance( ret.stop, (-i < max_dist) ? i : -max_dist);
  167. }
  168. }
  169. else { // stepping forward
  170. if (i == 0 || -i >= max_dist)
  171. throw std::invalid_argument( "Zero-length slice");
  172. if (i > 0) {
  173. ret.stop = begin;
  174. std::advance( ret.stop, (std::min)( i-1, max_dist-1));
  175. }
  176. else { // i is negative, but not more negative than -max_dist
  177. ret.stop = end;
  178. std::advance( ret.stop, i-1);
  179. }
  180. }
  181. }
  182. // Now the fun part, handling the possibilites surrounding step.
  183. // At this point, step has been initialized, ret.stop, and ret.step
  184. // represent the widest possible range that could be traveled
  185. // (inclusive), and final_dist is the maximum distance covered by the
  186. // slice.
  187. typename iterator_difference<RandomAccessIterator>::type final_dist =
  188. std::distance( ret.start, ret.stop);
  189. // First case, if both ret.start and ret.stop are equal, then step
  190. // is irrelevant and we can return here.
  191. if (final_dist == 0)
  192. return ret;
  193. // Second, if there is a sign mismatch, than the resulting range and
  194. // step size conflict: std::advance( ret.start, ret.step) goes away from
  195. // ret.stop.
  196. if ((final_dist > 0) != (ret.step > 0))
  197. throw std::invalid_argument( "Zero-length slice.");
  198. // Finally, if the last step puts us past the end, we move ret.stop
  199. // towards ret.start in the amount of the remainder.
  200. // I don't remember all of the oolies surrounding negative modulii,
  201. // so I am handling each of these cases separately.
  202. if (final_dist < 0) {
  203. difference_type remainder = -final_dist % -ret.step;
  204. std::advance( ret.stop, remainder);
  205. }
  206. else {
  207. difference_type remainder = final_dist % ret.step;
  208. std::advance( ret.stop, -remainder);
  209. }
  210. return ret;
  211. }
  212. // Incorrect spelling. DO NOT USE. Only here for backward compatibility.
  213. // Corrected 2011-06-14.
  214. template<typename RandomAccessIterator>
  215. slice::range<RandomAccessIterator>
  216. get_indicies( const RandomAccessIterator& begin,
  217. const RandomAccessIterator& end) const
  218. {
  219. return get_indices(begin, end);
  220. }
  221. public:
  222. // This declaration, in conjunction with the specialization of
  223. // object_manager_traits<> below, allows C++ functions accepting slice
  224. // arguments to be called from from Python. These constructors should never
  225. // be used in client code.
  226. BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(slice, detail::slice_base)
  227. };
  228. namespace converter {
  229. template<>
  230. struct object_manager_traits<slice>
  231. : pytype_object_manager_traits<&PySlice_Type, slice>
  232. {
  233. };
  234. } // !namesapce converter
  235. } } // !namespace ::boost::python
  236. #endif // !defined BOOST_PYTHON_SLICE_JDB20040105_HPP