Skip to content
0.2.0-dev Download ZIP
74 lines ·1.8 KB Raw
1using System.Buffers.Binary;
2using System.Text;
3using EvilEngine.Mounts;
4
5namespace EvilEngine.Adapters.Unreal;
6
7internal ref struct UnrealReader(ReadOnlySpan<byte> data, string location)
8{
9 private readonly ReadOnlySpan<byte> _data = data;
10
11 public int Position { get; set; }
12
13 public readonly int Remaining => _data.Length - Position;
14
15 public ReadOnlySpan<byte> Bytes(int count)
16 {
17 if (count < 0 || count > Remaining)
18 throw new MountException(
19 $"'{location}' runs out of bytes reading {count} at {Position} of {_data.Length}.");
20 var bytes = _data.Slice(Position, count);
21 Position += count;
22 return bytes;
23 }
24
25 public byte U8()
26 {
27 return Bytes(1)[0];
28 }
29
30 public int I32()
31 {
32 return BinaryPrimitives.ReadInt32LittleEndian(Bytes(4));
33 }
34
35 public uint U32()
36 {
37 return BinaryPrimitives.ReadUInt32LittleEndian(Bytes(4));
38 }
39
40 public long I64()
41 {
42 return BinaryPrimitives.ReadInt64LittleEndian(Bytes(8));
43 }
44
45 public ulong U64()
46 {
47 return BinaryPrimitives.ReadUInt64LittleEndian(Bytes(8));
48 }
49
50 public bool Flag()
51 {
52 return I32() != 0;
53 }
54
55 public int Count(int size)
56 {
57 var count = I32();
58 if (count < 0 || (long)count * size > Remaining)
59 throw new MountException(
60 $"'{location}' lists {count} records of {size} bytes at {Position - 4}, past its end.");
61 return count;
62 }
63
64 public string FString()
65 {
66 var length = I32();
67 if (length == 0)
68 return "";
69 var text = length < 0
70 ? Encoding.Unicode.GetString(Bytes(checked(-length * 2)))
71 : Encoding.Latin1.GetString(Bytes(length));
72 return text.TrimEnd('\0');
73 }
74}