using System.Collections.Generic; using Netcode; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { /// A watcher which detects changes to a net dictionary field. /// The dictionary key type. /// The dictionary value type. /// The net type equivalent to . /// The serializable dictionary type that can store the keys and values. /// The net field instance type. internal class NetDictionaryWatcher : BaseDisposableWatcher, IDictionaryWatcher where TKey : notnull where TField : class, INetObject, new() where TSerialDict : IDictionary, new() where TSelf : NetDictionary { /********* ** Fields *********/ /// The pairs added since the last reset. private readonly IDictionary PairsAdded = new Dictionary(); /// The pairs removed since the last reset. private readonly IDictionary PairsRemoved = new Dictionary(); /// The field being watched. private readonly NetDictionary Field; /********* ** Accessors *********/ /// public string Name { get; } /// public bool IsChanged => this.PairsAdded.Count > 0 || this.PairsRemoved.Count > 0; /// public IEnumerable> Added => this.PairsAdded; /// public IEnumerable> Removed => this.PairsRemoved; /********* ** Public methods *********/ /// Construct an instance. /// A name which identifies what the watcher is watching, used for troubleshooting. /// The field to watch. public NetDictionaryWatcher(string name, NetDictionary field) { this.Name = name; this.Field = field; field.OnValueAdded += this.OnValueAdded; field.OnValueRemoved += this.OnValueRemoved; } /// public void Update() { this.AssertNotDisposed(); } /// public void Reset() { this.AssertNotDisposed(); this.PairsAdded.Clear(); this.PairsRemoved.Clear(); } /// public override void Dispose() { if (!this.IsDisposed) { this.Field.OnValueAdded -= this.OnValueAdded; this.Field.OnValueRemoved -= this.OnValueRemoved; } base.Dispose(); } /********* ** Private methods *********/ /// A callback invoked when an entry is added to the dictionary. /// The entry key. /// The entry value. private void OnValueAdded(TKey key, TValue value) { this.PairsAdded[key] = value; } /// A callback invoked when an entry is removed from the dictionary. /// The entry key. /// The entry value. private void OnValueRemoved(TKey key, TValue value) { if (!this.PairsRemoved.ContainsKey(key)) this.PairsRemoved[key] = value; } } }