MCPcopy Create free account
hub / github.com/pybind/pybind11 / unchecked_reference

Class unchecked_reference

include/pybind11/numpy.h:646–730  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

644 */
645template <typename T, ssize_t Dims>
646class unchecked_reference {
647protected:
648 static constexpr bool Dynamic = Dims < 0;
649 const unsigned char *data_;
650 // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
651 // make large performance gains on big, nested loops, but requires compile-time dimensions
652 conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>> shape_, strides_;
653 const ssize_t dims_;
654
655 friend class pybind11::array;
656 // Constructor for compile-time dimensions:
657 template <bool Dyn = Dynamic>
658 unchecked_reference(const void *data,
659 const ssize_t *shape,
660 const ssize_t *strides,
661 enable_if_t<!Dyn, ssize_t>)
662 : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
663 for (size_t i = 0; i < (size_t) dims_; i++) {
664 shape_[i] = shape[i];
665 strides_[i] = strides[i];
666 }
667 }
668 // Constructor for runtime dimensions:
669 template <bool Dyn = Dynamic>
670 unchecked_reference(const void *data,
671 const ssize_t *shape,
672 const ssize_t *strides,
673 enable_if_t<Dyn, ssize_t> dims)
674 : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
675 dims_{dims} {}
676
677public:
678 /**
679 * Unchecked const reference access to data at the given indices. For a compile-time known
680 * number of dimensions, this requires the correct number of arguments; for run-time
681 * dimensionality, this is not checked (and so is up to the caller to use safely).
682 */
683 template <typename... Ix>
684 const T &operator()(Ix... index) const {
685 static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
686 "Invalid number of indices for unchecked array reference");
687 return *reinterpret_cast<const T *>(data_
688 + byte_offset_unsafe(strides_, ssize_t(index)...));
689 }
690 /**
691 * Unchecked const reference access to data; this operator only participates if the reference
692 * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
693 */
694 template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
695 const T &operator[](ssize_t index) const {
696 return operator()(index);
697 }
698
699 /// Pointer access to the data at the given indices.
700 template <typename... Ix>
701 const T *data(Ix... ix) const {
702 return &operator()(ssize_t(ix)...);
703 }

Callers

nothing calls this directly

Calls 1

byte_offset_unsafeFunction · 0.85

Tested by

no test coverage detected