using System.Text; using System.Text.RegularExpressions; namespace Qrakhen.Qamp.Core; public static class Extensions { public static uint GetHash(this string str) { if (string.IsNullOrEmpty(str)) return 0; byte[] bytes = Encoding.ASCII.GetBytes(str); unchecked { uint hash = 216613661u; for (int i = 0; i < bytes.Length; i++) { hash ^= bytes[i]; hash *= 16777619; } return hash; } } public static bool TryMatch(this Regex regex, string str, out Match match) { match = regex.Match(str); return match.Success; } public static T[] Subset(this T[] array, long from, long length = -1) { length = length < 0 ? array.Length - from : length; var result = new T[length]; Array.Copy(array, from, result, 0, length); return result; } /// /// Expensive. /// 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[] GetDynamicBytes(this long value) { byte[] data = value.GetBytes(); return data.Subset(0, GetPrimitiveLength(value)); } public static int GetPrimitiveLength(this long value) { int length = 8; for (int i = 1; i < 8; i++) { if (value <= (1L << (i * 8))) { length = i; break; } } return length; } 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); }