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

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

static partial class ops {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public static bool Try( Action action )
{
   try { action(); return true; }
   catch { return false; }
}

public static bool Try( out Exception? error, Action action )
{
   try { action(); }
   catch ( Exception e )
      { error = e; return false; }
   error = null; return true;
}

public static bool TryAgain( ref Exception? error, Action action )
{
   try { action(); }
   catch ( Exception e ) {
      if ( error != null )
         error = e;
      return false;
   }
   return true;
}

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

public static R? Try<R>( Func<R> function )
{
   try { return function(); }
   catch { return default; }
}

public static R? Try<R>( out Exception? error, Func<R> function )
{
   R rslt;
   try { rslt = function(); }
   catch ( Exception e )
      { error = e; return default; }
   error = null;
   return rslt;
}

public static R? TryAgain<R>( ref Exception? error, Func<R> function )
{
   try { return function(); }
   catch ( Exception e ) {
      error ??= e;
      return default;
   }
}

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

public static async Task<bool> Try_A( Func<Task> actionA )
{
   try {
      await actionA().ConfigureAwait(false);
      return true;
   }
   catch {
      return false;
   }
}

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

public static async Task<R?> Try_A<R>( Func<Task<R>> functionA )
{
   try {
      return await functionA().ConfigureAwait(false);
   }
   catch {
      return default;
   }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // ops

} // user_rtx (.wasm)
