using System; using System.Collections; using System.Collections.Generic; namespace CC_Functions.AspNet { /// /// Provides synchronizing for dictionaries with saving/loading backends /// /// The key type /// The param type public abstract class SaveLoadDict : IDictionary { /// public IEnumerator> GetEnumerator() { lock (this) return Load().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { lock (this) return GetEnumerator(); } /// public void Add(KeyValuePair item) { lock (this) Add(item.Key, item.Value); } /// public void Clear() { lock (this) Save(new Dictionary()); } /// public bool Contains(KeyValuePair item) { lock (this) return Load().Contains(item); } /// public void CopyTo(KeyValuePair[] array, int arrayIndex) { lock (this) Load().CopyTo(array, arrayIndex); } /// public bool Remove(KeyValuePair item) { lock (this) { IDictionary dictionary = Load(); try { return dictionary.Remove(item); } finally { Save(dictionary); } } } /// public int Count { get { lock (this) return Load().Count; } } /// public bool IsReadOnly => false; /// public void Add(T key, U value) { lock (this) { IDictionary dictionary = Load(); dictionary.Add(key, value); Save(dictionary); } } /// public bool ContainsKey(T key) { lock (this) return Load().ContainsKey(key); } /// public bool Remove(T key) { lock (this) { IDictionary dictionary = Load(); try { return dictionary.Remove(key); } finally { Save(dictionary); } } } /// public bool TryGetValue(T key, out U value) { lock (this) return Load().TryGetValue(key, out value); } /// public U this[T key] { get { lock (this) return Load()[key]; } set { lock (this) { IDictionary dictionary = Load(); dictionary[key] = value; Save(dictionary); } } } /// public ICollection Keys { get { lock (this) return Load().Keys; } } /// public ICollection Values { get { lock (this) return Load().Values; } } /// /// Replace the current content based on the current state /// /// Function to mutate the content public void Mutate(Func, IDictionary> f) { lock (this) Save(f(Load())); } /// /// Save the dictionary content /// /// Dictionary content to save protected abstract void Save(IDictionary v); /// /// Load the content to a dictionary /// /// The loaded content protected abstract IDictionary Load(); } }