using System.Buffers.Binary; using System.Text; namespace EvilEngine.Adapters.EaPegasus; internal static class BigEndian { public static ReadOnlySpan Slice(ReadOnlySpan data, long at, long length, string what) { return at >= 0 && length >= 0 && at <= data.Length - length ? data.Slice((int)at, (int)length) : throw new InvalidDataException($"{what} at 0x{at:X} runs past the end ({data.Length} bytes)"); } public static ushort U16(ReadOnlySpan data, long at, string what) { return BinaryPrimitives.ReadUInt16BigEndian(Slice(data, at, 2, what)); } public static uint U32(ReadOnlySpan data, long at, string what) { return BinaryPrimitives.ReadUInt32BigEndian(Slice(data, at, 4, what)); } public static ulong U64(ReadOnlySpan data, long at, string what) { return BinaryPrimitives.ReadUInt64BigEndian(Slice(data, at, 8, what)); } public static string Text(ReadOnlySpan data, long at, string what) { var rest = Slice(data, at, data.Length - at, what); var end = rest.IndexOf((byte)0); return end >= 0 ? Encoding.UTF8.GetString(rest[..end]) : throw new InvalidDataException($"{what} at 0x{at:X} is never terminated"); } public static long Align(long value, long alignment) { return (value + alignment - 1) & ~(alignment - 1); } }