PKHeX/PKHeX.Core/PKM/HOME/HomeOptional1.cs
Kurt e265c18fa2 Span-ify HOME data structures
Much easier to read.
Optionals no longer store the 3-byte header in their memory reference.
If they were smart, they could track per-game visitation date/time in a future header format...

Fixes adding new side-formats and an updated header not writing the first time.
Fixes GameDataPK8.CopyTo where PokeJob data copies from the wrong segment
2023-05-09 19:13:58 -07:00

41 lines
1.3 KiB
C#

using System;
using static System.Buffers.Binary.BinaryPrimitives;
namespace PKHeX.Core;
/// <summary>
/// Side game data base class for <see cref="PKM"/> data transferred into HOME.
/// </summary>
public abstract class HomeOptional1
{
// Internal Attributes set on creation
private readonly Memory<byte> Buffer; // Raw Storage
protected Span<byte> Data => Buffer.Span;
public const int HeaderSize = 3; // u8 format, u16 length(data[u8])
protected abstract HomeGameDataFormat Format { get; }
protected HomeOptional1(ushort size) => Buffer = new byte[size];
protected HomeOptional1(Memory<byte> buffer) => Buffer = buffer;
protected void EnsureSize(int size)
{
if (Buffer.Length != size)
throw new ArgumentOutOfRangeException(nameof(size), size, $"Expected size {Buffer.Length} but received {size}.");
}
protected byte[] ToArray() => Data.ToArray();
protected int WriteWithHeader(Span<byte> result)
{
result[0] = (byte)Format;
WriteUInt16LittleEndian(result[1..], (ushort)Data.Length);
return HeaderSize + WriteWithoutHeader(result[HeaderSize..]);
}
private int WriteWithoutHeader(Span<byte> result)
{
var span = Data;
span.CopyTo(result);
return span.Length;
}
}