Counter Strike : Global Offensive Source Code
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.

98 lines
2.0 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. #ifndef _BLOCKARRAY_H
  9. #define _BLOCKARRAY_H
  10. #include "tier0/dbg.h"
  11. // memdbgon must be the last include file in a .cpp file!!!
  12. #include <tier0/memdbgon.h>
  13. template <class T, int nBlockSize, int nMaxBlocks>
  14. class BlockArray
  15. {
  16. public:
  17. BlockArray()
  18. {
  19. nCount = nBlocks = 0;
  20. }
  21. ~BlockArray()
  22. {
  23. GetBlocks(0);
  24. }
  25. T& operator[] (int iIndex);
  26. void SetCount(int nObjects);
  27. int GetCount() { return nCount; }
  28. private:
  29. T * Blocks[nMaxBlocks+1];
  30. short nCount;
  31. short nBlocks;
  32. void GetBlocks(int nNewBlocks);
  33. };
  34. template <class T, int nBlockSize, int nMaxBlocks>
  35. void BlockArray<T,nBlockSize,nMaxBlocks>::
  36. GetBlocks(int nNewBlocks)
  37. {
  38. for(int i = nBlocks; i < nNewBlocks; i++)
  39. {
  40. Blocks[i] = new T[nBlockSize];
  41. }
  42. for(int i = nNewBlocks; i < nBlocks; i++)
  43. {
  44. delete[] Blocks[i];
  45. }
  46. nBlocks = nNewBlocks;
  47. }
  48. template <class T, int nBlockSize, int nMaxBlocks>
  49. void BlockArray<T,nBlockSize,nMaxBlocks>::
  50. SetCount(int nObjects)
  51. {
  52. if(nObjects == nCount)
  53. return;
  54. // find the number of blocks required by nObjects, checking for
  55. // integer rounding error
  56. int nNewBlocks = (nObjects / nBlockSize);
  57. if ((nNewBlocks * nBlockSize) < nObjects)
  58. {
  59. nNewBlocks++;
  60. }
  61. if(nNewBlocks != nBlocks)
  62. {
  63. // Make sure we don't get an overrun.
  64. if ( nNewBlocks > ARRAYSIZE( Blocks ) )
  65. {
  66. Error( "BlockArray< ?, %d, %d > - too many blocks needed.", nBlockSize, nMaxBlocks );
  67. }
  68. GetBlocks(nNewBlocks);
  69. }
  70. nCount = nObjects;
  71. }
  72. template <class T, int nBlockSize, int nMaxBlocks>
  73. T& BlockArray<T,nBlockSize,nMaxBlocks>::operator[] (int iIndex)
  74. {
  75. if(iIndex >= nCount)
  76. {
  77. Error( "BlockArray< %d, %d > - invalid block index.", iIndex, nCount );
  78. SetCount(iIndex+1);
  79. }
  80. return Blocks[iIndex / nBlockSize][iIndex % nBlockSize];
  81. }
  82. #include <tier0/memdbgoff.h>
  83. #endif // _BLOCKARRAY_H