TranslatorCache.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace ARMeilleure.Translation
  5. {
  6. internal class TranslatorCache<T>
  7. {
  8. private readonly IntervalTree<ulong, T> _tree;
  9. private readonly ReaderWriterLock _treeLock;
  10. public int Count => _tree.Count;
  11. public TranslatorCache()
  12. {
  13. _tree = new IntervalTree<ulong, T>();
  14. _treeLock = new ReaderWriterLock();
  15. }
  16. public bool TryAdd(ulong address, ulong size, T value)
  17. {
  18. return AddOrUpdate(address, size, value, null);
  19. }
  20. public bool AddOrUpdate(ulong address, ulong size, T value, Func<ulong, T, T> updateFactoryCallback)
  21. {
  22. _treeLock.AcquireWriterLock(Timeout.Infinite);
  23. bool result = _tree.AddOrUpdate(address, address + size, value, updateFactoryCallback);
  24. _treeLock.ReleaseWriterLock();
  25. return result;
  26. }
  27. public T GetOrAdd(ulong address, ulong size, T value)
  28. {
  29. _treeLock.AcquireWriterLock(Timeout.Infinite);
  30. value = _tree.GetOrAdd(address, address + size, value);
  31. _treeLock.ReleaseWriterLock();
  32. return value;
  33. }
  34. public bool Remove(ulong address)
  35. {
  36. _treeLock.AcquireWriterLock(Timeout.Infinite);
  37. bool removed = _tree.Remove(address) != 0;
  38. _treeLock.ReleaseWriterLock();
  39. return removed;
  40. }
  41. public void Clear()
  42. {
  43. _treeLock.AcquireWriterLock(Timeout.Infinite);
  44. _tree.Clear();
  45. _treeLock.ReleaseWriterLock();
  46. }
  47. public bool ContainsKey(ulong address)
  48. {
  49. _treeLock.AcquireReaderLock(Timeout.Infinite);
  50. bool result = _tree.ContainsKey(address);
  51. _treeLock.ReleaseReaderLock();
  52. return result;
  53. }
  54. public bool TryGetValue(ulong address, out T value)
  55. {
  56. _treeLock.AcquireReaderLock(Timeout.Infinite);
  57. bool result = _tree.TryGet(address, out value);
  58. _treeLock.ReleaseReaderLock();
  59. return result;
  60. }
  61. public int GetOverlaps(ulong address, ulong size, ref ulong[] overlaps)
  62. {
  63. _treeLock.AcquireReaderLock(Timeout.Infinite);
  64. int count = _tree.Get(address, address + size, ref overlaps);
  65. _treeLock.ReleaseReaderLock();
  66. return count;
  67. }
  68. public List<T> AsList()
  69. {
  70. _treeLock.AcquireReaderLock(Timeout.Infinite);
  71. List<T> list = _tree.AsList();
  72. _treeLock.ReleaseReaderLock();
  73. return list;
  74. }
  75. }
  76. }