HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_StackBuffer.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: UT_StackBuffer.h (C++)
7  *
8  * COMMENTS: A special buffer class that allocates from the stack if
9  * below the given threshold.
10  *
11  */
12 
13 #ifndef __UT_StackBuffer_h__
14 #define __UT_StackBuffer_h__
15 
16 #include <SYS/SYS_Types.h>
17 
18 template <typename T, size_t MAXBYTES = 256>
20 {
21 public:
22  typedef T value_type;
23 
24  UT_StackBuffer() : mySize(0), myData(myBuffer) {}
25  UT_StackBuffer(size_t num_elems)
26  : mySize(num_elems)
27  {
28  if (num_elems <= MAXELEMS)
29  myData = myBuffer;
30  else
31  myData = new T[num_elems];
32  }
34  {
35  if (myData != myBuffer)
36  delete [] myData;
37  }
38 
39  /// be careful with this, as constructors/destructors will not be called
40  /// on the contents of the stack buffer
41  void setSize(size_t num_elems)
42  {
43  if (mySize == num_elems)
44  return;
45 
46  if (myData != myBuffer)
47  delete [] myData;
48 
49  if (num_elems <= MAXELEMS)
50  myData = myBuffer;
51  else
52  myData = new T[num_elems];
53 
54  mySize = num_elems;
55  }
56 
57  operator T *()
58  {
59  return myData;
60  }
61  operator const T *() const
62  {
63  return (const T *)myData;
64  }
65 
66  T *array() { return myData; }
67  const T *array() const { return myData; }
68 
69  // Some compilers get confused when there are both the array subscript
70  // operators below and the implicit cast to pointer above,
71  // even though it seems obvious that the operator[] should take
72  // precedence when doing buf[integer].
73 #if 0
74  T &operator[](exint i) { return myData[i]; }
75  const T &operator[](exint i) const { return myData[i]; }
76 #endif
77 
78  T &operator()(exint i) { return myData[i]; }
79  const T &operator()(exint i) const { return myData[i]; }
80 
81  exint size() const { return mySize; }
82 
83  typedef T *iterator;
84  typedef const T *const_iterator;
85  iterator begin() { return myData; }
86  iterator end() { return myData+mySize; }
87  const_iterator begin() const { return myData; }
88  const_iterator end() const { return myData+mySize; }
89 
90 private:
91  static const int MAXELEMS = (MAXBYTES + sizeof(T) - 1)/sizeof(T);
92 
93  T *myData;
94  exint mySize;
95  T myBuffer[MAXELEMS];
96 };
97 
98 #endif // __UT_StackBuffer_h__
void setSize(size_t num_elems)
iterator end()
UT_StackBuffer(size_t num_elems)
int64 exint
Definition: SYS_Types.h:125
const T & operator()(exint i) const
const_iterator end() const
exint size() const
T & operator()(exint i)
const T * const_iterator
const_iterator begin() const
iterator begin()
const T * array() const