Innovenergy_trunk/csharp/Lib/Protocols/Modbus/Util/ArraySegmentExtensions.cs

57 lines
1.9 KiB
C#

namespace InnovEnergy.Lib.Protocols.Modbus.Util;
public static class ArraySegmentExtensions
{
public static ArraySegment<T> ToArraySegment<T>(this IEnumerable<T> enumerable)
{
if (enumerable is T[] array)
return new ArraySegment<T>(array);
if (enumerable is ArraySegment<T> arraySegment)
return arraySegment; // already an ArraySegment, doh!
return new ArraySegment<T>(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);
}
}