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.

124 lines
2.3 KiB

  1. // generic queue class
  2. // usage:
  3. // QueueOf<char *> charq;
  4. #ifndef _QUEUE_H_
  5. #define _QUEUE_H_
  6. template <class T>
  7. class QueueOf
  8. {
  9. public:
  10. QueueOf(): m_maxItems(8),m_iFirst(0),m_iLast(0)
  11. {
  12. // m_maxItems is always a power of 2
  13. m_List = new T [m_maxItems];
  14. }
  15. // returns TRUE if the queue is empty and FALSE otherwise
  16. BOOL IsEmpty(void) { return (m_iLast == m_iFirst);}
  17. // add an element to the tail of the queue
  18. // makes a copy of the element
  19. BOOL Put(const T &itemT)
  20. {
  21. int inext;
  22. inext = (m_iLast+1)&(m_maxItems-1);
  23. if (inext == m_iFirst)
  24. {
  25. // too many items
  26. if (!Grow())
  27. {
  28. return FALSE;
  29. }
  30. inext = (m_iLast+1)&(m_maxItems-1);
  31. }
  32. m_List[m_iLast] = itemT;
  33. m_iLast = inext;
  34. return TRUE;
  35. }
  36. // get the first element in the queue
  37. BOOL Get(T *pT)
  38. {
  39. if (IsEmpty())
  40. return FALSE; // nothing in queue
  41. else
  42. {
  43. if (pT)
  44. *pT = m_List[m_iFirst];
  45. m_iFirst = (m_iFirst+1)&(m_maxItems-1);
  46. return TRUE;
  47. }
  48. }
  49. // get the ith element in the queue without removing it
  50. BOOL Peek(T *pT, UINT pos=0)
  51. {
  52. if (pos >= GetCount())
  53. return FALSE;
  54. else
  55. {
  56. *pT = m_List[(m_iFirst+pos)&(m_maxItems-1)];
  57. return TRUE;
  58. }
  59. }
  60. // delete the ith element in the queue (this is not an efficient function!)
  61. BOOL Remove(UINT pos)
  62. {
  63. if (pos >= GetCount())
  64. return FALSE;
  65. else
  66. {
  67. int i1 = (m_iFirst+(int)pos)&(m_maxItems-1);
  68. int i2 = (i1+1)&(m_maxItems-1);
  69. // shift left to fill the gap
  70. for (; i2 != m_iLast; i1=i2,i2=(i2+1)&(m_maxItems-1))
  71. {
  72. m_List[i1] = m_List[i2];
  73. }
  74. m_iLast = i1; // i1 = m_iLast-1
  75. return TRUE;
  76. }
  77. }
  78. // return the number of elements in the queue
  79. UINT GetCount(void)
  80. {
  81. return (m_iLast >= m_iFirst ? m_iLast-m_iFirst : m_iLast+m_maxItems-m_iFirst);
  82. }
  83. ~QueueOf()
  84. {
  85. delete []m_List;
  86. }
  87. private:
  88. BOOL Grow(void)
  89. {
  90. int i,j;
  91. // double the size of the queue array
  92. T* pNewList = new T [m_maxItems*2];
  93. if (!pNewList)
  94. return FALSE;
  95. for (i=0, j=m_iFirst; j != m_iLast; i++, j = ((++j)&(m_maxItems-1)))
  96. {
  97. pNewList[i] = m_List[j];
  98. }
  99. m_iFirst = 0;
  100. m_iLast = i;
  101. m_maxItems = m_maxItems*2;
  102. delete [] m_List;
  103. m_List = pNewList;
  104. return TRUE;
  105. }
  106. int m_maxItems;
  107. int m_iFirst;
  108. int m_iLast;
  109. T *m_List;
  110. };
  111. ;
  112. #endif