using System;
using System.Collections;
using System.Collections.Generic;
namespace StardewModdingAPI.Framework.Utilities
{
/// A wrapper meant for tracking recursive contexts.
/// The key type.
internal class ContextHash : HashSet
{
/*********
** Public methods
*********/
/// Construct an instance.
public ContextHash() { }
/// Construct an instance.
/// The implementation to use when comparing values in the set, or null to use the default comparer for the set type.
public ContextHash(IEqualityComparer comparer)
: base(comparer) { }
/// Add a key while an action is in progress, and remove it when it completes.
/// The key to add.
/// The action to perform.
/// The specified key is already added.
public void Track(T key, Action action)
{
if(this.Contains(key))
throw new InvalidOperationException($"Can't track context for key {key} because it's already added.");
this.Add(key);
try
{
action();
}
finally
{
this.Remove(key);
}
}
/// Add a key while an action is in progress, and remove it when it completes.
/// The value type returned by the method.
/// The key to add.
/// The action to perform.
public TResult Track(T key, Func action)
{
if (this.Contains(key))
throw new InvalidOperationException($"Can't track context for key {key} because it's already added.");
this.Add(key);
try
{
return action();
}
finally
{
this.Remove(key);
}
}
}
}