using System; namespace OpenMacroBoard.SDK.Internals { internal static class ConstrainedContext { /// /// Creates a context which might depend on the provided item or a clone of that item. /// /// /// This is useful in situation where you only want to do an expensive operation /// for types when needed. The /// makes sure that elements that depend on the parent (borrow, no copy) will not be disposed /// but cloned (owned copies) will be disposed. /// /// Input type. /// Output type. public static ConditionalDisposable For( TInput item, Func borrow, Func ownedCopy ) where TInput : class, IDisposable where TOutput : class, IDisposable { var borrowedResult = borrow(item); if (borrowedResult is not null) { return new ConditionalDisposable(borrowedResult, false); } var ownedResult = ownedCopy(item); return new ConditionalDisposable(ownedResult, true); } } }