0.2.0-dev Download ZIP
71 lines ·2.1 KB Raw
| 1 | using System.Buffers.Binary; |
| 2 | using System.IO.Hashing; |
| 3 | using System.Text; |
| 4 | |
| 5 | namespace EvilEngine.Adapters.Tests.Support; |
| 6 | |
| 7 | public sealed class GmaWriter(byte version = 3) |
| 8 | { |
| 9 | private readonly List<(string Name, byte[] Data)> _entries = []; |
| 10 | |
| 11 | public GmaWriter Add(string name, byte[] data) |
| 12 | { |
| 13 | _entries.Add((name, data)); |
| 14 | return this; |
| 15 | } |
| 16 | |
| 17 | public GmaWriter Add(string name, string text) |
| 18 | { |
| 19 | return Add(name, Encoding.UTF8.GetBytes(text)); |
| 20 | } |
| 21 | |
| 22 | public byte[] Build(string title = "Evil Addon", |
| 23 | string description = "{\"description\":\"\",\"type\":\"tool\",\"tags\":[\"fun\"]}", string author = "syhgma", |
| 24 | ulong timestamp = 1_761_782_400) |
| 25 | { |
| 26 | using var output = new MemoryStream(); |
| 27 | output.Write("GMAD"u8); |
| 28 | output.WriteByte(version); |
| 29 | UInt64(output, 0); |
| 30 | UInt64(output, timestamp); |
| 31 | if (version > 1) |
| 32 | output.WriteByte(0); |
| 33 | Text(output, title); |
| 34 | Text(output, description); |
| 35 | Text(output, author); |
| 36 | UInt32(output, 1); |
| 37 | for (var i = 0; i < _entries.Count; i++) |
| 38 | { |
| 39 | UInt32(output, (uint)i + 1); |
| 40 | Text(output, _entries[i].Name); |
| 41 | UInt64(output, (ulong)_entries[i].Data.LongLength); |
| 42 | UInt32(output, Crc32.HashToUInt32(_entries[i].Data)); |
| 43 | } |
| 44 | |
| 45 | UInt32(output, 0); |
| 46 | foreach (var (_, data) in _entries) |
| 47 | output.Write(data); |
| 48 | UInt32(output, Crc32.HashToUInt32(output.ToArray())); |
| 49 | return output.ToArray(); |
| 50 | } |
| 51 | |
| 52 | private static void Text(Stream stream, string text) |
| 53 | { |
| 54 | stream.Write(Encoding.UTF8.GetBytes(text)); |
| 55 | stream.WriteByte(0); |
| 56 | } |
| 57 | |
| 58 | private static void UInt32(Stream stream, uint value) |
| 59 | { |
| 60 | Span<byte> bytes = stackalloc byte[4]; |
| 61 | BinaryPrimitives.WriteUInt32LittleEndian(bytes, value); |
| 62 | stream.Write(bytes); |
| 63 | } |
| 64 | |
| 65 | private static void UInt64(Stream stream, ulong value) |
| 66 | { |
| 67 | Span<byte> bytes = stackalloc byte[8]; |
| 68 | BinaryPrimitives.WriteUInt64LittleEndian(bytes, value); |
| 69 | stream.Write(bytes); |
| 70 | } |
| 71 | } |