IdPoolWithObj.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. namespace Ryujinx.Core.OsHle.Utilities
  6. {
  7. class IdPoolWithObj : IEnumerable<KeyValuePair<int, object>>
  8. {
  9. private IdPool Ids;
  10. private ConcurrentDictionary<int, object> Objs;
  11. public IdPoolWithObj()
  12. {
  13. Ids = new IdPool();
  14. Objs = new ConcurrentDictionary<int, object>();
  15. }
  16. public int GenerateId(object Data)
  17. {
  18. int Id = Ids.GenerateId();
  19. if (Id == -1 || !Objs.TryAdd(Id, Data))
  20. {
  21. throw new InvalidOperationException();
  22. }
  23. return Id;
  24. }
  25. public bool ReplaceData(int Id, object Data)
  26. {
  27. if (Objs.ContainsKey(Id))
  28. {
  29. Objs[Id] = Data;
  30. return true;
  31. }
  32. return false;
  33. }
  34. public T GetData<T>(int Id)
  35. {
  36. if (Objs.TryGetValue(Id, out object Data) && Data is T)
  37. {
  38. return (T)Data;
  39. }
  40. return default(T);
  41. }
  42. public void Delete(int Id)
  43. {
  44. if (Objs.TryRemove(Id, out object Obj))
  45. {
  46. if (Obj is IDisposable DisposableObj)
  47. {
  48. DisposableObj.Dispose();
  49. }
  50. Ids.DeleteId(Id);
  51. }
  52. }
  53. IEnumerator<KeyValuePair<int, object>> IEnumerable<KeyValuePair<int, object>>.GetEnumerator()
  54. {
  55. return Objs.GetEnumerator();
  56. }
  57. IEnumerator IEnumerable.GetEnumerator()
  58. {
  59. return Objs.GetEnumerator();
  60. }
  61. }
  62. }