//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// CommonHelpers satellite library | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#nullable enable
using System;
using System.Collections.Generic;

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

//**************************************************************************************************
/// <summary>
/// List manipulation
/// </summary>
public static class HList {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/// <exception cref="ArgumentNullException" />
public static T? FirstOrNull<T>(IList<T> list)
where T: class =>
   FirstOrDefaultUnsafe( list );
/// <exception cref="ArgumentNullException" />
public static T? FirstOrNullV<T>(IList<T> list)
where T: struct =>
   FirstOrDefaultUnsafe( list );

/// <exception cref="ArgumentNullException" />
public static T? SecondOrNull<T>(IList<T> list)
where T: class =>
   SecondOrDefaultUnsafe( list );
/// <exception cref="ArgumentNullException" />
public static T? SecondOrNullV<T>(IList<T> list)
where T: struct =>
   SecondOrDefaultUnsafe( list );

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

/// <exception cref="ArgumentNullException" />
public static T? LastOrNull<T>(IList<T> list)
where T: class =>
   LastOrDefaultUnsafe( list );
/// <exception cref="ArgumentNullException" />
public static T? LastOrNullV<T>(IList<T> list)
where T: struct =>
   LastOrDefaultUnsafe( list );

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

/// <exception cref="ArgumentNullException" />
static T FirstOrDefaultUnsafe<T>(IList<T> list)
{
   HArgChecking.VerifyNotNull( list );
   return list.Count > 0 ? list[0] : default(T)!;
}

/// <exception cref="ArgumentNullException" />
static T SecondOrDefaultUnsafe<T>(IList<T> list)
{
   HArgChecking.VerifyNotNull( list );
   return list.Count > 1 ? list[1] : default(T)!;
}

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

/// <exception cref="ArgumentNullException" />
static T LastOrDefaultUnsafe<T>(IList<T> list)
{
   HArgChecking.VerifyNotNull( list );
   int count = list.Count;
   return count > 0 ? list[count-1] : default(T)!;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // HList
//**************************************************************************************************

} // CommonHelpers (.WASM)
