using System; using System.Collections.Generic; namespace PkmnLibSharp.Utilities { /// /// Helper class to ensure an object is disposed when it goes out of scope. /// /// public class ScopedOwner : IDisposable where T : PointerWrapper { public T? Value { get; private set; } public ScopedOwner(T value) { Value = value; } public T? TakeOwnership() { var val = Value; Value = null; return val; } ~ScopedOwner() { if (Value != null) Value.Dispose(); } public static implicit operator T?(ScopedOwner val) => val.Value; public override string ToString() { if (Value == null) return "null"; return Value.ToString(); } public void Dispose() { if (Value != null) Value.Dispose(); Value = null; } protected bool Equals(ScopedOwner other) { return EqualityComparer.Default.Equals(Value, other.Value); } public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((ScopedOwner) obj); } public override int GetHashCode() { return EqualityComparer.Default.GetHashCode(Value); } public static bool operator ==(ScopedOwner? left, ScopedOwner? right) { return Equals(left, right); } public static bool operator !=(ScopedOwner? left, ScopedOwner? right) { return !Equals(left, right); } } }