using System; using System.Collections.Generic; namespace Semmle.Extraction.CIL { /// /// A factory and a cache for mapping source entities to target entities. /// Could be considered as a memoizer. /// /// The type of the source. /// The type of the generated object. public class CachedFunction { readonly Func generator; readonly Dictionary cache; /// /// Initializes the factory with a given mapping. /// /// The mapping. public CachedFunction(Func g) { generator = g; cache = new Dictionary(); } /// /// Gets the target for a given source. /// Create it if it does not exist. /// /// The source object. /// The created object. public TargetType this[SrcType src] { get { TargetType result; if (!cache.TryGetValue(src, out result)) { result = generator(src); cache[src] = result; } return result; } } } /// /// A factory for mapping a pair of source entities to a target entity. /// /// Source entity type 1. /// Source entity type 2. /// The target type. public class CachedFunction { readonly CachedFunction<(Src1, Src2), Target> factory; /// /// Initializes the factory with a given mapping. /// /// The mapping. public CachedFunction(Func g) { factory = new CachedFunction<(Src1, Src2), Target>(p => g(p.Item1, p.Item2)); } public Target this[Src1 s1, Src2 s2] => factory[(s1, s2)]; } }