Init
This commit is contained in:
47
ConsoleApp2/Helpers/Extensions.String.cs
Normal file
47
ConsoleApp2/Helpers/Extensions.String.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace ConsoleApp2.Helpers;
|
||||
|
||||
public static class StringExtensions
|
||||
{
|
||||
public static string Omit(this ReadOnlySpan<char> @this, int maxLength)
|
||||
{
|
||||
if (@this.Length > maxLength)
|
||||
return @this[..maxLength].ToString() + "...";
|
||||
return @this.ToString();
|
||||
}
|
||||
|
||||
public static string Omit(this string @this, int maxLength) => Omit(@this.AsSpan(), maxLength);
|
||||
|
||||
public static string FromHex(ReadOnlySpan<char> hexString, Encoding? encoding = null)
|
||||
{
|
||||
encoding ??= Encoding.UTF8;
|
||||
|
||||
var realLength = 0;
|
||||
for (var i = hexString.Length - 2; i >= 0; i -= 2)
|
||||
{
|
||||
var b = byte.Parse(hexString.Slice(i, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
if (b != 0) //not NULL character
|
||||
{
|
||||
realLength = i + 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var bytes = new byte[realLength / 2];
|
||||
for (var i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
bytes[i] = byte.Parse(hexString.Slice(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return encoding.GetString(bytes);
|
||||
}
|
||||
|
||||
public static bool CheckJsonHex(ReadOnlySpan<char> hexStr)
|
||||
{
|
||||
if (hexStr.Length < 2)
|
||||
return false;
|
||||
return FromHex(hexStr[..2]) is ['{'] or ['['];
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user