PKHeX/PKHeX.Core/Util/RandUtil.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

40 lines
1.4 KiB
C#

using System;
using System.Threading;
namespace PKHeX.Core
{
public static partial class Util
{
// Multithread safe rand, ha
public static Random Rand => _local.Value;
private static readonly ThreadLocal<Random> _local = new(() => new Random());
public static uint Rand32() => Rand32(Rand);
public static uint Rand32(Random rnd) => (uint)rnd.Next(1 << 30) << 2 | (uint)rnd.Next(1 << 2);
/// <summary>
/// Shuffles the order of items within a collection of items.
/// </summary>
/// <typeparam name="T">Item type</typeparam>
/// <param name="items">Item collection</param>
public static void Shuffle<T>(Span<T> items) => Shuffle(items, 0, items.Length, Rand);
/// <summary>
/// Shuffles the order of items within a collection of items.
/// </summary>
/// <typeparam name="T">Item type</typeparam>
/// <param name="items">Item collection</param>
/// <param name="start">Starting position</param>
/// <param name="end">Ending position</param>
/// <param name="rnd">RNG object to use</param>
public static void Shuffle<T>(Span<T> items, int start, int end, Random rnd)
{
for (int i = start; i < end; i++)
{
int index = i + rnd.Next(end - i);
(items[index], items[i]) = (items[i], items[index]);
}
}
}
}