IdList.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System.Collections.Generic;
  2. using System;
  3. namespace Ryujinx.Graphics.Vulkan
  4. {
  5. class IdList<T> where T : class
  6. {
  7. private readonly List<T> _list;
  8. private int _freeMin;
  9. public IdList()
  10. {
  11. _list = new List<T>();
  12. _freeMin = 0;
  13. }
  14. public int Add(T value)
  15. {
  16. int id;
  17. int count = _list.Count;
  18. id = _list.IndexOf(null, _freeMin);
  19. if ((uint)id < (uint)count)
  20. {
  21. _list[id] = value;
  22. }
  23. else
  24. {
  25. id = count;
  26. _freeMin = id + 1;
  27. _list.Add(value);
  28. }
  29. return id + 1;
  30. }
  31. public void Remove(int id)
  32. {
  33. id--;
  34. int count = _list.Count;
  35. if ((uint)id >= (uint)count)
  36. {
  37. return;
  38. }
  39. if (id + 1 == count)
  40. {
  41. // Trim unused items.
  42. int removeIndex = id;
  43. while (removeIndex > 0 && _list[removeIndex - 1] == null)
  44. {
  45. removeIndex--;
  46. }
  47. _list.RemoveRange(removeIndex, count - removeIndex);
  48. if (_freeMin > removeIndex)
  49. {
  50. _freeMin = removeIndex;
  51. }
  52. }
  53. else
  54. {
  55. _list[id] = null;
  56. if (_freeMin > id)
  57. {
  58. _freeMin = id;
  59. }
  60. }
  61. }
  62. public bool TryGetValue(int id, out T value)
  63. {
  64. id--;
  65. try
  66. {
  67. value = _list[id];
  68. return value != null;
  69. }
  70. catch (ArgumentOutOfRangeException)
  71. {
  72. value = null;
  73. return false;
  74. }
  75. catch (IndexOutOfRangeException)
  76. {
  77. value = null;
  78. return false;
  79. }
  80. }
  81. public void Clear()
  82. {
  83. _list.Clear();
  84. _freeMin = 0;
  85. }
  86. public IEnumerator<T> GetEnumerator()
  87. {
  88. for (int i = 0; i < _list.Count; i++)
  89. {
  90. if (_list[i] != null)
  91. {
  92. yield return _list[i];
  93. }
  94. }
  95. }
  96. }
  97. }