using System.Collections.Generic; using System.Linq; namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { /// A watcher which detects changes to a collection of values using a specified instance. /// The value type within the collection. internal class ComparableListWatcher : BaseDisposableWatcher, ICollectionWatcher { /********* ** Fields *********/ /// The collection to watch. private readonly ICollection CurrentValues; /// The values during the previous update. private HashSet LastValues; /// The pairs added since the last reset. private readonly List AddedImpl = new(); /// The pairs removed since the last reset. private readonly List RemovedImpl = new(); /********* ** Accessors *********/ /// public string Name { get; } /// public bool IsChanged => this.AddedImpl.Count > 0 || this.RemovedImpl.Count > 0; /// public IEnumerable Added => this.AddedImpl; /// public IEnumerable Removed => this.RemovedImpl; /********* ** Public methods *********/ /// Construct an instance. /// A name which identifies what the watcher is watching, used for troubleshooting. /// The collection to watch. /// The equality comparer which indicates whether two values are the same. public ComparableListWatcher(string name, ICollection values, IEqualityComparer comparer) { this.Name = name; this.CurrentValues = values; this.LastValues = new HashSet(comparer); } /// public void Update() { this.AssertNotDisposed(); // optimize for zero items if (this.CurrentValues.Count == 0) { if (this.LastValues.Count > 0) { this.AddedImpl.AddRange(this.LastValues); this.LastValues.Clear(); } return; } // detect changes HashSet curValues = new HashSet(this.CurrentValues, this.LastValues.Comparer); this.RemovedImpl.AddRange(from value in this.LastValues where !curValues.Contains(value) select value); this.AddedImpl.AddRange(from value in curValues where !this.LastValues.Contains(value) select value); this.LastValues = curValues; } /// public void Reset() { this.AssertNotDisposed(); this.AddedImpl.Clear(); this.RemovedImpl.Clear(); } } }