Leaked source code of windows server 2003
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.

93 lines
2.2 KiB

  1. //----------------------------------------------------------------------------
  2. //
  3. // Specialized allocators.
  4. //
  5. // Copyright (C) Microsoft Corporation, 2001.
  6. //
  7. //----------------------------------------------------------------------------
  8. #ifndef __ALLOC_HPP__
  9. #define __ALLOC_HPP__
  10. //----------------------------------------------------------------------------
  11. //
  12. // FixedSizeStackAllocator.
  13. //
  14. // Parcels out memory chunks in strict LIFO allocation order.
  15. // This could easily be generalized to mixed allocation sizes
  16. // but then the size of each allocation would have to be tracked.
  17. //
  18. //----------------------------------------------------------------------------
  19. struct FixedSizeStackBlock
  20. {
  21. FixedSizeStackBlock* Next;
  22. PUCHAR MemLimit;
  23. };
  24. class FixedSizeStackAllocator
  25. {
  26. public:
  27. FixedSizeStackAllocator(ULONG ChunkSize, ULONG ChunksPerBlock,
  28. BOOL KeepLastBlock);
  29. ~FixedSizeStackAllocator(void);
  30. void* Alloc(void)
  31. {
  32. if (!m_Blocks ||
  33. m_Blocks->MemLimit >= (PUCHAR)m_Blocks + m_BlockSize)
  34. {
  35. if (!AllocBlock())
  36. {
  37. return NULL;
  38. }
  39. }
  40. void* Mem = m_Blocks->MemLimit;
  41. m_Blocks->MemLimit += m_ChunkSize;
  42. m_NumAllocs++;
  43. return Mem;
  44. }
  45. void Free(void* Mem)
  46. {
  47. if (!Mem)
  48. {
  49. return;
  50. }
  51. DBG_ASSERT(m_Blocks->MemLimit - m_ChunkSize == (PUCHAR)Mem);
  52. m_NumAllocs--;
  53. m_Blocks->MemLimit = (PUCHAR)Mem;
  54. if (m_Blocks->MemLimit == (PUCHAR)(m_Blocks + 1))
  55. {
  56. FreeBlock();
  57. }
  58. }
  59. void FreeAll(void);
  60. ULONG NumAllocatedChunks(void)
  61. {
  62. return m_NumAllocs;
  63. }
  64. protected:
  65. // Base methods use malloc/free.
  66. virtual void* RawAlloc(ULONG Bytes);
  67. virtual void RawFree(void* Mem);
  68. private:
  69. FixedSizeStackBlock* AllocBlock(void);
  70. void FreeBlock(void);
  71. ULONG m_ChunkSize;
  72. BOOL m_KeepLastBlock;
  73. ULONG m_BlockSize;
  74. ULONG m_NumAllocs;
  75. FixedSizeStackBlock* m_Blocks;
  76. };
  77. #endif // #ifndef __ALLOC_HPP__