array.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 #ifndef PXR_BASE_VT_ARRAY_H
25 #define PXR_BASE_VT_ARRAY_H
26 
28 
29 #include "pxr/pxr.h"
30 #include "pxr/base/vt/api.h"
31 #include "pxr/base/vt/hash.h"
32 #include "pxr/base/vt/streamOut.h"
33 #include "pxr/base/vt/traits.h"
34 #include "pxr/base/vt/types.h"
35 
37 #include "pxr/base/arch/pragmas.h"
38 #include "pxr/base/tf/diagnostic.h"
39 #include "pxr/base/tf/mallocTag.h"
40 
41 #include <boost/functional/hash.hpp>
42 #include <boost/iterator_adaptors.hpp>
43 #include <boost/iterator/reverse_iterator.hpp>
44 
45 #include <algorithm>
46 #include <atomic>
47 #include <cstddef>
48 #include <cstdlib>
49 #include <limits>
50 #include <memory>
51 #include <new>
52 #include <type_traits>
53 
54 PXR_NAMESPACE_OPEN_SCOPE
55 
56 // Helper class for clients that create VtArrays referring to foreign-owned
57 // data.
58 class Vt_ArrayForeignDataSource
59 {
60 public:
61  explicit Vt_ArrayForeignDataSource(
62  void (*detachedFn)(Vt_ArrayForeignDataSource *self) = nullptr,
63  size_t initRefCount = 0)
64  : _refCount(initRefCount)
65  , _detachedFn(detachedFn) {}
66 
67 private:
68  template <class T> friend class VtArray;
69  // Invoked when no more arrays share this data source.
70  void _ArraysDetached() { if (_detachedFn) { _detachedFn(this); } }
71 protected:
72  std::atomic<size_t> _refCount;
73  void (*_detachedFn)(Vt_ArrayForeignDataSource *self);
74 };
75 
76 // Private base class helper for VtArray implementation.
77 class Vt_ArrayBase
78 {
79 public:
80  Vt_ArrayBase() : _shapeData { 0 }, _foreignSource(nullptr) {}
81 
82  Vt_ArrayBase(Vt_ArrayForeignDataSource *foreignSrc)
83  : _shapeData { 0 }, _foreignSource(foreignSrc) {}
84 
85  Vt_ArrayBase(Vt_ArrayBase const &other) = default;
86  Vt_ArrayBase(Vt_ArrayBase &&other) : Vt_ArrayBase(other) {
87  other._shapeData.clear();
88  other._foreignSource = nullptr;
89  }
90 
91  Vt_ArrayBase &operator=(Vt_ArrayBase const &other) = default;
92  Vt_ArrayBase &operator=(Vt_ArrayBase &&other) {
93  if (this == &other)
94  return *this;
95  *this = other;
96  other._shapeData.clear();
97  other._foreignSource = nullptr;
98  return *this;
99  }
100 
101 protected:
102  // Control block header for native data representation. Houses refcount and
103  // capacity. For arrays with native data, this structure always lives
104  // immediately preceding the start of the array's _data in memory. See
105  // _GetControlBlock() for details.
106  struct _ControlBlock {
107  _ControlBlock() : nativeRefCount(0), capacity(0) {}
108  _ControlBlock(size_t initCount, size_t initCap)
109  : nativeRefCount(initCount), capacity(initCap) {}
110  mutable std::atomic<size_t> nativeRefCount;
111  size_t capacity;
112  };
113 
114  _ControlBlock &_GetControlBlock(void *nativeData) {
115  TF_DEV_AXIOM(!_foreignSource);
116  return *(reinterpret_cast<_ControlBlock *>(nativeData) - 1);
117  }
118 
119  _ControlBlock const &_GetControlBlock(void *nativeData) const {
120  TF_DEV_AXIOM(!_foreignSource);
121  return *(reinterpret_cast<_ControlBlock *>(nativeData) - 1);
122  }
123 
124  // Mutable ref count, as is standard.
125  std::atomic<size_t> &_GetNativeRefCount(void *nativeData) const {
126  return _GetControlBlock(nativeData).nativeRefCount;
127  }
128 
129  size_t &_GetCapacity(void *nativeData) {
130  return _GetControlBlock(nativeData).capacity;
131  }
132  size_t const &_GetCapacity(void *nativeData) const {
133  return _GetControlBlock(nativeData).capacity;
134  }
135 
136  VT_API void _DetachCopyHook(char const *funcName) const;
137 
138  Vt_ShapeData _shapeData;
139  Vt_ArrayForeignDataSource *_foreignSource;
140 };
141 
229 template<typename ELEM>
230 class VtArray : public Vt_ArrayBase {
231  public:
232 
234  typedef ELEM ElementType;
235  typedef ELEM value_type;
236 
239 
243  using const_iterator = ElementType const *;
244 
246  typedef boost::reverse_iterator<iterator> reverse_iterator;
248  typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
249 
253  typedef ElementType const &const_reference;
257  typedef ElementType const *const_pointer;
258 
260 
262  VtArray() : _data(nullptr) {}
263 
276  template <typename LegacyInputIterator>
277  VtArray(LegacyInputIterator first, LegacyInputIterator last,
278  typename std::enable_if<
279  !std::is_integral<LegacyInputIterator>::value,
280  void>::type* = nullptr)
281  : VtArray() {
282  assign(first, last);
283  }
284 
286  VtArray(Vt_ArrayForeignDataSource *foreignSrc,
287  ElementType *data, size_t size, bool addRef = true)
288  : Vt_ArrayBase(foreignSrc)
289  , _data(data) {
290  if (addRef) {
291  foreignSrc->_refCount.fetch_add(1, std::memory_order_relaxed);
292  }
293  _shapeData.totalSize = size;
294  }
295 
297  VtArray(VtArray const &other) : Vt_ArrayBase(other)
298  , _data(other._data) {
299  if (!_data)
300  return;
301 
302  if (ARCH_LIKELY(!_foreignSource)) {
303  _GetNativeRefCount(_data).fetch_add(1, std::memory_order_relaxed);
304  }
305  else {
306  _foreignSource->_refCount.fetch_add(1, std::memory_order_relaxed);
307  }
308  }
309 
312  VtArray(VtArray &&other) : Vt_ArrayBase(std::move(other))
313  , _data(other._data) {
314  other._data = nullptr;
315  }
316 
318  VtArray(std::initializer_list<ELEM> initializerList)
319  : VtArray() {
320  assign(initializerList);
321  }
322 
324  explicit VtArray(size_t n)
325  : VtArray() {
326  assign(n, value_type());
327  }
328 
330  explicit VtArray(size_t n, value_type const &value)
331  : VtArray() {
332  assign(n, value);
333  }
334 
337  VtArray &operator=(VtArray const &other) {
338  // This might look recursive but it's really invoking move-assign, since
339  // we create a temporary copy (an rvalue).
340  if (this != &other)
341  *this = VtArray(other);
342  return *this;
343  }
344 
348  if (this == &other)
349  return *this;
350  _DecRef();
351  static_cast<Vt_ArrayBase &>(*this) = std::move(other);
352  _data = other._data;
353  other._data = nullptr;
354  return *this;
355  }
356 
358  VtArray &operator=(std::initializer_list<ELEM> initializerList) {
359  this->assign(initializerList.begin(), initializerList.end());
360  return *this;
361  }
362 
363  ~VtArray() { _DecRef(); }
364 
373  VtArray const &AsConst() const noexcept {
374  return *this;
375  }
376 
379 
382  iterator begin() { return iterator(data()); }
385  iterator end() { return iterator(data() + size()); }
386 
388  const_iterator begin() const { return const_iterator(data()); }
390  const_iterator end() const { return const_iterator(data() + size()); }
391 
393  const_iterator cbegin() const { return begin(); }
395  const_iterator cend() const { return end(); }
396 
403 
406  return const_reverse_iterator(end());
407  }
410  return const_reverse_iterator(begin());
411  }
412 
414  const_reverse_iterator crbegin() const { return rbegin(); }
416  const_reverse_iterator crend() const { return rend(); }
417 
420  pointer data() { _DetachIfNotUnique(); return _data; }
422  const_pointer data() const { return _data; }
424  const_pointer cdata() const { return _data; }
425 
431  template <typename... Args>
432  void emplace_back(Args&&... args) {
433  // If this is a non-pxr array with rank > 1, disallow push_back.
434  if (ARCH_UNLIKELY(_shapeData.otherDims[0])) {
435  TF_CODING_ERROR("Array rank %u != 1", _shapeData.GetRank());
436  return;
437  }
438  // If we don't own the data, or if we need more space, realloc.
439  size_t curSize = size();
440  if (ARCH_UNLIKELY(
441  _foreignSource || !_IsUnique() || curSize == capacity())) {
442  value_type *newData = _AllocateCopy(
443  _data, _CapacityForSize(curSize + 1), curSize);
444  _DecRef();
445  _data = newData;
446  }
447  // Copy the value.
448  ::new (static_cast<void*>(_data + curSize)) value_type(
449  std::forward<Args>(args)...);
450  // Adjust size.
451  ++_shapeData.totalSize;
452  }
453 
459  void push_back(ElementType const& element) {
460  emplace_back(element);
461  }
462 
468  void push_back(ElementType&& element) {
469  emplace_back(std::move(element));
470  }
471 
474  void pop_back() {
475  // If this is a presto array with rank > 1, disallow push_back.
476  if (ARCH_UNLIKELY(_shapeData.otherDims[0])) {
477  TF_CODING_ERROR("Array rank %u != 1", _shapeData.GetRank());
478  return;
479  }
480  _DetachIfNotUnique();
481  // Invoke the destructor.
482  (_data + size() - 1)->~value_type();
483  // Adjust size.
484  --_shapeData.totalSize;
485  }
486 
488  size_t size() const { return _shapeData.totalSize; }
489 
494  size_t capacity() const {
495  if (!_data) {
496  return 0;
497  }
498  // We do not allow mutation to foreign source data, so always report
499  // foreign sourced arrays as at capacity.
500  return ARCH_UNLIKELY(_foreignSource) ? size() : _GetCapacity(_data);
501  }
502 
506  constexpr size_t max_size() const {
507  // The number of value_type elements that can be fit into maximum size_t
508  // bytes minus the size of _ControlBlock.
509  return (std::numeric_limits<size_t>::max() - sizeof(_ControlBlock))
510  / sizeof(value_type);
511  }
512 
514  bool empty() const { return size() == 0; }
515 
519  void reserve(size_t num) {
520  if (num <= capacity())
521  return;
522 
523  value_type *newData =
524  _data ? _AllocateCopy(_data, num, size()) : _AllocateNew(num);
525 
526  _DecRef();
527  _data = newData;
528  }
529 
533  reference front() { return *begin(); }
536  const_reference front() const { return *begin(); }
539  const_reference cfront() const { return *begin(); }
540 
544  reference back() { return *rbegin(); }
547  const_reference back() const { return *rbegin(); }
550  const_reference cback() const { return *rbegin(); }
551 
557  void resize(size_t newSize) {
558  struct _Filler {
559  inline void operator()(pointer b, pointer e) const {
560  std::uninitialized_fill(b, e, value_type());
561  }
562  };
563  return resize(newSize, _Filler());
564  }
565 
570  template <class FillElemsFn>
571  void resize(size_t newSize, FillElemsFn &&fillElems) {
572  const size_t oldSize = size();
573  if (oldSize == newSize) {
574  return;
575  }
576  if (newSize == 0) {
577  clear();
578  return;
579  }
580 
581  const bool growing = newSize > oldSize;
582  value_type *newData = _data;
583 
584  if (!_data) {
585  // Allocate newSize elements and initialize.
586  newData = _AllocateNew(newSize);
587  std::forward<FillElemsFn>(fillElems)(newData, newData + newSize);
588  }
589  else if (_IsUnique()) {
590  if (growing) {
591  if (newSize > _GetCapacity(_data)) {
592  newData = _AllocateCopy(_data, newSize, oldSize);
593  }
594  // fill with newly added elements from oldSize to newSize.
595  std::forward<FillElemsFn>(fillElems)(newData + oldSize,
596  newData + newSize);
597  }
598  else {
599  // destroy removed elements
600  for (auto *cur = newData + newSize,
601  *end = newData + oldSize; cur != end; ++cur) {
602  cur->~value_type();
603  }
604  }
605  }
606  else {
607  newData =
608  _AllocateCopy(_data, newSize, growing ? oldSize : newSize);
609  if (growing) {
610  // fill with newly added elements from oldSize to newSize.
611  std::forward<FillElemsFn>(fillElems)(newData + oldSize,
612  newData + newSize);
613  }
614  }
615 
616  // If we created new data, clean up the old and move over to the new.
617  if (newData != _data) {
618  _DecRef();
619  _data = newData;
620  }
621  // Adjust size.
622  _shapeData.totalSize = newSize;
623  }
624 
626  void clear() {
627  if (!_data)
628  return;
629  if (_IsUnique()) {
630  // Clear out elements, run dtors, keep capacity.
631  for (value_type *p = _data, *e = _data + size(); p != e; ++p) {
632  p->~value_type();
633  }
634  }
635  else {
636  // Detach to empty.
637  _DecRef();
638  }
639  _shapeData.totalSize = 0;
640  }
641 
655  TF_DEV_AXIOM(pos != cend());
656  return erase(pos, pos+1);
657  }
658 
675  if (first == last){
676  return std::next(begin(), std::distance(cbegin(), last));
677  }
678  if ((first == cbegin()) && (last == cend())){
679  clear();
680  return end();
681  }
682  // Given the previous two conditions, we know that we are removing
683  // at least one element and the result array will contain at least one
684  // element.
685  value_type* removeStart = std::next(_data, std::distance(cbegin(), first));
686  value_type* removeEnd = std::next(_data, std::distance(cbegin(), last));
687  value_type* endIt = std::next(_data, size());
688  size_t newSize = size() - std::distance(first, last);
689  if (_IsUnique()){
690  // If the array is unique, we can simply move the tail elements
691  // and free to the end of the array.
692  value_type* deleteIt = std::move(removeEnd, endIt, removeStart);
693  for (; deleteIt != endIt; ++deleteIt) {
694  deleteIt->~value_type();
695  }
696  _shapeData.totalSize = newSize;
697  return iterator(removeStart);
698  } else{
699  // If the array is not unique, we want to avoid copying the
700  // elements in the range we are erasing. We allocate a
701  // new buffer and copy the head and tail ranges, omitting
702  // [first, last)
703  value_type* newData = _AllocateNew(newSize);
704  value_type* newMiddle = std::uninitialized_copy(
705  _data, removeStart, newData);
706  value_type* newEnd = std::uninitialized_copy(
707  removeEnd, endIt, newMiddle);
708  TF_DEV_AXIOM(newEnd == std::next(newData, newSize));
709  TF_DEV_AXIOM(std::distance(newData, newMiddle) ==
710  std::distance(_data, removeStart));
711  _DecRef();
712  _data = newData;
713  _shapeData.totalSize = newSize;
714  return iterator(newMiddle);
715  }
716  }
717 
724  template <class ForwardIter>
725  typename std::enable_if<!std::is_integral<ForwardIter>::value>::type
726  assign(ForwardIter first, ForwardIter last) {
727  struct _Copier {
728  void operator()(pointer b, pointer e) const {
729  std::uninitialized_copy(first, last, b);
730  }
731  ForwardIter const &first, &last;
732  };
733  clear();
734  resize(std::distance(first, last), _Copier { first, last });
735  }
736 
743  void assign(size_t n, const value_type &fill) {
744  struct _Filler {
745  void operator()(pointer b, pointer e) const {
746  std::uninitialized_fill(b, e, fill);
747  }
748  const value_type &fill;
749  };
750  clear();
751  resize(n, _Filler { fill });
752  }
753 
759  void assign(std::initializer_list<ELEM> initializerList) {
760  assign(initializerList.begin(), initializerList.end());
761  }
762 
764  void swap(VtArray &other) {
765  std::swap(_data, other._data);
766  std::swap(_shapeData, other._shapeData);
767  std::swap(_foreignSource, other._foreignSource);
768  }
769 
771 
773  ElementType &operator[](size_t index) {
774  return data()[index];
775  }
776 
778  ElementType const &operator[](size_t index) const {
779  return data()[index];
780  }
781 
784  bool IsIdentical(VtArray const & other) const {
785  return
786  _data == other._data &&
787  _shapeData == other._shapeData &&
788  _foreignSource == other._foreignSource;
789  }
790 
792  bool operator == (VtArray const & other) const {
793  return IsIdentical(other) ||
794  (*_GetShapeData() == *other._GetShapeData() &&
795  std::equal(cbegin(), cend(), other.cbegin()));
796  }
797 
799  bool operator != (VtArray const &other) const {
800  return !(*this == other);
801  }
802 
803  public:
804  // XXX -- Public so VtValue::_ArrayHelper<T,U>::GetShapeData() has access.
805  Vt_ShapeData const *_GetShapeData() const {
806  return &_shapeData;
807  }
808  Vt_ShapeData *_GetShapeData() {
809  return &_shapeData;
810  }
811 
812  private:
813  class _Streamer : public VtStreamOutIterator {
814  public:
815  _Streamer(const_pointer data) : _p(data) { }
816  virtual ~_Streamer() { }
817  virtual void Next(std::ostream &out)
818  {
819  VtStreamOut(*_p++, out);
820  }
821 
822  private:
823  const_pointer _p;
824  };
825 
827  friend std::ostream &operator <<(std::ostream &out, const VtArray &self) {
828  VtArray::_Streamer streamer(self.cdata());
829  VtStreamOutArray(&streamer, self.size(), self._GetShapeData(), out);
830  return out;
831  }
832 
834  friend void swap(VtArray &lhs, VtArray &rhs) {
835  lhs.swap(rhs);
836  }
837 
838  void _DetachIfNotUnique() {
839  if (_IsUnique())
840  return;
841  // Copy to local.
842  _DetachCopyHook(__ARCH_PRETTY_FUNCTION__);
843  auto *newData = _AllocateCopy(_data, size(), size());
844  _DecRef();
845  _data = newData;
846  }
847 
848  inline bool _IsUnique() const {
849  return !_data ||
850  (ARCH_LIKELY(!_foreignSource) && _GetNativeRefCount(_data) == 1);
851  }
852 
853  inline size_t _CapacityForSize(size_t sz) const {
854  // Currently just successive powers of two.
855  size_t cap = 1;
856  while (cap < sz) {
857  cap += cap;
858  }
859  return cap;
860  }
861 
862  value_type *_AllocateNew(size_t capacity) {
863  TfAutoMallocTag2 tag("VtArray::_AllocateNew", __ARCH_PRETTY_FUNCTION__);
864  // Need space for the control block and capacity elements.
865  // Exceptionally large capacity requests can overflow the arithmetic
866  // here. If that happens we'll just attempt to allocate the max size_t
867  // value and let new() throw.
868  size_t numBytes = (capacity <= max_size())
869  ? sizeof(_ControlBlock) + capacity * sizeof(value_type)
870  : std::numeric_limits<size_t>::max();
871  void *data = ::operator new(numBytes);
872  // Placement-new a control block.
873  ::new (data) _ControlBlock(/*count=*/1, capacity);
874  // Data starts after the block.
875  return reinterpret_cast<value_type *>(
876  static_cast<_ControlBlock *>(data) + 1);
877  }
878 
879  value_type *_AllocateCopy(value_type *src, size_t newCapacity,
880  size_t numToCopy) {
881  // Allocate and copy elements.
882  value_type *newData = _AllocateNew(newCapacity);
883  std::uninitialized_copy(src, src + numToCopy, newData);
884  return newData;
885  }
886 
887  void _DecRef() {
888  if (!_data)
889  return;
890  if (ARCH_LIKELY(!_foreignSource)) {
891  // Drop the refcount. If we take it to zero, destroy the data.
892  if (_GetNativeRefCount(_data).fetch_sub(
893  1, std::memory_order_release) == 1) {
894  std::atomic_thread_fence(std::memory_order_acquire);
895  for (value_type *p = _data, *e = _data + _shapeData.totalSize;
896  p != e; ++p) {
897  p->~value_type();
898  }
899  ::operator delete(static_cast<void *>(
900  std::addressof(_GetControlBlock(_data))));
901  }
902  }
903  else {
904  // Drop the refcount in the foreign source. If we take it to zero,
905  // invoke the function pointer to alert the foreign source.
906  if (_foreignSource->_refCount.fetch_sub(
907  1, std::memory_order_release) == 1) {
908  std::atomic_thread_fence(std::memory_order_acquire);
909  _foreignSource->_ArraysDetached();
910  }
911  }
912  _foreignSource = nullptr;
913  _data = nullptr;
914  }
915 
916  value_type *_data;
917 };
918 
919 // Declare basic array instantiations as extern templates. They are explicitly
920 // instantiated in array.cpp.
921 #define VT_ARRAY_EXTERN_TMPL(r, unused, elem) \
922  extern template class VtArray< VT_TYPE(elem) >;
923 BOOST_PP_SEQ_FOR_EACH(VT_ARRAY_EXTERN_TMPL, ~, VT_SCALAR_VALUE_TYPES)
924 
925 template <class ELEM>
926 typename std::enable_if<VtIsHashable<ELEM>(), size_t>::type
927 hash_value(VtArray<ELEM> const &array) {
928  size_t h = array.size();
929  for (auto const &x: array) {
930  boost::hash_combine(h, x);
931  }
932  return h;
933 }
934 
935 // Specialize traits so others can figure out that VtArray is an array.
936 template <typename T>
937 struct VtIsArray< VtArray <T> > : public std::true_type {};
938 
939 
940 #define VTOPERATOR_CPPARRAY(op) \
941  template <class T> \
942  VtArray<T> \
943  operator op (VtArray<T> const &lhs, VtArray<T> const &rhs) \
944  { \
945  /* accept empty vecs */ \
946  if (!lhs.empty() && !rhs.empty() && lhs.size() != rhs.size()) { \
947  TF_CODING_ERROR("Non-conforming inputs for operator %s", #op); \
948  return VtArray<T>(); \
949  } \
950  /* promote empty vecs to vecs of zeros */ \
951  const bool leftEmpty = lhs.size() == 0, rightEmpty = rhs.size() == 0; \
952  VtArray<T> ret(leftEmpty ? rhs.size() : lhs.size()); \
953  T zero = VtZero<T>(); \
954  if (leftEmpty) { \
955  std::transform(rhs.begin(), rhs.end(), ret.begin(), \
956  [zero](T const &r) { return T(zero op r); }); \
957  } \
958  else if (rightEmpty) { \
959  std::transform(lhs.begin(), lhs.end(), ret.begin(), \
960  [zero](T const &l) { return T(l op zero); }); \
961  } \
962  else { \
963  std::transform(lhs.begin(), lhs.end(), rhs.begin(), ret.begin(), \
964  [](T const &l, T const &r) { return T(l op r); }); \
965  } \
966  return ret; \
967  }
968 
969 ARCH_PRAGMA_PUSH
970 ARCH_PRAGMA_FORCING_TO_BOOL
971 ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
972 ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
973 
974 VTOPERATOR_CPPARRAY(+);
975 VTOPERATOR_CPPARRAY(-);
976 VTOPERATOR_CPPARRAY(*);
977 VTOPERATOR_CPPARRAY(/);
978 VTOPERATOR_CPPARRAY(%);
979 
980 template <class T>
982 operator-(VtArray<T> const &a) {
983  VtArray<T> ret(a.size());
984  std::transform(a.begin(), a.end(), ret.begin(),
985  [](T const &x) { return -x; });
986  return ret;
987 }
988 
989 ARCH_PRAGMA_POP
990 
991 // Operations on scalars and arrays
992 // These are free functions defined in Array.h
993 #define VTOPERATOR_CPPSCALAR_TYPE(op,arraytype,scalartype,rettype) \
994  template<typename arraytype> \
995  VtArray<ElemType> \
996  operator op (scalartype const &scalar, \
997  VtArray<arraytype> const &vec) { \
998  VtArray<rettype> ret(vec.size()); \
999  for (size_t i = 0; i<vec.size(); ++i) { \
1000  ret[i] = scalar op vec[i]; \
1001  } \
1002  return ret; \
1003  } \
1004  template<typename arraytype> \
1005  VtArray<ElemType> \
1006  operator op (VtArray<arraytype> const &vec, \
1007  scalartype const &scalar) { \
1008  VtArray<rettype> ret(vec.size()); \
1009  for (size_t i = 0; i<vec.size(); ++i) { \
1010  ret[i] = vec[i] op scalar; \
1011  } \
1012  return ret; \
1013  }
1014 
1015 #define VTOPERATOR_CPPSCALAR(op) \
1016  VTOPERATOR_CPPSCALAR_TYPE(op,ElemType,ElemType,ElemType)
1017 
1018 // define special-case operators on arrays and doubles - except if the array
1019 // holds doubles, in which case we already defined the operator (with
1020 // VTOPERATOR_CPPSCALAR above) so we can't do it again!
1021 #define VTOPERATOR_CPPSCALAR_DOUBLE(op) \
1022  template<typename ElemType> \
1023  typename boost::disable_if<boost::is_same<ElemType, double>, \
1024  VtArray<ElemType> >::type \
1025  operator op (double const &scalar, \
1026  VtArray<ElemType> const &vec) { \
1027  VtArray<ElemType> ret(vec.size()); \
1028  for (size_t i = 0; i<vec.size(); ++i) { \
1029  ret[i] = scalar op vec[i]; \
1030  } \
1031  return ret; \
1032  } \
1033  template<typename ElemType> \
1034  typename boost::disable_if<boost::is_same<ElemType, double>, \
1035  VtArray<ElemType> >::type \
1036  operator op (VtArray<ElemType> const &vec, \
1037  double const &scalar) { \
1038  VtArray<ElemType> ret(vec.size()); \
1039  for (size_t i = 0; i<vec.size(); ++i) { \
1040  ret[i] = vec[i] op scalar; \
1041  } \
1042  return ret; \
1043  }
1044 
1045 // free functions for operators combining scalar and array types
1046 ARCH_PRAGMA_PUSH
1047 ARCH_PRAGMA_FORCING_TO_BOOL
1048 ARCH_PRAGMA_UNSAFE_USE_OF_BOOL
1049 ARCH_PRAGMA_UNARY_MINUS_ON_UNSIGNED
1050 VTOPERATOR_CPPSCALAR(+)
1051 VTOPERATOR_CPPSCALAR(-)
1052 VTOPERATOR_CPPSCALAR(*)
1053 VTOPERATOR_CPPSCALAR_DOUBLE(*)
1054 VTOPERATOR_CPPSCALAR(/)
1055 VTOPERATOR_CPPSCALAR_DOUBLE(/)
1056 VTOPERATOR_CPPSCALAR(%)
1057 ARCH_PRAGMA_POP
1058 
1059 PXR_NAMESPACE_CLOSE_SCOPE
1060 
1061 #endif // PXR_BASE_VT_ARRAY_H
#define TF_DEV_AXIOM(cond)
The same as TF_AXIOM, but compiled only in dev builds.
Definition: diagnostic.h:222
void resize(size_t newSize, FillElemsFn &&fillElems)
Resize this array.
Definition: array.h:571
ElementType & operator[](size_t index)
Allows usage of [i].
Definition: array.h:773
Pragmas for controlling compiler-specific behaviors.
void reserve(size_t num)
Ensure enough memory is allocated to hold num elements.
Definition: array.h:519
const_iterator begin() const
Return a const iterator to the start of the array.
Definition: array.h:388
size_t capacity() const
Return the number of items this container can grow to hold without triggering a (re)allocation.
Definition: array.h:494
friend std::ostream & operator<<(std::ostream &out, const VtArray &self)
Outputs a comma-separated list of the values in the array.
Definition: array.h:827
const_reference cback() const
Return a const reference to the last element in this array.
Definition: array.h:550
VtArray(Vt_ArrayForeignDataSource *foreignSrc, ElementType *data, size_t size, bool addRef=true)
Create an array with foreign source.
Definition: array.h:286
VtArray & operator=(VtArray &&other)
Move assign from other.
Definition: array.h:347
constexpr size_t max_size() const
Return a theoretical maximum size limit for the container.
Definition: array.h:506
VtArray & operator=(std::initializer_list< ELEM > initializerList)
Replace current array contents with those in initializerList.
Definition: array.h:358
reverse_iterator rend()
Return a reverse iterator to the start of the array.
Definition: array.h:402
size_t size() const
Return the total number of elements in this array.
Definition: array.h:488
Define preprocessor function name macros.
iterator begin()
Return a non-const iterator to the start of the array.
Definition: array.h:382
ElementType const * const_pointer
Const pointer type.
Definition: array.h:257
#define TF_CODING_ERROR(fmt, args)
Issue an internal programming error, but continue execution.
Definition: diagnostic.h:85
Basic type for a vector of 3 float components.
Definition: vec3f.h:63
const_reference cfront() const
Return a const reference to the first element in this array.
Definition: array.h:539
Low-level utilities for informing users of various internal and external diagnostic conditions.
VtArray(LegacyInputIterator first, LegacyInputIterator last, typename std::enable_if< !std::is_integral< LegacyInputIterator >::value, void >::type *=nullptr)
Create an array from a pair of iterators.
Definition: array.h:277
VtArray()
Create an empty array.
Definition: array.h:262
const_iterator end() const
Return a const iterator to the end of the array.
Definition: array.h:390
VtArray & operator=(VtArray const &other)
Copy assign from other.
Definition: array.h:337
void resize(size_t newSize)
Resize this array.
Definition: array.h:557
VtArray(size_t n, value_type const &value)
Create an array filled with n copies of value.
Definition: array.h:330
boost::reverse_iterator< iterator > reverse_iterator
Reverse iterator type.
Definition: array.h:246
iterator end()
Returns a non-const iterator to the end of the array.
Definition: array.h:385
bool IsIdentical(VtArray const &other) const
Tests if two arrays are identical, i.e.
Definition: array.h:784
ElementType const & const_reference
Const reference type.
Definition: array.h:253
void push_back(ElementType const &element)
Appends an element at the end of the array.
Definition: array.h:459
const_iterator cend() const
Return a const iterator to the end of the array.
Definition: array.h:395
void pop_back()
Remove the last element of an array.
Definition: array.h:474
ElementType & reference
Reference type.
Definition: array.h:251
void swap(UsdStageLoadRules &l, UsdStageLoadRules &r)
Swap the contents of rules l and r.
const_reverse_iterator crend() const
Return a const reverse iterator to the start of the array.
Definition: array.h:416
const_reverse_iterator crbegin() const
Return a const reverse iterator to the end of the array.
Definition: array.h:414
const_iterator cbegin() const
Return a const iterator to the start of the array.
Definition: array.h:393
std::enable_if<!std::is_integral< ForwardIter >::value >::type assign(ForwardIter first, ForwardIter last)
Assign array contents.
Definition: array.h:726
void push_back(ElementType &&element)
Appends an element at the end of the array.
Definition: array.h:468
pointer data()
Return a non-const pointer to this array's data.
Definition: array.h:420
Scoped (i.e.
Definition: mallocTag.h:255
VtArray const & AsConst() const noexcept
Return *this as a const reference.
Definition: array.h:373
const_reverse_iterator rbegin() const
Return a const reverse iterator to the end of the array.
Definition: array.h:405
Represents an arbitrary dimensional rectangular container class.
Definition: array.h:230
reference back()
Return a reference to the last element in this array.
Definition: array.h:544
friend void swap(VtArray &lhs, VtArray &rhs)
Swap array contents.
Definition: array.h:834
reverse_iterator rbegin()
Return a non-const reverse iterator to the end of the array.
Definition: array.h:399
Defines all the types "TYPED" for which Vt creates a VtTYPEDArray typedef.
ElementType * pointer
Pointer type.
Definition: array.h:255
Array concept. By default, types are not arrays.
Definition: traits.h:41
iterator erase(const_iterator pos)
Removes a single element at pos from the array.
Definition: array.h:654
VtArray(VtArray &&other)
Move from other.
Definition: array.h:312
void swap(VtArray &other)
Swap the contents of this array with other.
Definition: array.h:764
std::enable_if< std::is_same< Half, half >::value, size_t >::type hash_value(const Half &h)
Overload hash_value for half.
Definition: half.h:50
VtArray(size_t n)
Create an array filled with n value-initialized elements.
Definition: array.h:324
reference front()
Return a non-const reference to the first element in this array.
Definition: array.h:533
boost::reverse_iterator< const_iterator > const_reverse_iterator
Reverse const iterator type.
Definition: array.h:248
iterator erase(const_iterator first, const_iterator last)
Remove a range of elements [first, last) from the array.
Definition: array.h:674
ElementType const * const_iterator
Const iterator type.
Definition: array.h:243
const_reverse_iterator rend() const
Return a const reverse iterator to the start of the array.
Definition: array.h:409
bool empty() const
Return true if this array contains no elements, false otherwise.
Definition: array.h:514
VtArray(std::initializer_list< ELEM > initializerList)
Initialize array from the contents of a initializerList.
Definition: array.h:318
const_pointer cdata() const
Return a const pointer to the data held by this array.
Definition: array.h:424
ElementType * iterator
Iterator type.
Definition: array.h:241
const_reference front() const
Return a const reference to the first element in this array.
Definition: array.h:536
const_pointer data() const
Return a const pointer to this array's data.
Definition: array.h:422
void assign(size_t n, const value_type &fill)
Assign array contents.
Definition: array.h:743
ELEM ElementType
Type this array holds.
Definition: array.h:234
ElementType const & operator[](size_t index) const
Allows usage of [i].
Definition: array.h:778
const_reference back() const
Return a const reference to the last element in this array.
Definition: array.h:547
VtArray(VtArray const &other)
Copy other. The new array shares underlying data with other.
Definition: array.h:297
void emplace_back(Args &&... args)
Initializes a new element at the end of the array.
Definition: array.h:432
bool operator==(VtArray const &other) const
Tests two arrays for equality. See also IsIdentical().
Definition: array.h:792
void clear()
Equivalent to resize(0).
Definition: array.h:626
void assign(std::initializer_list< ELEM > initializerList)
Assign array contents via intializer list Equivalent to:
Definition: array.h:759
bool operator !=(VtArray const &other) const
Tests two arrays for inequality.
Definition: array.h:799