Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

141 lines
2.8 KiB

  1. #ifndef _SIMPLEARRAY_H_
  2. #define _SIMPLEARRAY_H_
  3. #include <malloc.h>
  4. #ifndef SIMPLEARRAY_STARTSIZE
  5. #define SIMPLEARRAY_STARTSIZE 1
  6. #endif
  7. template <class T>
  8. class CSimpleArray
  9. {
  10. public:
  11. T* m_aT;
  12. int m_nSize;
  13. int m_nAllocSize;
  14. // Construction/destruction
  15. CSimpleArray() : m_aT(NULL), m_nSize(0), m_nAllocSize(0)
  16. { }
  17. ~CSimpleArray()
  18. {
  19. RemoveAll();
  20. }
  21. // Operations
  22. int GetSize() const
  23. {
  24. return m_nSize;
  25. }
  26. BOOL Add(T& t)
  27. {
  28. if(m_nSize == m_nAllocSize)
  29. {
  30. T* aT;
  31. int nNewAllocSize = (m_nAllocSize == 0) ? SIMPLEARRAY_STARTSIZE : (m_nSize * 2);
  32. if (m_aT)
  33. aT = (T*)realloc(m_aT, nNewAllocSize * sizeof(T));
  34. else
  35. aT = (T*)malloc(nNewAllocSize * sizeof(T));
  36. if(aT == NULL)
  37. return FALSE;
  38. m_nAllocSize = nNewAllocSize;
  39. m_aT = aT;
  40. }
  41. m_nSize++;
  42. SetAtIndex(m_nSize - 1, t);
  43. return TRUE;
  44. }
  45. BOOL Remove(T& t)
  46. {
  47. int nIndex = Find(t);
  48. if(nIndex == -1)
  49. return FALSE;
  50. return RemoveAt(nIndex);
  51. }
  52. BOOL RemoveAt(int nIndex)
  53. {
  54. //---- always call the dtr ----
  55. #if _MSC_VER >= 1200
  56. m_aT[nIndex].~T();
  57. #else
  58. T* MyT;
  59. MyT = &m_aT[nIndex];
  60. MyT->~T();
  61. #endif
  62. //---- if target entry is not at end, compact the array ----
  63. if(nIndex != (m_nSize - 1))
  64. {
  65. memmove((void*)&m_aT[nIndex], (void*)&m_aT[nIndex + 1], (m_nSize - (nIndex + 1)) * sizeof(T));
  66. }
  67. m_nSize--;
  68. return TRUE;
  69. }
  70. void RemoveAll()
  71. {
  72. if(m_aT != NULL)
  73. {
  74. for(int i = 0; i < m_nSize; i++) {
  75. #if _MSC_VER >= 1200
  76. m_aT[i].~T();
  77. #else
  78. T* MyT;
  79. MyT = &m_aT[i];
  80. MyT->~T();
  81. #endif
  82. }
  83. free(m_aT);
  84. m_aT = NULL;
  85. }
  86. m_nSize = 0;
  87. m_nAllocSize = 0;
  88. }
  89. T& operator[] (int nIndex) const
  90. {
  91. DBG_ASSERT(nIndex >= 0 && nIndex < m_nSize);
  92. return m_aT[nIndex];
  93. }
  94. T* GetData() const
  95. {
  96. return m_aT;
  97. }
  98. // Implementation
  99. class Wrapper
  100. {
  101. public:
  102. Wrapper(T& _t) : t(_t)
  103. {
  104. }
  105. template <class _Ty>
  106. void *operator new(size_t, _Ty* p)
  107. {
  108. return p;
  109. }
  110. T t;
  111. };
  112. void SetAtIndex(int nIndex, T& t)
  113. {
  114. DBG_ASSERT(nIndex >= 0 && nIndex < m_nSize);
  115. new(m_aT + nIndex) Wrapper(t);
  116. }
  117. int Find(T& t) const
  118. {
  119. for(int i = 0; i < m_nSize; i++)
  120. {
  121. if(m_aT[i] == t)
  122. return i;
  123. }
  124. return -1; // not found
  125. }
  126. };
  127. #endif