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

#if !WASM
namespace CommonHelpers {
#else
namespace CommonHelpers.WASM {
#endif

//**************************************************************************************************
partial class HDisposable {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

public static void Dispose<T>([HOptional] ref T instance) where T: IDisposable
{
   if (instance==null)
      return;
   var disposable = instance;
   instance = default(T);
   disposable.Dispose();
}

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

public static bool TryDispose([HOptional] IDisposable instance) =>
   instance == null || HOps.Try(() => Dispose( instance ));

public static bool TryDispose<T>([HOptional] ref T instance) where T: IDisposable =>
   instance == null || TryDispose( HOps.Exchange( ref instance, default(T) ) );

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

/// <exception cref="ArgumentNullException" />
public static bool Using([HOptional] IDisposable instance,Action body)
{
   HArgChecking.VerifyNotNull( body );
   if ( instance == null )
      return false;
   try { body(); }
   finally { instance.Dispose(); }
   return true;
}

/// <exception cref="ArgumentNullException" />
public static async Task<bool> Using_A( [HOptional] IDisposable instance,
                                        Func<Task> bodyA )
{
   HArgChecking.VerifyNotNull( bodyA );
   if ( instance == null )
      return false;
   try { await bodyA(); }
   finally { instance.Dispose(); }
   return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // HDisposable
//**************************************************************************************************

} // CommonHelpers (.WASM)
