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

55 lines
1.8 KiB
C#
Raw Normal View History

2023-05-04 07:32:35 +00:00
using InnovEnergy.Lib.Utils;
2023-02-16 12:57:06 +00:00
namespace InnovEnergy.Lib.Protocols.Modbus.Util;
public static class ArraySegmentExtensions
{
2023-05-04 07:32:35 +00:00
public static ArraySegment<T> ToArraySegment<T>(this IEnumerable<T> enumerable) => enumerable switch
2023-02-16 12:57:06 +00:00
{
2023-05-04 07:32:35 +00:00
ArraySegment<T> ars => ars,
IReadOnlyList<T> rol => rol.ToArray(),
_ => enumerable.ToArray()
};
2023-02-16 12:57:06 +00:00
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);
}
}