PKHeX/PKHeX.Core/PKM/Util/EntityFileNamer.cs
Kurt 47071b41f3
Refactoring: Span-based value writes and method signatures (#3361)
Existing `get`/`set` logic is flawed in that it doesn't work on Big Endian operating systems, and it allocates heap objects when it doesn't need to.

`System.Buffers.Binary.BinaryPrimitives` in the `System.Memory` NuGet package provides both Little Endian and Big Endian methods to read and write data; all the `get`/`set` operations have been reworked to use this new API. This removes the need for PKHeX's manual `BigEndian` class, as all functions are already covered by the BinaryPrimitives API.

The `StringConverter` has now been rewritten to accept a Span to read from & write to, no longer requiring a temporary StringBuilder.

Other Fixes included:
- The Super Training UI for Gen6 has been reworked according to the latest block structure additions.
- Cloning a Stadium2 Save File now works correctly (opening from the Folder browser list).
- Checksum & Sanity properties removed from parent PKM class, and is now implemented via interface.
2022-01-02 21:35:59 -08:00

54 lines
1.9 KiB
C#

namespace PKHeX.Core
{
public static class EntityFileNamer
{
/// <summary>
/// Object that converts the <see cref="PKM"/> data into a <see cref="string"/> file name.
/// </summary>
public static IFileNamer<PKM> Namer { get; set; } = new DefaultEntityNamer();
/// <summary>
/// Gets the file name (without extension) for the input <see cref="pk"/> data.
/// </summary>
/// <param name="pk">Input entity to create a file name for.</param>
/// <returns>File name for the <see cref="pk"/> data</returns>
public static string GetName(PKM pk) => Namer.GetName(pk);
}
public sealed class DefaultEntityNamer : IFileNamer<PKM>
{
public string GetName(PKM obj)
{
if (obj is GBPKM gb)
return GetGBPKM(gb);
return GetRegular(obj);
}
private static string GetRegular(PKM pk)
{
string form = pk.Form > 0 ? $"-{pk.Form:00}" : string.Empty;
string star = pk.IsShiny ? " ★" : string.Empty;
var chk = pk is ISanityChecksum s ? s.Checksum : PokeCrypto.GetCHK(pk.Data, pk.SIZE_STORED);
return $"{pk.Species:000}{form}{star} - {pk.Nickname} - {chk:X4}{pk.EncryptionConstant:X8}";
}
private static string GetGBPKM(GBPKM gb)
{
string form = gb.Form > 0 ? $"-{gb.Form:00}" : string.Empty;
string star = gb.IsShiny ? " ★" : string.Empty;
var raw = gb switch
{
PK1 pk1 => new PokeList1(pk1).Write(),
PK2 pk2 => new PokeList2(pk2).Write(),
_ => gb.Data,
};
var checksum = Checksums.CRC16_CCITT(raw);
return $"{gb.Species:000}{form}{star} - {gb.Nickname} - {checksum:X4}";
}
}
public interface IFileNamer<in T>
{
string GetName(T obj);
}
}