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.

110 lines
2.1 KiB

  1. /*++
  2. Copyright (C) 1996-2001 Microsoft Corporation
  3. Module Name:
  4. FLEXQ.CPP
  5. Abstract:
  6. CFlexQueue.
  7. History:
  8. --*/
  9. #include "precomp.h"
  10. //#include <dbgalloc.h>
  11. #include <flexq.h>
  12. CFlexQueue::CFlexQueue(int nInitialSize) :
  13. m_nSize(nInitialSize), m_nHeadIndex(0), m_nTailIndex(0)
  14. {
  15. if(m_nSize)
  16. m_ppData = new void*[m_nSize];
  17. else
  18. m_ppData = NULL;
  19. }
  20. CFlexQueue::~CFlexQueue()
  21. {
  22. delete [] m_ppData;
  23. }
  24. bool CFlexQueue::Grow()
  25. {
  26. int nNewSize = (m_nSize + 1) * 2;
  27. // Allocate new memory block
  28. // =========================
  29. void** ppNewData = new void*[nNewSize];
  30. if(ppNewData == NULL)
  31. return false;
  32. // Copy the queue data to the beginning of the array
  33. // =================================================
  34. if(m_nHeadIndex <= m_nTailIndex)
  35. {
  36. memcpy(ppNewData, m_ppData + m_nHeadIndex,
  37. (m_nTailIndex - m_nHeadIndex) * sizeof(void*));
  38. }
  39. else
  40. {
  41. memcpy(ppNewData, m_ppData + m_nHeadIndex,
  42. (m_nSize - m_nHeadIndex) * sizeof(void*));
  43. memcpy(ppNewData + (m_nSize - m_nHeadIndex), m_ppData,
  44. m_nTailIndex * sizeof(void*));
  45. }
  46. m_nTailIndex = GetQueueSize();
  47. m_nHeadIndex = 0;
  48. m_nSize = nNewSize;
  49. delete [] m_ppData;
  50. m_ppData = ppNewData;
  51. return true;
  52. }
  53. bool CFlexQueue::Enqueue(void* pNew)
  54. {
  55. if(GetQueueSize() >= m_nSize - 1)
  56. {
  57. if(!Grow()) return false;
  58. }
  59. m_ppData[m_nTailIndex] = pNew;
  60. IncrementIndex(m_nTailIndex);
  61. return true;
  62. }
  63. void* CFlexQueue::Dequeue()
  64. {
  65. if(GetQueueSize() == 0)
  66. return NULL;
  67. void* pRet = m_ppData[m_nHeadIndex];
  68. IncrementIndex(m_nHeadIndex);
  69. return pRet;
  70. }
  71. void* CFlexQueue::Peek()
  72. {
  73. if(GetQueueSize() == 0)
  74. return NULL;
  75. return m_ppData[m_nHeadIndex];
  76. }
  77. bool CFlexQueue::Requeue(void* pNew)
  78. {
  79. if(GetQueueSize() >= m_nSize - 1)
  80. {
  81. if(!Grow()) return false;
  82. }
  83. DecrementIndex(m_nHeadIndex);
  84. m_ppData[m_nHeadIndex] = pNew;
  85. return true;
  86. }