Minor clean

No functional change
This commit is contained in:
Kurt 2024-05-27 10:33:25 -05:00
parent a7421a7ceb
commit ca2bd3baf4
21 changed files with 76 additions and 83 deletions

View file

@ -23,7 +23,7 @@ public sealed class StartupArguments
/// </summary>
public void ReadArguments(IEnumerable<string> args)
{
foreach (string path in args)
foreach (var path in args)
{
var other = FileUtil.GetSupportedFile(path, SAV);
if (other is SaveFile s)

View file

@ -1,4 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
namespace PKHeX.Core;
@ -53,7 +54,7 @@ public static class GameLanguage
/// <summary>
/// Gets a list of strings for the specified language and file type.
/// </summary>
public static string[] GetStrings(string ident, string lang, string type = "text")
public static string[] GetStrings(string ident, string lang, [ConstantExpected] string type = "text")
{
string[] data = Util.GetStringList(ident, lang, type);
if (data.Length == 0)

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace PKHeX.Core;
@ -67,7 +68,10 @@ public sealed class GameStrings : IBasicStrings
Gen2 = new(Get("gsc_00000"));
Gen3 = new(Get("rsefrlg_00000"));
CXD = new(Get("cxd_00000"));
SanitizeMetStringsCXD(CXD.Met0);
// Less than 10% of location values are unique.
// Just mark them with the ID if they aren't empty.
AppendLocationIndex(CXD.Met0.AsSpan(0, 227));
// Current Generation strings
natures = Util.GetNaturesList(l);
@ -132,7 +136,7 @@ public sealed class GameStrings : IBasicStrings
Get("mail4").CopyTo(g4items, 137);
}
private LocationSet4 Get4(string ident)
private LocationSet4 Get4([ConstantExpected] string ident)
{
var met0 = Get($"{ident}_00000");
var met2 = Get($"{ident}_02000");
@ -140,7 +144,7 @@ public sealed class GameStrings : IBasicStrings
return new LocationSet4(met0, met2, met3);
}
private LocationSet6 Get6(string ident)
private LocationSet6 Get6([ConstantExpected] string ident)
{
var met0 = Get($"{ident}_00000");
var met3 = Get($"{ident}_30000");
@ -149,34 +153,32 @@ public sealed class GameStrings : IBasicStrings
return new LocationSet6(met0,met3, met4, met6);
}
private LocationSet6 Get6(string ident, string[] met3, string[] met6)
private LocationSet6 Get6([ConstantExpected] string ident, string[] met3, string[] met6)
{
var met0 = Get($"{ident}_00000");
var met4 = Get($"{ident}_40000");
return new LocationSet6(met0, met3, met4, met6);
}
private string[] GetG3CXD(string[] arr, string fileName)
private string[] GetG3CXD(ReadOnlySpan<string> arr, [ConstantExpected] string fileName)
{
// Concatenate the Gen3 Item list with the CXD item array; CXD items starting at index 500.
var item500 = Get(fileName);
var result = new string[500 + item500.Length];
for (int i = arr.Length; i < result.Length; i++)
result[i] = string.Empty;
arr.CopyTo(result, 0);
arr.CopyTo(result);
item500.CopyTo(result, 500);
return result;
}
private static void SanitizeMetStringsCXD(string[] cxd)
private static void AppendLocationIndex(Span<string> names)
{
// Less than 10% of location values are unique.
// Just mark them with the ID if they aren't empty.
for (int i = 0; i < 227; i++)
for (int i = 0; i < names.Length; i++)
{
ref var str = ref cxd[i];
ref var str = ref names[i];
if (str.Length != 0)
str = $"{str} [{i:000}]";
str += $" [{i:000}]";
}
}
@ -284,7 +286,7 @@ public sealed class GameStrings : IBasicStrings
itemlist[1763] += " (LA)"; // Secret Medicine
}
private static void SanitizeItemsSV(string[] items)
private static void SanitizeItemsSV(Span<string> items)
{
items[2313] += " (1)"; // Academy Bottle
items[2314] += " (2)"; // Academy Bottle
@ -305,7 +307,7 @@ public sealed class GameStrings : IBasicStrings
items[2556] += " (2)"; // Violet Book
}
private static void SanitizeItemsLA(string[] items)
private static void SanitizeItemsLA(Span<string> items)
{
// Recipes
items[1784] += " (~)"; // Gigaton Ball
@ -639,7 +641,7 @@ public sealed class GameStrings : IBasicStrings
// set.Met3[18] += " (-)"; // Pokémon HOME -- duplicate with 40000's entry
}
private static void Deduplicate(string[] arr, int group)
private static void Deduplicate(Span<string> arr, int group)
{
var counts = new Dictionary<string, int>();
@ -704,18 +706,20 @@ public sealed class GameStrings : IBasicStrings
private string[] GetItemStrings9()
{
// in Generation 9, TMs are padded to 3 digits; format them appropriately here
// in Generation 9, TM #'s are padded to 3 digits; format them appropriately here
var clone = (string[])itemlist.Clone();
var span = clone.AsSpan();
var zero = lang is "ja" or "zh" or "zh2" ? "" : "0";
for (int i = 328; i <= 419; i++)
clone[i] = clone[i].Insert(clone[i].Length - 2, zero);
for (int i = 618; i <= 620; i++)
clone[i] = clone[i].Insert(clone[i].Length - 2, zero);
for (int i = 690; i <= 693; i++)
clone[i] = clone[i].Insert(clone[i].Length - 2, zero);
InsertZero(span[328..420], zero); // 01-92
InsertZero(span[618..621], zero); // 93-95
InsertZero(span[690..694], zero); // 96-99
return clone;
static void InsertZero(Span<string> arr, string insert)
{
foreach (ref var str in arr)
str = str.Insert(str.Length - 2, insert);
}
}
private string[] GetItemStrings3(GameVersion game)

View file

@ -1,5 +1,6 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace PKHeX.Core;
@ -18,12 +19,14 @@ public static class EncounterUtil
/// <summary>
/// Gets a raw chunk of data from the specified resource.
/// </summary>
public static ReadOnlySpan<byte> Get([Length(2, 2)] string resource) => Util.GetBinaryResource($"encounter_{resource}.pkl");
public static ReadOnlySpan<byte> Get([Length(2, 2), ConstantExpected] string resource)
=> Util.GetBinaryResource($"encounter_{resource}.pkl");
/// <summary>
/// Gets an index-able accessor for the specified resource.
/// </summary>
public static BinLinkerAccessor Get([Length(2, 2)] string resource, [Length(2, 2)] ReadOnlySpan<byte> ident) => BinLinkerAccessor.Get(Get(resource), ident);
public static BinLinkerAccessor Get([Length(2, 2), ConstantExpected] string resource, [Length(2, 2)] ReadOnlySpan<byte> ident)
=> BinLinkerAccessor.Get(Get(resource), ident);
/// <summary>
/// Grabs the localized names for individual templates for all languages from the specified <see cref="index"/> of the <see cref="names"/> list.

View file

@ -268,11 +268,11 @@ internal static class Encounters8Nest
internal const int Watchtower = 126;
internal const int MaxLair = 244;
internal static readonly EncounterStatic8N[] Nest_SW = GetBase("sw", SW);
internal static readonly EncounterStatic8N[] Nest_SH = GetBase("sh", SH);
internal static readonly EncounterStatic8N[] Nest_SW = GetBase("sw_nest", SW);
internal static readonly EncounterStatic8N[] Nest_SH = GetBase("sh_nest", SH);
internal static readonly EncounterStatic8ND[] Dist_SW = GetDist("sw", SW);
internal static readonly EncounterStatic8ND[] Dist_SH = GetDist("sh", SH);
internal static readonly EncounterStatic8ND[] Dist_SW = GetDist("sw_dist", SW);
internal static readonly EncounterStatic8ND[] Dist_SH = GetDist("sh_dist", SH);
internal static readonly EncounterStatic8U[] DynAdv_SWSH = GetUnderground();
@ -293,9 +293,9 @@ internal static class Encounters8Nest
new(SWSH) { Species = 133, Level = 25, Ability = A2, IVs = new(31,31,31,-1,-1,-1), DynamaxLevel = 5, Moves = new(606,273,038,129), CanGigantamax = true }, // ★Sgr7194 Gigantamax Eevee
];
private static EncounterStatic8N[] GetBase([Length(2, 2)] string name, [ConstantExpected] GameVersion game)
private static EncounterStatic8N[] GetBase([Length(2, 2), ConstantExpected] string name, [ConstantExpected] GameVersion game)
{
var data = EncounterUtil.Get($"{name}_nest");
var data = EncounterUtil.Get(name);
const int size = 10;
var result = new EncounterStatic8N[data.Length / size];
@ -308,9 +308,9 @@ internal static class Encounters8Nest
return result;
}
private static EncounterStatic8ND[] GetDist([Length(2, 2)] string name, [ConstantExpected] GameVersion game)
private static EncounterStatic8ND[] GetDist([Length(2, 2), ConstantExpected] string name, [ConstantExpected] GameVersion game)
{
var data = EncounterUtil.Get($"{name}_dist");
var data = EncounterUtil.Get(name);
const int size = 0x10;
var result = new EncounterStatic8ND[data.Length / size];

View file

@ -255,7 +255,7 @@ public sealed class NicknameVerifier : Verifier
ushort species = pk.Species;
byte format = pk.Format;
int language = pk.Language;
var expect = SpeciesName.GetSpeciesNameGeneration(species, language, format);
ReadOnlySpan<char> expect = SpeciesName.GetSpeciesNameGeneration(species, language, format);
if (nickname.SequenceEqual(expect))
return true;
@ -283,7 +283,7 @@ public sealed class NicknameVerifier : Verifier
return false;
}
private static bool IsMatch45(ReadOnlySpan<char> nickname, ushort species, string expect, int language, bool canHaveAnyLanguage)
private static bool IsMatch45(ReadOnlySpan<char> nickname, ushort species, ReadOnlySpan<char> expect, int language, bool canHaveAnyLanguage)
{
if (species is (int)Species.Farfetchd)
{
@ -302,7 +302,7 @@ public sealed class NicknameVerifier : Verifier
return nickname.SequenceEqual(expect);
}
private static bool IsMatchUpper45(ReadOnlySpan<char> nickname, string expect)
private static bool IsMatchUpper45(ReadOnlySpan<char> nickname, ReadOnlySpan<char> expect)
{
for (int i = 0; i < expect.Length; i++)
{

View file

@ -1,3 +1,4 @@
namespace PKHeX.Core;
/// <summary>
/// Exposes information about the level the Pokémon was obtained.

View file

@ -1007,7 +1007,7 @@ public abstract class PKM : ISpeciesForm, ITrainerID32, IGeneration, IShiny, ILa
// Transfer properties in the order they are defined in the destination PKM format for best conversion
var shared = destProperties.Intersect(srcProperties);
foreach (string property in shared)
foreach (var property in shared)
{
// Setter sanity check: a derived type may not implement a setter if its parent type has one.
if (!BatchEditing.TryGetHasProperty(result, property, out var pi))

View file

@ -301,7 +301,7 @@ public static class EntityConverter
return false;
}
}
if (IsIncompatibleGB(target, target.Japanese, pk.Japanese))
if (!IsCompatibleGB(target, target.Japanese, pk.Japanese))
{
converted = target;
result = IncompatibleLanguageGB;
@ -321,14 +321,14 @@ public static class EntityConverter
/// <summary>
/// Checks if a <see cref="GBPKM"/> is incompatible with the Generation 1/2 destination environment.
/// </summary>
public static bool IsIncompatibleGB(PKM pk, bool destJapanese, bool srcJapanese)
public static bool IsCompatibleGB(PKM pk, bool destJapanese, bool srcJapanese)
{
if (pk.Format > 2)
return false;
return true;
if (destJapanese == srcJapanese)
return false;
return true;
if (pk is SK2 sk2 && sk2.IsPossible(srcJapanese))
return false;
return true;
return true;
return false;
}
}

View file

@ -951,8 +951,6 @@ public static class FormConverter
SetDecorations(result, 7, forms[CaramelSwirl]);
SetDecorations(result, 8, forms[RainbowSwirl]);
return;
static void SetDecorations(Span<string> result, [ConstantExpected] byte f, string baseName)
{
int start = f * AlcremieCountDecoration;

View file

@ -25,6 +25,7 @@ public sealed record SimpleTrainerInfo : ITrainerInfo, IRegionOrigin
public SimpleTrainerInfo(GameVersion game = PKX.Version)
{
Version = game;
Context = Version.GetContext();
SanityCheckRegionOrigin(game);
}

View file

@ -25,8 +25,8 @@ public sealed class CaptureRecords(SAV7b sav, Memory<byte> raw) : SaveBlock<SAV7
private const int TotalTransferredOffset = 0x7A8;
// Calling into these directly, you should be sure that you're less than ENTRY_COUNT.
private int GetCapturedOffset(int index) => CapturedOffset + (index * 4);
private int GetTransferredOffset(int index) => TransferredOffset + (index * 4);
private static int GetCapturedOffset(int index) => CapturedOffset + (index * 4);
private static int GetTransferredOffset(int index) => TransferredOffset + (index * 4);
public uint GetCapturedCountIndex(int index) => ReadUInt32LittleEndian(Data[GetCapturedOffset(index)..]);
public uint GetTransferredCountIndex(int index) => ReadUInt32LittleEndian(Data[GetTransferredOffset(index)..]);
public void SetCapturedCountIndex(int index, uint value) => WriteUInt32LittleEndian(Data[GetCapturedOffset(index)..], Math.Min(MAX_COUNT_ENTRY_CAPTURE, value));

View file

@ -32,7 +32,7 @@ public static class SaveExtensions
if (sav.PKMType != pk.GetType())
return false;
if (sav is ILangDeviantSave il && EntityConverter.IsIncompatibleGB(pk, il.Japanese, pk.Japanese))
if (sav is ILangDeviantSave il && !EntityConverter.IsCompatibleGB(pk, il.Japanese, pk.Japanese))
return false;
return true;
@ -140,7 +140,7 @@ public static class SaveExtensions
continue;
}
if (sav is ILangDeviantSave il && EntityConverter.IsIncompatibleGB(temp, il.Japanese, pk.Japanese))
if (sav is ILangDeviantSave il && !EntityConverter.IsCompatibleGB(temp, il.Japanese, pk.Japanese))
{
var str = EntityConverterResult.IncompatibleLanguageGB.GetIncompatibleGBMessage(pk, il.Japanese);
Debug.WriteLine(str);

View file

@ -31,7 +31,7 @@ public static class SaveFinder
public static string? GetSwitchLocation(IEnumerable<string> drives, bool skipFirstDrive = true) =>
FindConsoleRootFolder(drives, "Nintendo", skipFirstDrive);
private static string? FindConsoleRootFolder(IEnumerable<string> drives, string path, bool skipFirstDrive)
private static string? FindConsoleRootFolder(IEnumerable<string> drives, [ConstantExpected] string path, bool skipFirstDrive)
{
if (skipFirstDrive)
drives = drives.Skip(1);

View file

@ -942,7 +942,7 @@ public static class SaveUtil
private static IEnumerable<string> FilterSaveFiles(bool ignoreBackups, IEnumerable<string> files)
{
foreach (string file in files)
foreach (var file in files)
{
if (ignoreBackups && IsBackup(file))
continue;

View file

@ -99,7 +99,7 @@ public static partial class Util
/// </summary>
/// <param name="fileName">Base file name</param>
/// <remarks>Ignores Korean Language.</remarks>
public static string[][] GetLanguageStrings7(string fileName) =>
public static string[][] GetLanguageStrings7([ConstantExpected] string fileName) =>
[
[], // 0 - None
GetStringList(fileName, "ja"), // 1
@ -115,7 +115,7 @@ public static partial class Util
/// Retrieves the localization index list for all requested strings for the <see cref="fileName"/> through Korean.
/// </summary>
/// <param name="fileName">Base file name</param>
public static string[][] GetLanguageStrings8(string fileName) =>
public static string[][] GetLanguageStrings8([ConstantExpected] string fileName) =>
[
[], // 0 - None
GetStringList(fileName, "ja"), // 1
@ -133,7 +133,7 @@ public static partial class Util
/// </summary>
/// <param name="fileName">Base file name</param>
/// <param name="zh2">String to use for the second Chinese localization.</param>
public static string[][] GetLanguageStrings10(string fileName, string zh2 = "zh") =>
public static string[][] GetLanguageStrings10([ConstantExpected] string fileName, string zh2 = "zh") =>
[
[], // 0 - None
GetStringList(fileName, "ja"), // 1
@ -180,9 +180,9 @@ public static partial class Util
return raw;
}
public static string[] GetStringList(string fileName, string lang2char, string type = "text") => GetStringList(GetFullResourceName(fileName, lang2char, type));
public static string[] GetStringList(string fileName, string lang2char, [ConstantExpected] string type = "text") => GetStringList(GetFullResourceName(fileName, lang2char, type));
private static string GetFullResourceName(string fileName, string lang2char, string type) => $"{type}_{fileName}_{lang2char}";
private static string GetFullResourceName(string fileName, string lang2char, [ConstantExpected] string type) => $"{type}_{fileName}_{lang2char}";
public static byte[] GetBinaryResource(string name)
{
@ -216,7 +216,7 @@ public static partial class Util
if (s.Length == 0)
return [];
var count = GetCount(s);
var count = 1 + s.Count('\n');
var result = new string[count];
var i = 0;
@ -234,17 +234,4 @@ public static partial class Util
s = s[(index + 1)..];
}
}
private static int GetCount(ReadOnlySpan<char> s)
{
int count = 1;
while (true)
{
var index = s.IndexOf('\n');
if (index == -1)
return count;
count++;
s = s[(index+1)..];
}
}
}

View file

@ -1757,7 +1757,7 @@ public sealed partial class PKMEditor : UserControl, IMainEditor
DrawMoveRectangle(e, brush, text, textColor, moveTypeIcon);
}
private static void DrawMoveRectangle(DrawItemEventArgs e, Brush backBrush, string foreText, Color textColor, Bitmap? icon)
private static void DrawMoveRectangle(DrawItemEventArgs e, Brush backBrush, ReadOnlySpan<char> foreText, Color textColor, Bitmap? icon)
{
var g = e.Graphics;
var rec = e.Bounds;

View file

@ -12,8 +12,8 @@ public partial class StatusBrowser : Form
public bool WasChosen { get; private set; }
public StatusCondition Choice { get; private set; }
private readonly int StatusHeight;
private const int StatusCount = 7;
private int StatusHeight { get; }
private int StatusWidth => StatusHeight;
private int StatusBrowserWidth => StatusWidth * 2;

View file

@ -300,7 +300,7 @@ public sealed class SlotChangeManager(SAVEditor se) : IDisposable
if (badDest && (pk.Species == 0 || pk.IsEgg))
return false;
if (sav is ILangDeviantSave il && EntityConverter.IsIncompatibleGB(temp, il.Japanese, pk.Japanese))
if (sav is ILangDeviantSave il && !EntityConverter.IsCompatibleGB(temp, il.Japanese, pk.Japanese))
{
var str = EntityConverterResult.IncompatibleLanguageGB.GetIncompatibleGBMessage(pk, il.Japanese);
WinFormsUtil.Error(str);

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
@ -240,7 +241,7 @@ public sealed partial class SAV_EventWork : Form
ChangeSAV();
}
private static string[] GetStringList(GameVersion game, string type)
private static string[] GetStringList(GameVersion game, [ConstantExpected] string type)
{
var gamePrefix = GetGameFilePrefix(game);
return GameLanguage.GetStrings(gamePrefix, GameInfo.CurrentLanguage, type);

View file

@ -24,7 +24,7 @@ public class ShowdownSetTests
var set = new ShowdownSet(SetGlaceonUSUMTutor);
var pk7 = new PK7 {Species = set.Species, Form = set.Form, Moves = set.Moves};
var encounters = EncounterMovesetGenerator.GenerateEncounters(pk7, set.Moves, GameVersion.MN);
Assert.True(!encounters.Any());
Assert.False(encounters.Any());
pk7.HandlingTrainerName = "PKHeX";
encounters = EncounterMovesetGenerator.GenerateEncounters(pk7, set.Moves, GameVersion.MN);
var first = encounters.FirstOrDefault();
@ -153,9 +153,6 @@ public class ShowdownSetTests
var text = string.Join("\r\n\r\n", Sets);
var sets = ShowdownParsing.GetShowdownSets(text);
Assert.True(sets.Count() == Sets.Length);
sets = ShowdownParsing.GetShowdownSets(string.Empty);
Assert.True(!sets.Any());
}
[Fact]
@ -163,7 +160,7 @@ public class ShowdownSetTests
{
string[] lines = ["", " ", " "];
var sets = ShowdownParsing.GetShowdownSets(lines);
Assert.True(!sets.Any());
Assert.False(sets.Any());
}
[Theory]
@ -183,7 +180,7 @@ public class ShowdownSetTests
var pk7 = new PK3 { Species = set.Species, Form = set.Form, Moves = set.Moves, CurrentLevel = set.Level };
var encs = EncounterMovesetGenerator.GenerateEncounters(pk7, set.Moves);
var tr3 = encs.First(z => z is EncounterTrade3);
var pk3 = tr3.ConvertToPKM(new SAV3FRLG());
var pk3 = tr3.ConvertToPKM(new SimpleTrainerInfo(GameVersion.FR));
var la = new LegalityAnalysis(pk3);
la.Valid.Should().BeTrue(la.Report());