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