2023-03-28 18:29:29 +00:00
|
|
|
using System;
|
|
|
|
using System.IO;
|
2017-05-12 04:34:18 +00:00
|
|
|
|
2022-06-18 18:04:24 +00:00
|
|
|
namespace PKHeX.Core;
|
|
|
|
|
|
|
|
public static partial class Util
|
2017-05-12 04:34:18 +00:00
|
|
|
{
|
2022-06-18 18:04:24 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Cleans the local <see cref="fileName"/> by removing any invalid filename characters.
|
|
|
|
/// </summary>
|
|
|
|
/// <returns>New string without any invalid characters.</returns>
|
|
|
|
public static string CleanFileName(string fileName)
|
2017-05-12 04:34:18 +00:00
|
|
|
{
|
2023-03-28 18:29:29 +00:00
|
|
|
Span<char> result = stackalloc char[fileName.Length];
|
|
|
|
int ctr = GetCleanFileName(fileName, result);
|
2023-04-23 00:51:32 +00:00
|
|
|
if (ctr == fileName.Length)
|
|
|
|
return fileName;
|
2023-03-28 18:29:29 +00:00
|
|
|
return new string(result[..ctr]);
|
|
|
|
}
|
|
|
|
|
2024-02-03 20:11:17 +00:00
|
|
|
/// <inheritdoc cref="CleanFileName(string)"/>
|
|
|
|
public static string CleanFileName(ReadOnlySpan<char> fileName)
|
|
|
|
{
|
|
|
|
Span<char> result = stackalloc char[fileName.Length];
|
|
|
|
int ctr = GetCleanFileName(fileName, result);
|
|
|
|
if (ctr == fileName.Length)
|
|
|
|
return fileName.ToString();
|
|
|
|
return new string(result[..ctr]);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Removes any invalid filename characters from the input string.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="input">String to clean</param>
|
|
|
|
/// <param name="output">Buffer to write the cleaned string to</param>
|
|
|
|
/// <returns>Length of the cleaned string</returns>
|
2023-03-28 18:29:29 +00:00
|
|
|
private static int GetCleanFileName(ReadOnlySpan<char> input, Span<char> output)
|
|
|
|
{
|
|
|
|
ReadOnlySpan<char> invalid = Path.GetInvalidFileNameChars();
|
|
|
|
int ctr = 0;
|
|
|
|
foreach (var c in input)
|
|
|
|
{
|
|
|
|
if (!invalid.Contains(c))
|
|
|
|
output[ctr++] = c;
|
|
|
|
}
|
|
|
|
return ctr;
|
2017-05-12 04:34:18 +00:00
|
|
|
}
|
|
|
|
}
|