IdList.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Ryujinx.Graphics.Metal
  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 = [];
  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. if ((uint)id < (uint)_list.Count)
  68. {
  69. value = _list[id];
  70. return value != null;
  71. }
  72. value = null;
  73. return false;
  74. }
  75. catch (ArgumentOutOfRangeException)
  76. {
  77. value = null;
  78. return false;
  79. }
  80. catch (IndexOutOfRangeException)
  81. {
  82. value = null;
  83. return false;
  84. }
  85. }
  86. public void Clear()
  87. {
  88. _list.Clear();
  89. _freeMin = 0;
  90. }
  91. public IEnumerator<T> GetEnumerator()
  92. {
  93. for (int i = 0; i < _list.Count; i++)
  94. {
  95. if (_list[i] != null)
  96. {
  97. yield return _list[i];
  98. }
  99. }
  100. }
  101. }
  102. }