CycQueue.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*********************************************************************************
  2. *Author: OnClick
  3. *Version: 0.0.1
  4. *UnityVersion: 2017.2.3p3
  5. *Date: 2019-03-14
  6. *Description: IFramework
  7. *History: 2018.11--
  8. *********************************************************************************/
  9. using System;
  10. namespace IFramework.Packets
  11. {
  12. class CycQueue<T> : IDisposable
  13. {
  14. private T[] array = null;
  15. private int capacity = 4;
  16. private int head = 0;
  17. private int tail = 0;
  18. public int Capacity { get { return capacity; } }
  19. public T[] Array { get { return array; } }
  20. public bool IsEmpty { get { return tail == head; } }
  21. public int Length { get { return (tail - head + capacity) % capacity; } }
  22. public bool IsFull { get { return (tail + 1) % capacity == head; } }
  23. public CycQueue(int capacity)
  24. {
  25. if (capacity < 4) capacity = 4;
  26. this.capacity = capacity;
  27. array = new T[capacity];
  28. }
  29. public bool EnQueue(T value)
  30. {
  31. if (IsFull) return false;
  32. array[tail] = value;
  33. tail = (tail + 1) % capacity;
  34. return true;
  35. }
  36. public T DeQueue()
  37. {
  38. if (IsEmpty) return default(T);
  39. T v = array[head];
  40. head = (head + 1) % capacity;
  41. return v;
  42. }
  43. public T[] DeQueue(int size)
  44. {
  45. if (size > Length) return null;
  46. T[] array = new T[size];
  47. int index = 0;
  48. while (size > 0)
  49. {
  50. if (IsEmpty) return null;
  51. array[index] = this.array[head];
  52. head = (head + 1) % capacity;
  53. size--;
  54. index++;
  55. }
  56. return array;
  57. }
  58. public void Clear()
  59. {
  60. head = tail = 0;
  61. }
  62. public void Clear(int size)
  63. {
  64. int len = size <= Length ? size : Length;
  65. while (len > 0)
  66. {
  67. if (IsEmpty) break;
  68. head = (head + 1) % capacity;
  69. len--;
  70. }
  71. }
  72. public int DeSearchIndex(T value, int offset)
  73. {
  74. if (offset > Length) return -1;
  75. if (offset > 0)
  76. {
  77. head = (head + offset) % capacity;
  78. }
  79. while (Length > 0)
  80. {
  81. if (IsEmpty) return -1;
  82. if (value.Equals(array[head])) return head;
  83. head = (head + 1) % capacity;
  84. }
  85. return -1;
  86. }
  87. public int PeekIndex(T value, int offset)
  88. {
  89. if (offset > Length) return -1;
  90. int _h = (head + offset) % capacity;
  91. if (array[_h].Equals(value)) return _h;
  92. return -1;
  93. }
  94. public void Dispose()
  95. {
  96. if (array != null)
  97. array = null;
  98. }
  99. }
  100. }