Adds ScopedOwner class, that disposes owned values when garbage collected.
parent
7e31bba05e
commit
7807ee9676
Binary file not shown.
Binary file not shown.
@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace PkmnLibSharp.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class to ensure an object is disposed when it goes out of scope.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ScopedOwner<T> : 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<T> 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<T> other)
|
||||
{
|
||||
return EqualityComparer<T?>.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<T>) obj);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return EqualityComparer<T?>.Default.GetHashCode(Value);
|
||||
}
|
||||
|
||||
public static bool operator ==(ScopedOwner<T>? left, ScopedOwner<T>? right)
|
||||
{
|
||||
return Equals(left, right);
|
||||
}
|
||||
|
||||
public static bool operator !=(ScopedOwner<T>? left, ScopedOwner<T>? right)
|
||||
{
|
||||
return !Equals(left, right);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue