Debian Codegraph @

src/python/PyImath/PyImathFixedArray.h

raw
1 //
2 // SPDX-License-Identifier: BSD-3-Clause
3 // Copyright Contributors to the OpenEXR Project.
4 //
5
6 // clang-format off
7
8 #ifndef _PyImathFixedArray_h_
9 #define _PyImathFixedArray_h_
10
11 #define BOOST_BIND_GLOBAL_PLACEHOLDERS
12 #include <boost/python.hpp>
13 #include <boost/operators.hpp>
14 #include <boost/shared_array.hpp>
15 #include <boost/any.hpp>
16 #include <iostream>
17 #include "PyImathUtil.h"
18
19 //
20 // Note: when PyImath from the v2 release of OpenEXR depended on Iex,
21 // the PY_IMATH_LEAVE/RETURN_PYTHON macros bracketed calls that
22 // enabled/disabled float-point exceptions via via the MathExcOn
23 // class. This was a compile-time option based on the setting of
24 // PYIMATH_ENABLE_EXCEPTIONS. This behavior is now deprecated, hence
25 // the empty macros.
26 //
27
28 #define PY_IMATH_LEAVE_PYTHON PyImath::PyReleaseLock pyunlock;
29 #define PY_IMATH_RETURN_PYTHON
30
31 namespace PyImath {
32
33 namespace {
34
35 //
36 // Utility classes used for converting array members to boost python objects.
37 //
38
39 template <class T>
40 struct ReturnReference
41 {
42 static boost::python::object applyReadOnly (const T& val)
43 {
44 typename boost::python::copy_const_reference::apply<const T&>::type converter;
45 return boost::python::object(boost::python::handle<>(converter(val)));
46 }
47
48 static boost::python::object applyWritable (T& val)
49 {
50 typename boost::python::reference_existing_object::apply<T&>::type converter;
51 return boost::python::object(boost::python::handle<>(converter(val)));
52 }
53
54 static bool isReferenceWrap () { return true; }
55 };
56
57 template <class T>
58 struct ReturnByValue
59 {
60 static boost::python::object applyReadOnly (const T& val)
61 {
62 typename boost::python::return_by_value::apply<T>::type converter;
63 return boost::python::object(boost::python::handle<>(converter(val)));
64 }
65
66 static boost::python::object applyWritable (T& val)
67 {
68 return applyReadOnly (val);
69 }
70
71 static bool isReferenceWrap () { return false; }
72 };
73
74 } // namespace
75
76 //
77 // Utility class for a runtime-specified fixed length array type in python
78 //
79 template <class T>
80 struct FixedArrayDefaultValue
81 {
82 static T value();
83 };
84
85 enum Uninitialized {UNINITIALIZED};
86
87 template <class T>
88 class FixedArray
89 {
90 T * _ptr;
91 size_t _length;
92 size_t _stride;
93 bool _writable;
94
95 // this handle optionally stores a shared_array to allocated array data
96 // so that everything is freed properly on exit.
97 boost::any _handle;
98
99 boost::shared_array<size_t> _indices; // non-NULL iff I'm a masked reference
100 size_t _unmaskedLength;
101
102
103 public:
104 typedef T BaseType;
105
106 FixedArray(T *ptr, Py_ssize_t length, Py_ssize_t stride = 1, bool writable = true)
107 : _ptr(ptr), _length(length), _stride(stride), _writable(writable),
108 _handle(), _unmaskedLength(0)
109 {
110 if (length < 0)
111 {
112 throw std::domain_error ("Fixed array length must be non-negative");
113 }
114 if (stride <= 0)
115 {
116 throw std::domain_error ("Fixed array stride must be positive");
117 }
118 // nothing
119 }
120
121 FixedArray(T *ptr, Py_ssize_t length, Py_ssize_t stride,
122 boost::any handle, bool writable = true)
123 : _ptr(ptr), _length(length), _stride(stride), _writable(writable),
124 _handle(handle), _unmaskedLength(0)
125 {
126 if (_length < 0)
127 {
128 throw std::domain_error("Fixed array length must be non-negative");
129 }
130 if (stride <= 0)
131 {
132 throw std::domain_error("Fixed array stride must be positive");
133 }
134 // nothing
135 }
136
137 FixedArray(const T *ptr, Py_ssize_t length, Py_ssize_t stride = 1)
138 : _ptr(const_cast<T *>(ptr)), _length(length), _stride(stride),
139 _writable(false), _handle(), _unmaskedLength(0)
140 {
141 if (length < 0)
142 {
143 throw std::logic_error("Fixed array length must be non-negative");
144 }
145 if (stride <= 0)
146 {
147 throw std::logic_error("Fixed array stride must be positive");
148 }
149 // nothing
150 }
151
152 FixedArray(const T *ptr, Py_ssize_t length, Py_ssize_t stride, boost::any handle)
153 : _ptr(const_cast<T *>(ptr)), _length(length), _stride(stride), _writable(false),
154 _handle(handle), _unmaskedLength(0)
155 {
156 if (_length < 0)
157 {
158 throw std::logic_error("Fixed array length must be non-negative");
159 }
160 if (stride <= 0)
161 {
162 throw std::logic_error("Fixed array stride must be positive");
163 }
164 // nothing
165 }
166
167 explicit FixedArray(Py_ssize_t length)
168 : _ptr(0), _length(length), _stride(1), _writable(true),
169 _handle(), _unmaskedLength(0)
170 {
171 if (_length < 0) {
172 throw std::domain_error("Fixed array length must be non-negative");
173 }
174 boost::shared_array<T> a(new T[length]);
175 T tmp = FixedArrayDefaultValue<T>::value();
176 for (Py_ssize_t i=0; i<length; ++i) a[i] = tmp;
177 _handle = a;
178 _ptr = a.get();
179 }
180
181 FixedArray(Py_ssize_t length,Uninitialized)
182 : _ptr(0), _length(length), _stride(1), _writable(true),
183 _handle(), _unmaskedLength(0)
184 {
185 if (_length < 0) {
186 throw std::domain_error("Fixed array length must be non-negative");
187 }
188 boost::shared_array<T> a(new T[length]);
189 _handle = a;
190 _ptr = a.get();
191 }
192
193 FixedArray(const T &initialValue, Py_ssize_t length)
194 : _ptr(0), _length(length), _stride(1), _writable(true),
195 _handle(), _unmaskedLength(0)
196 {
197 if (_length < 0) {
198 throw std::domain_error("Fixed array length must be non-negative");
199 }
200 boost::shared_array<T> a(new T[length]);
201 for (Py_ssize_t i=0; i<length; ++i) a[i] = initialValue;
202 _handle = a;
203 _ptr = a.get();
204 }
205
206 template <typename MaskArrayType>
207 FixedArray(FixedArray& f, const MaskArrayType& mask)
208 : _ptr(f._ptr), _stride(f._stride), _writable(f._writable), _handle(f._handle), _unmaskedLength(0)
209 {
210 if (f.isMaskedReference())
211 {
212 throw std::invalid_argument("Masking an already-masked FixedArray not supported yet (SQ27000)");
213 }
214
215 size_t len = f.match_dimension(mask);
216 _unmaskedLength = len;
217
218 size_t reduced_len = 0;
219 for (size_t i = 0; i < len; ++i)
220 if (mask[i])
221 reduced_len++;
222
223 _indices.reset(new size_t[reduced_len]);
224
225 for (size_t i = 0, j = 0; i < len; ++i)
226 {
227 if (mask[i])
228 {
229 _indices[j] = i;
230 j++;
231 }
232 }
233
234 _length = reduced_len;
235 }
236
237 template <typename MaskArrayType>
238 FixedArray(const FixedArray& f, const MaskArrayType& mask)
239 : _ptr(f._ptr), _stride(f._stride), _writable(false), _handle(f._handle), _unmaskedLength(0)
240 {
241 if (f.isMaskedReference())
242 {
243 throw std::invalid_argument("Masking an already-masked FixedArray not supported yet (SQ27000)");
244 }
245
246 size_t len = f.match_dimension(mask);
247 _unmaskedLength = len;
248
249 size_t reduced_len = 0;
250 for (size_t i = 0; i < len; ++i)
251 if (mask[i])
252 reduced_len++;
253
254 _indices.reset(new size_t[reduced_len]);
255
256 for (size_t i = 0, j = 0; i < len; ++i)
257 {
258 if (mask[i])
259 {
260 _indices[j] = i;
261 j++;
262 }
263 }
264
265 _length = reduced_len;
266 }
267
268 template <class S>
269 explicit FixedArray(const FixedArray<S> &other)
270 : _ptr(0), _length(other.len()), _stride(1), _writable(true),
271 _handle(), _unmaskedLength(other.unmaskedLength())
272 {
273 boost::shared_array<T> a(new T[_length]);
274 for (size_t i=0; i<_length; ++i) a[i] = T(other[i]);
275 _handle = a;
276 _ptr = a.get();
277
278 if (_unmaskedLength)
279 {
280 _indices.reset(new size_t[_length]);
281
282 for (size_t i = 0; i < _length; ++i)
283 _indices[i] = other.raw_ptr_index(i);
284 }
285 }
286
287 FixedArray(const FixedArray &other)
288 : _ptr(other._ptr), _length(other._length), _stride(other._stride),
289 _writable(other._writable),
290 _handle(other._handle),
291 _indices(other._indices),
292 _unmaskedLength(other._unmaskedLength)
293 {
294 }
295
296 const FixedArray &
297 operator = (const FixedArray &other)
298 {
299 if (&other == this) return *this;
300
301 _ptr = other._ptr;
302 _length = other._length;
303 _stride = other._stride;
304 _writable = other._writable;
305 _handle = other._handle;
306 _unmaskedLength = other._unmaskedLength;
307 _indices = other._indices;
308
309 return *this;
310 }
311
312 ~FixedArray()
313 {
314 // nothing
315 }
316
317 explicit operator bool() const {return _ptr != nullptr;}
318
319 const boost::any & handle() { return _handle; }
320
321 //
322 // Make an index suitable for indexing into an array in c++ from
323 // a python index, which can be negative for indexing relative to
324 // the end of an array
325 //
326 size_t canonical_index(Py_ssize_t index) const
327 {
328 if (index < 0) index += len();
329 if (index >= len() || index < 0) {
330 PyErr_SetString(PyExc_IndexError, "Index out of range");
331 boost::python::throw_error_already_set();
332 }
333 return index; // still a virtual index if this is a masked reference array
334 }
335
336 void extract_slice_indices(PyObject *index, size_t &start, size_t &end, Py_ssize_t &step, size_t &slicelength) const
337 {
338 if (PySlice_Check(index)) {
339 #if PY_MAJOR_VERSION > 2
340 PyObject *slice = index;
341 #else
342 PySliceObject *slice = reinterpret_cast<PySliceObject *>(index);
343 #endif
344 Py_ssize_t s,e,sl;
345 if (PySlice_GetIndicesEx(slice,_length,&s,&e,&step,&sl) == -1) {
346 boost::python::throw_error_already_set();
347 }
348 // e can be -1 if the iteration is backwards with a negative slice operator [::-n] (n > 0).
349 if (s < 0 || e < -1 || sl < 0) {
350 throw std::domain_error("Slice extraction produced invalid start, end, or length indices");
351 }
352 start = s;
353 end = e;
354 slicelength = sl;
355 } else if (PyInt_Check(index)) {
356 size_t i = canonical_index(PyInt_AsSsize_t(index));
357 start = i; end = i+1; step = 1; slicelength = 1;
358 } else {
359 PyErr_SetString(PyExc_TypeError, "Object is not a slice");
360 boost::python::throw_error_already_set();
361 }
362 }
363
364 // Although this method isn't used directly by this class,
365 // there are some sub-classes that are using it.
366 typedef typename boost::mpl::if_<boost::is_class<T>, T&,T>::type get_type;
367 get_type getitem(Py_ssize_t index) { return (*this)[canonical_index(index)]; }
368 typedef typename boost::mpl::if_<boost::is_class<T>,const T&,T>::type get_type_const;
369 get_type_const getitem(Py_ssize_t index) const { return (*this)[canonical_index(index)]; }
370
371 // We return an internal reference for class-types and a copy of the data
372 // for non-class types. Returning an internal refeference doesn't seem
373 // to work with non-class types.
374
375 boost::python::object getobjectTuple (Py_ssize_t index)
376 {
377 typedef typename boost::mpl::if_<boost::is_class<T>,
378 ReturnReference<T>,
379 ReturnByValue<T> >::type convertType;
380
381 boost::python::object retval;
382 int referenceMode = 0;
383
384 const size_t i = canonical_index(index);
385 T& val = _ptr[(isMaskedReference() ? raw_ptr_index(i) : i) * _stride];
386
387 if (_writable)
388 {
389 retval = convertType::applyWritable (val);
390
391 if (convertType::isReferenceWrap())
392 referenceMode = 0; // Managed reference.
393 else
394 referenceMode = 2; // Default policy (return-by-value)
395 }
396 else
397 {
398 retval = convertType::applyReadOnly (val);
399
400 if (convertType::isReferenceWrap())
401 referenceMode = 1; // Copy const reference
402 else
403 referenceMode = 2; // Default policy (return-by-value)
404 }
405
406 return boost::python::make_tuple (referenceMode, retval);
407 }
408
409 boost::python::object getobjectTuple (Py_ssize_t index) const
410 {
411 typedef typename boost::mpl::if_<boost::is_class<T>,
412 ReturnReference<T>,
413 ReturnByValue<T> >::type convertType;
414
415 boost::python::object retval;
416 int referenceMode = 1;
417
418 const size_t i = canonical_index(index);
419 const T& val = _ptr[(isMaskedReference() ? raw_ptr_index(i) : i) * _stride];
420
421 retval = convertType::applyReadOnly (val);
422
423 if (convertType::isReferenceWrap())
424 referenceMode = 1; // Copy const reference
425 else
426 referenceMode = 2; // Default policy (return-by-value)
427
428 return boost::python::make_tuple (referenceMode, retval);
429 }
430
431 FixedArray getslice(::PyObject *index) const
432 {
433 size_t start=0, end=0, slicelength=0;
434 Py_ssize_t step;
435 extract_slice_indices(index,start,end,step,slicelength);
436 FixedArray f(slicelength);
437
438 if (isMaskedReference())
439 {
440 for (size_t i=0; i<slicelength; ++i)
441 f._ptr[i] = _ptr[raw_ptr_index(start+i*step)*_stride];
442 }
443 else
444 {
445 for (size_t i=0; i<slicelength; ++i)
446 f._ptr[i] = _ptr[(start+i*step)*_stride];
447 }
448 return f;
449 }
450
451 template <typename MaskArrayType>
452 FixedArray getslice_mask(const MaskArrayType& mask)
453 {
454 // 'writable' state is preserved in the returned fixed-array.
455 FixedArray f(*this, mask);
456 return f;
457 }
458
459 void
460 setitem_scalar(PyObject *index, const T &data)
461 {
462 if (!_writable)
463 throw std::invalid_argument("Fixed array is read-only.");
464
465 size_t start=0, end=0, slicelength=0;
466 Py_ssize_t step;
467 extract_slice_indices(index,start,end,step,slicelength);
468
469 if (isMaskedReference())
470 {
471 for (size_t i=0; i<slicelength; ++i)
472 _ptr[raw_ptr_index(start+i*step)*_stride] = data;
473 }
474 else
475 {
476 for (size_t i=0; i<slicelength; ++i)
477 _ptr[(start+i*step)*_stride] = data;
478 }
479 }
480
481 template <typename MaskArrayType>
482 void
483 setitem_scalar_mask(const MaskArrayType &mask, const T &data)
484 {
485 if (!_writable)
486 throw std::invalid_argument("Fixed array is read-only.");
487
488 size_t len = match_dimension(mask, false);
489
490 if (isMaskedReference())
491 {
492 for (size_t i = 0; i < len; ++i)
493 _ptr[raw_ptr_index(i)*_stride] = data;
494 }
495 else
496 {
497 for (size_t i=0; i<len; ++i)
498 if (mask[i]) _ptr[i*_stride] = data;
499 }
500 }
501
502 template <typename ArrayType>
503 void
504 setitem_vector(::PyObject *index, const ArrayType &data)
505 {
506 if (!_writable)
507 throw std::invalid_argument("Fixed array is read-only.");
508
509 size_t start=0, end=0, slicelength=0;
510 Py_ssize_t step;
511 extract_slice_indices(index,start,end,step,slicelength);
512
513 // we have a valid range of indices
514 if ((size_t)data.len() != slicelength) {
515 PyErr_SetString(PyExc_IndexError, "Dimensions of source do not match destination");
516 boost::python::throw_error_already_set();
517 }
518
519 if (isMaskedReference())
520 {
521 for (size_t i=0; i<slicelength; ++i)
522 _ptr[raw_ptr_index(start+i*step)*_stride] = data[i];
523 }
524 else
525 {
526 for (size_t i=0; i<slicelength; ++i)
527 _ptr[(start+i*step)*_stride] = data[i];
528 }
529 }
530
531 template <typename MaskArrayType, typename ArrayType>
532 void
533 setitem_vector_mask(const MaskArrayType &mask, const ArrayType &data)
534 {
535 if (!_writable)
536 throw std::invalid_argument("Fixed array is read-only.");
537
538 // We could relax this but this restriction if there's a good
539 // enough reason too.
540
541 if (isMaskedReference())
542 {
543 throw std::invalid_argument("We don't support setting item masks for masked reference arrays.");
544 }
545
546 size_t len = match_dimension(mask);
547 if ((size_t)data.len() == len)
548 {
549 for (size_t i = 0; i < len; ++i)
550 if (mask[i]) _ptr[i*_stride] = data[i];
551 }
552 else
553 {
554 Py_ssize_t count = 0;
555 for (size_t i = 0; i < len; ++i)
556 if (mask[i]) count++;
557
558 if (data.len() != count) {
559 throw std::invalid_argument("Dimensions of source data do not match destination either masked or unmasked");
560 }
561
562 Py_ssize_t dataIndex = 0;
563 for (size_t i = 0; i < len; ++i)
564 {
565 if (mask[i])
566 {
567 _ptr[i*_stride] = data[dataIndex];
568 dataIndex++;
569 }
570 }
571 }
572 }
573
574 // exposed as Py_ssize_t for compatilbity with standard python sequences
575 Py_ssize_t len() const { return _length; }
576 size_t stride() const { return _stride; }
577 bool writable() const { return _writable; }
578
579 // This method is mainly here for use in confidence tests, but there may
580 // be other use-cases where a writable array needs to be made read-only.
581 // Note that we do not provide a 'makeWritable' method here, because that
582 // type of operation shouldn't be allowed.
583 void makeReadOnly() { _writable = false; }
584
585 // no bounds checking on i!
586 T& operator [] (size_t i)
587 {
588 if (!_writable)
589 throw std::invalid_argument("Fixed array is read-only.");
590
591 return _ptr[(isMaskedReference() ? raw_ptr_index(i) : i) * _stride];
592 }
593
594 // no bounds checking on i!
595 const T& operator [] (size_t i) const
596 {
597 return _ptr[(isMaskedReference() ? raw_ptr_index(i) : i) * _stride];
598 }
599
600 // no mask conversion or bounds checking on i!
601 T& direct_index(size_t i)
602 {
603 if (!_writable)
604 throw std::invalid_argument("Fixed array is read-only.");
605
606 return _ptr[i*_stride];
607 }
608
609 // no mask conversion or bounds checking on i!
610 const T& direct_index (size_t i) const
611 {
612 return _ptr[i*_stride];
613 }
614
615 // In some cases, an access to the raw data without the 'writable' check
616 // is needed. Generally in specialized python-wrapping helpers.
617 T& unchecked_index (size_t i)
618 {
619 return _ptr[(isMaskedReference() ? raw_ptr_index(i) : i) * _stride];
620 }
621
622 T& unchecked_direct_index (size_t i)
623 {
624 return _ptr[i*_stride];
625 }
626
627 bool isMaskedReference() const {return _indices.get() != 0;}
628 size_t unmaskedLength() const {return _unmaskedLength;}
629
630 // Conversion of indices to raw pointer indices.
631 // This should only be called when this is a masked reference.
632 // No safety checks done for performance.
633 size_t raw_ptr_index(size_t i) const
634 {
635 assert(isMaskedReference());
636 assert(i < _length);
637 assert(_indices[i] >= 0 && _indices[i] < _unmaskedLength);
638 return _indices[i];
639 }
640
641 static boost::python::class_<FixedArray<T> > register_(const char *doc)
642 {
643 // Depending on the data-type (class or fundamental) and the writable
644 // state of the array, different forms are returned by the '__getitem__'
645 // method. If writable and a class, an internal reference to the data
646 // is returned so that its value can be changed. If not-writable or a
647 // fundemental data type (float, int, etc.), then a 'copy' of the data
648 // is returned.
649
650 typename boost::python::object (FixedArray<T>::*nonconst_getobject)(Py_ssize_t) =
651 &FixedArray<T>::getobjectTuple;
652 typename boost::python::object (FixedArray<T>:: *const_getobject)(Py_ssize_t) const =
653 &FixedArray<T>::getobjectTuple;
654
655 boost::python::class_<FixedArray<T> > c(name(),doc, boost::python::init<size_t>("construct an array of the specified length initialized to the default value for the type"));
656 c
657 .def(boost::python::init<const FixedArray<T> &>("construct an array with the same values as the given array"))
658 .def(boost::python::init<const T &,size_t>("construct an array of the specified length initialized to the specified default value"))
659 .def("__getitem__", &FixedArray<T>::getslice)
660 .def("__getitem__", &FixedArray<T>::getslice_mask<FixedArray<int> > )
661 .def("__getitem__", const_getobject,
662 selectable_postcall_policy_from_tuple<
663 boost::python::with_custodian_and_ward_postcall<0,1>,
664 boost::python::return_value_policy<boost::python::copy_const_reference>,
665 boost::python::default_call_policies>())
666 .def("__getitem__", nonconst_getobject,
667 selectable_postcall_policy_from_tuple<
668 boost::python::with_custodian_and_ward_postcall<0,1>,
669 boost::python::return_value_policy<boost::python::copy_const_reference>,
670 boost::python::default_call_policies>())
671 .def("__setitem__", &FixedArray<T>::setitem_scalar)
672 .def("__setitem__", &FixedArray<T>::setitem_scalar_mask<FixedArray<int> >)
673 .def("__setitem__", &FixedArray<T>::setitem_vector<FixedArray<T> >)
674 .def("__setitem__", &FixedArray<T>::setitem_vector_mask<FixedArray<int>, FixedArray<T> >)
675 .def("__len__",&FixedArray<T>::len)
676 .def("writable",&FixedArray<T>::writable)
677 .def("makeReadOnly", &FixedArray<T>::makeReadOnly)
678 .def("ifelse",&FixedArray<T>::ifelse_scalar)
679 .def("ifelse",&FixedArray<T>::ifelse_vector)
680 ;
681 return c;
682 }
683
684 template <typename ArrayType>
685 size_t match_dimension(const ArrayType &a1, bool strictComparison = true) const
686 {
687 if (len() == a1.len())
688 return len();
689
690 bool throwExc = false;
691 if (strictComparison)
692 throwExc = true;
693 else if (isMaskedReference())
694 {
695 if (static_cast<Py_ssize_t>(_unmaskedLength) != a1.len())
696 throwExc = true;
697 }
698 else
699 throwExc = true;
700
701 if (throwExc)
702 {
703 throw std::invalid_argument("Dimensions of source do not match destination");
704 }
705
706 return len();
707 }
708
709 FixedArray<T> ifelse_vector(const FixedArray<int> &choice, const FixedArray<T> &other) {
710 size_t len = match_dimension(choice);
711 match_dimension(other);
712 FixedArray<T> tmp(len); // should use default construction but V3f doens't initialize
713 for (size_t i=0; i < len; ++i) tmp[i] = choice[i] ? (*this)[i] : other[i];
714 return tmp;
715 }
716
717 FixedArray<T> ifelse_scalar(const FixedArray<int> &choice, const T &other) {
718 size_t len = match_dimension(choice);
719 FixedArray<T> tmp(len); // should use default construction but V3f doens't initialize
720 for (size_t i=0; i < len; ++i) tmp[i] = choice[i] ? (*this)[i] : other;
721 return tmp;
722 }
723
724 // Instantiations of fixed ararys must implement this static member
725 static const char *name();
726
727 // Various 'Accessor' classes used in performance-critical areas while also
728 // managing the writable/read-only state efficiently.
729
730 class ReadOnlyDirectAccess
731 {
732 public:
733 ReadOnlyDirectAccess (const FixedArray<T>& array)
734 : _ptr (array._ptr), _stride (array._stride)
735 {
736 if (array.isMaskedReference())
737 throw std::invalid_argument ("Fixed array is masked. ReadOnlyDirectAccess not granted.");
738 }
739
740 ReadOnlyDirectAccess (const ReadOnlyDirectAccess& other)
741 : _ptr (other._ptr), _stride (other._stride) {}
742
743 const T& operator[] (size_t i) const { return _ptr[i*_stride]; }
744
745 private:
746 const T* _ptr;
747
748 protected:
749 const size_t _stride;
750 };
751
752 class WritableDirectAccess : public ReadOnlyDirectAccess
753 {
754 public:
755 WritableDirectAccess (FixedArray<T>& array)
756 : ReadOnlyDirectAccess (array), _ptr (array._ptr)
757 {
758 if (!array.writable())
759 throw std::invalid_argument ("Fixed array is read-only. WritableDirectAccess not granted.");
760 }
761
762 WritableDirectAccess (const WritableDirectAccess& other)
763 : ReadOnlyDirectAccess (other), _ptr (other._ptr) {}
764
765 T& operator[] (size_t i) { return _ptr[i*_stride]; }
766
767 private:
768 T* _ptr;
769
770 using ReadOnlyDirectAccess::_stride;
771 };
772
773 //
774
775 class ReadOnlyMaskedAccess
776 {
777 public:
778 ReadOnlyMaskedAccess (const FixedArray<T>& array)
779 : _ptr (array._ptr), _stride (array._stride),
780 _indices (array._indices)
781 {
782 if (!array.isMaskedReference())
783 throw std::invalid_argument ("Fixed array is not masked. ReadOnlyMaskedAccess not granted.");
784 }
785
786 ReadOnlyMaskedAccess (const ReadOnlyMaskedAccess& other)
787 : _ptr (other._ptr), _stride (other._stride),
788 _indices (other._indices) {}
789
790 // No index-range check here.
791 const T& operator[] (size_t i) const { return _ptr[_indices[i]*_stride]; }
792
793 private:
794 const T* _ptr;
795
796 protected:
797 const size_t _stride;
798 boost::shared_array<size_t> _indices;
799 };
800
801 class WritableMaskedAccess : public ReadOnlyMaskedAccess
802 {
803 public:
804 WritableMaskedAccess (FixedArray<T>& array)
805 : ReadOnlyMaskedAccess (array), _ptr (array._ptr)
806 {
807 if (!array.writable())
808 std::invalid_argument ("Fixed array is read-only. WritableMaskedAccess not granted.");
809 }
810
811 WritableMaskedAccess (const WritableMaskedAccess& other)
812 : ReadOnlyMaskedAccess (other), _ptr (other._ptr) {}
813
814 // No index-range check here.
815 T& operator[] (size_t i) { return _ptr[_indices[i]*_stride]; }
816
817 private:
818 T* _ptr;
819
820 using ReadOnlyMaskedAccess::_stride;
821 using ReadOnlyMaskedAccess::_indices;
822 };
823
824 };
825
826 //
827 // Helper struct for arary indexing with a known compile time length
828 //
829 template <class Container, class Data>
830 struct IndexAccessDefault {
831 typedef Data & result_type;
832 static Data & apply(Container &c, size_t i) { return c[i]; }
833 };
834
835 template <class Container, class Data, int Length, class IndexAccess = IndexAccessDefault<Container,Data> >
836 struct StaticFixedArray
837 {
838 static Py_ssize_t len(const Container &) { return Length; }
839 static typename IndexAccess::result_type getitem(Container &c, Py_ssize_t index) { return IndexAccess::apply(c,canonical_index(index)); }
840 static void setitem(Container &c, Py_ssize_t index, const Data &data) { IndexAccess::apply(c,canonical_index(index)) = data; }
841 static size_t canonical_index(Py_ssize_t index)
842 {
843 if (index < 0) index += Length;
844 if (index < 0 || index >= Length) {
845 PyErr_SetString(PyExc_IndexError, "Index out of range");
846 boost::python::throw_error_already_set();
847 }
848 return index;
849 }
850 };
851
852 }
853
854 #endif // _PyImathFixedArray_h_