//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// UserRTX.NET satellite library | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Text;
using System.Threading.Tasks;

#if !WASM
namespace user_rtx { using u = user_rtx;
#else
namespace user_rtx.wasm { using u = user_rtx.wasm;
#endif

/// <summary>
/// Disposable helpers
/// </summary>
public static class disposable {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public static void Dispose( [u.opt] IDisposable? instance )
{
   if ( instance != null )
      instance.Dispose();
}

public static void Free<T>( [u.opt] ref T? instance )
where T: class, IDisposable
{
   if ( instance != null ) {
      var disp = instance;
      instance = null;
      disp.Dispose();
   }
}

public static bool DisposeIfDisposable( object instance )
{
   var disposable = instance as IDisposable;
   disposable?.Dispose();
   return disposable != null;
}

//--------------------------------------------------------------------------------------------------

public static bool TryDispose( [u.opt] IDisposable? instance ) =>
   instance == null || u.ops.Try(() => Dispose( instance ));

public static bool TryFree<T>( [u.opt] ref T? instance )
where T: class, IDisposable =>
   instance == null || TryDispose( u.ops.NullExchange( ref instance ) );

//==================================================================================================

public static bool Using( [u.opt] IDisposable? instance, Action action )
{
   if ( instance == null )
      return false;
   try { action(); }
   finally { instance.Dispose(); }
   return true;
}

public static async Task<bool> Using_A( [u.opt] IDisposable? instance,
                                        Func<Task> actionA )
{
   if ( instance == null )
      return false;
   try { await actionA(); }
   finally { instance.Dispose(); }
   return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // disposable

} // user_rtx (.wasm)
