NHSE/NHSE.Core/Util/StringUtil.cs
2020-03-30 13:55:12 -07:00

46 lines
1.5 KiB
C#

using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
namespace NHSE.Core
{
/// <summary>
/// Logic for manipulating strings
/// </summary>
public static class StringUtil
{
/// <summary>
/// Trims a string at the first instance of a 0x0000 terminator.
/// </summary>
/// <param name="input">String to trim.</param>
/// <returns>Trimmed string.</returns>
public static string TrimFromZero(string input) => TrimFromFirst(input, '\0');
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string TrimFromFirst(string input, char c)
{
int index = input.IndexOf(c);
return index < 0 ? input : input.Substring(0, index);
}
public static string GetString(byte[] data, int offset, int maxLength)
{
var str = Encoding.Unicode.GetString(data, offset, maxLength * 2);
return TrimFromZero(str);
}
public static byte[] GetBytes(string value, int maxLength)
{
if (value.Length > maxLength)
value = value.Substring(0, maxLength);
else if (value.Length < maxLength)
value = value.PadRight(maxLength, '\0');
return Encoding.Unicode.GetBytes(value);
}
public static string CleanFileName(string fileName)
{
return string.Concat(fileName.Split(Path.GetInvalidFileNameChars()));
}
}
}