0.2.0-dev Download ZIP
43 lines ·1.4 KB Raw
| 1 | using System.Buffers.Binary; |
| 2 | using System.Text; |
| 3 | |
| 4 | namespace EvilEngine.Adapters.EaPegasus; |
| 5 | |
| 6 | internal static class BigEndian |
| 7 | { |
| 8 | public static ReadOnlySpan<byte> Slice(ReadOnlySpan<byte> data, long at, long length, string what) |
| 9 | { |
| 10 | return at >= 0 && length >= 0 && at <= data.Length - length |
| 11 | ? data.Slice((int)at, (int)length) |
| 12 | : throw new InvalidDataException($"{what} at 0x{at:X} runs past the end ({data.Length} bytes)"); |
| 13 | } |
| 14 | |
| 15 | public static ushort U16(ReadOnlySpan<byte> data, long at, string what) |
| 16 | { |
| 17 | return BinaryPrimitives.ReadUInt16BigEndian(Slice(data, at, 2, what)); |
| 18 | } |
| 19 | |
| 20 | public static uint U32(ReadOnlySpan<byte> data, long at, string what) |
| 21 | { |
| 22 | return BinaryPrimitives.ReadUInt32BigEndian(Slice(data, at, 4, what)); |
| 23 | } |
| 24 | |
| 25 | public static ulong U64(ReadOnlySpan<byte> data, long at, string what) |
| 26 | { |
| 27 | return BinaryPrimitives.ReadUInt64BigEndian(Slice(data, at, 8, what)); |
| 28 | } |
| 29 | |
| 30 | public static string Text(ReadOnlySpan<byte> data, long at, string what) |
| 31 | { |
| 32 | var rest = Slice(data, at, data.Length - at, what); |
| 33 | var end = rest.IndexOf((byte)0); |
| 34 | return end >= 0 |
| 35 | ? Encoding.UTF8.GetString(rest[..end]) |
| 36 | : throw new InvalidDataException($"{what} at 0x{at:X} is never terminated"); |
| 37 | } |
| 38 | |
| 39 | public static long Align(long value, long alignment) |
| 40 | { |
| 41 | return (value + alignment - 1) & ~(alignment - 1); |
| 42 | } |
| 43 | } |