IdDictionary.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. namespace Ryujinx.Core.OsHle
  6. {
  7. class IdDictionary : IEnumerable<object>
  8. {
  9. private ConcurrentDictionary<int, object> Objs;
  10. private int FreeIdHint = 1;
  11. public IdDictionary()
  12. {
  13. Objs = new ConcurrentDictionary<int, object>();
  14. }
  15. public int Add(object Data)
  16. {
  17. if (Objs.TryAdd(FreeIdHint, Data))
  18. {
  19. return FreeIdHint++;
  20. }
  21. return AddSlow(Data);
  22. }
  23. private int AddSlow(object Data)
  24. {
  25. for (int Id = 1; Id < int.MaxValue; Id++)
  26. {
  27. if (Objs.TryAdd(Id, Data))
  28. {
  29. return Id;
  30. }
  31. }
  32. throw new InvalidOperationException();
  33. }
  34. public bool ReplaceData(int Id, object Data)
  35. {
  36. if (Objs.ContainsKey(Id))
  37. {
  38. Objs[Id] = Data;
  39. return true;
  40. }
  41. return false;
  42. }
  43. public object GetData(int Id)
  44. {
  45. if (Objs.TryGetValue(Id, out object Data))
  46. {
  47. return Data;
  48. }
  49. return null;
  50. }
  51. public T GetData<T>(int Id)
  52. {
  53. if (Objs.TryGetValue(Id, out object Data) && Data is T)
  54. {
  55. return (T)Data;
  56. }
  57. return default(T);
  58. }
  59. public bool Delete(int Id)
  60. {
  61. if (Objs.TryRemove(Id, out object Obj))
  62. {
  63. if (Obj is IDisposable DisposableObj)
  64. {
  65. DisposableObj.Dispose();
  66. }
  67. FreeIdHint = Id;
  68. return true;
  69. }
  70. return false;
  71. }
  72. IEnumerator<object> IEnumerable<object>.GetEnumerator()
  73. {
  74. return Objs.Values.GetEnumerator();
  75. }
  76. IEnumerator IEnumerable.GetEnumerator()
  77. {
  78. return Objs.Values.GetEnumerator();
  79. }
  80. }
  81. }