55 lines
1.8 KiB
C#
55 lines
1.8 KiB
C#
using InnovEnergy.Lib.Utils;
|
|
|
|
namespace InnovEnergy.Lib.Protocols.Modbus.Util;
|
|
|
|
public static class ArraySegmentExtensions
|
|
{
|
|
public static ArraySegment<T> ToArraySegment<T>(this IEnumerable<T> enumerable) => enumerable switch
|
|
{
|
|
ArraySegment<T> ars => ars,
|
|
IReadOnlyList<T> rol => rol.ToArray(),
|
|
_ => enumerable.ToArray()
|
|
};
|
|
|
|
public static ArraySegment<T> Skip<T>(this ArraySegment<T> seg, Int32 count)
|
|
{
|
|
var skip = Math.Min(count, seg.Count);
|
|
var take = seg.Count - skip;
|
|
|
|
return new ArraySegment<T>(seg.Array!,seg.Offset+skip, take);
|
|
}
|
|
|
|
public static ArraySegment<T> Take<T>(this ArraySegment<T> seg, Int32 count)
|
|
{
|
|
var take = Math.Min(count, seg.Count);
|
|
return new ArraySegment<T>(seg.Array!, seg.Offset, take);
|
|
}
|
|
|
|
public static ArraySegment<T> SkipLast<T>(this ArraySegment<T> seg, Int32 count)
|
|
{
|
|
var take = Math.Max(seg.Count - count, 0);
|
|
return new ArraySegment<T>(seg.Array!, seg.Offset, take);
|
|
}
|
|
|
|
public static ArraySegment<T> SkipWhile<T>(this ArraySegment<T> seg, Func<T,Boolean> predicate)
|
|
{
|
|
var skip = Enumerable.TakeWhile(seg, predicate).Count();
|
|
var take = seg.Count - skip;
|
|
return new ArraySegment<T>(seg.Array!, seg.Offset, take);
|
|
}
|
|
|
|
public static ArraySegment<T> TakeWhile<T>(this ArraySegment<T> seg, Func<T,Boolean> predicate)
|
|
{
|
|
var take = Enumerable.TakeWhile(seg, predicate).Count();
|
|
return new ArraySegment<T>(seg.Array!, seg.Offset, take);
|
|
}
|
|
|
|
|
|
public static ArraySegment<T> TakeLast<T>(this ArraySegment<T> seg, Int32 count)
|
|
{
|
|
var skip = Math.Max(seg.Count - count, 0);
|
|
var take = seg.Count - skip;
|
|
|
|
return new ArraySegment<T>(seg.Array!, seg.Offset+skip, take);
|
|
}
|
|
} |