c260ebd566
Scan directories sequentially to reduce memory footprint Reviewed-on: #3 Co-authored-by: Huy Nguyen <ecenshu@gmail.com> Co-committed-by: Huy Nguyen <ecenshu@gmail.com>
78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
using System.Globalization;
|
||
using System.Text.RegularExpressions;
|
||
|
||
namespace TinfoilVibeServer.Utilities;
|
||
|
||
|
||
public static class IdHelper
|
||
{
|
||
public static string ToStrId(this int num)
|
||
{
|
||
return ToIdFromConvertedNumBytes(BitConverter.GetBytes(num));
|
||
}
|
||
|
||
public static string ToStrId(this uint num)
|
||
{
|
||
return ToIdFromConvertedNumBytes(BitConverter.GetBytes(num));
|
||
}
|
||
|
||
public static string ToStrId(this long num)
|
||
{
|
||
return ToIdFromConvertedNumBytes(BitConverter.GetBytes(num));
|
||
}
|
||
|
||
public static string ToStrId(this ulong num)
|
||
{
|
||
return ToIdFromConvertedNumBytes(BitConverter.GetBytes(num));
|
||
}
|
||
|
||
public static string ToStrId(this IEnumerable<byte> bytes)
|
||
{
|
||
return bytes.Aggregate("", (current, b) => current + b.ToString("X2"));
|
||
}
|
||
|
||
public static string ToStrId(this Span<byte> bytes)
|
||
{
|
||
return bytes.ToArray().ToStrId();
|
||
}
|
||
|
||
private static string ToIdFromConvertedNumBytes(IEnumerable<byte> getBytes)
|
||
{
|
||
return ToStrId(getBytes.Reverse());
|
||
}
|
||
|
||
public static string GetTitleId(this FileInfo fileInfo)
|
||
{
|
||
var match = Regex.Match(fileInfo.Name, "^.*\\[(\\w{16})\\].*\\.nsp$");
|
||
return match is { Length: > 0, Groups.Count: > 1 }?match.Groups[1].Value:string.Empty;
|
||
}
|
||
#region 1️⃣ From hex string → byte[] (big‑endian)
|
||
|
||
/// <summary>
|
||
/// Turns an even‑length hex string into a byte array in **big‑endian** order
|
||
/// (the same order that the original <c>ToStrId</c> creates).
|
||
/// </summary>
|
||
private static byte[] HexStringToBytes(string hex)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(hex))
|
||
throw new ArgumentException("ID string cannot be empty", nameof(hex));
|
||
|
||
if (hex.Length % 2 != 0)
|
||
throw new ArgumentException("ID string must contain an even number of hex digits", nameof(hex));
|
||
|
||
var bytes = new byte[hex.Length / 2];
|
||
for (var i = 0; i < bytes.Length; i++)
|
||
{
|
||
var chunk = hex.Substring(i * 2, 2);
|
||
bytes[i] = byte.Parse(chunk, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||
}
|
||
|
||
return bytes;
|
||
}
|
||
|
||
#endregion
|
||
|
||
public static long ToLongFromStrId(this string hex) =>
|
||
BitConverter.ToInt64(HexStringToBytes(hex).Reverse().ToArray(), 0);
|
||
|
||
} |