67 lines
2.6 KiB
C#
67 lines
2.6 KiB
C#
using System.Text.Json.Serialization;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Qrakhen.Qamp.Core;
|
|
|
|
public static class Extensions
|
|
{
|
|
public static bool TryMatch(this Regex regex, string str, out Match match)
|
|
{
|
|
match = regex.Match(str);
|
|
return match.Success;
|
|
}
|
|
|
|
public static T[] Subset<T>(this T[] array, long from, long length)
|
|
{
|
|
var result = new T[length];
|
|
Array.Copy(array, from, result, 0, length);
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Expensive.
|
|
/// </summary>
|
|
public static void Insert(this Stream stream, byte[] data, long position = -1)
|
|
{
|
|
if (position < 0)
|
|
position = stream.Position;
|
|
|
|
byte[] buffer = new byte[stream.Length - position];
|
|
if (buffer.Length > 0) {
|
|
stream.Position = position;
|
|
stream.ReadExactly(buffer);
|
|
stream.Write(buffer);
|
|
}
|
|
stream.Position = position;
|
|
stream.Write(data);
|
|
}
|
|
|
|
public static void Remove(this Stream stream, long position, int amount)
|
|
{
|
|
byte[] buffer = new byte[stream.Length - (position + amount)];
|
|
if (buffer.Length > 0) {
|
|
stream.Position = position + amount;
|
|
stream.ReadExactly(buffer);
|
|
stream.Position = position;
|
|
stream.Write(buffer);
|
|
}
|
|
stream.Position = position;
|
|
stream.SetLength(stream.Length - amount);
|
|
}
|
|
|
|
public static byte[] GetBytes(this short value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this ushort value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this int value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this uint value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this long value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this ulong value) => BitConverter.GetBytes(value);
|
|
public static byte[] GetBytes(this double value) => BitConverter.GetBytes(value);
|
|
|
|
public static short ToInt16(this byte[] bytes) => BitConverter.ToInt16(bytes);
|
|
public static ushort ToUInt16(this byte[] bytes) => BitConverter.ToUInt16(bytes);
|
|
public static int ToInt32(this byte[] bytes) => BitConverter.ToInt32(bytes);
|
|
public static uint ToUInt32(this byte[] bytes) => BitConverter.ToUInt32(bytes);
|
|
public static long ToInt64(this byte[] bytes) => BitConverter.ToInt64(bytes);
|
|
public static ulong ToUInt64(this byte[] bytes) => BitConverter.ToUInt64(bytes);
|
|
public static double ToDouble(this byte[] bytes) => BitConverter.ToDouble(bytes);
|
|
} |