using MessagePack; using MessagePack.Resolvers; using Shaker.Model; using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Shaker.Tools { public static class Tools { private static MessagePackSerializerOptions options = TypelessContractlessStandardResolver.Options.WithOmitAssemblyVersion(true); public static byte[] GetBytes(this T value) { return MessagePack.MessagePackSerializer.Serialize(value, options); } public static T GetValue(this byte[] data) { return MessagePackSerializer.Deserialize(data, options); } /// /// 压缩数据包 /// /// /// public static byte[] CompressionBytes(byte[] arrays) { if (arrays == null || arrays.Length == 0) return new byte[0]; using (MemoryStream ms = new MemoryStream()) { using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionLevel.SmallestSize, true)) { ds.Write(arrays, 0, arrays.Length); } return ms.ToArray(); } } /// /// 解压数据包 /// /// /// public static byte[] DecompressionBytes(byte[] arrays) { if (arrays == null || arrays.Length == 0) return new byte[0]; using (MemoryStream ms = new MemoryStream(arrays)) { using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress, true)) { using (MemoryStream memoryStream = new MemoryStream()) { ds.CopyTo(memoryStream); return memoryStream.ToArray(); } } } } public static string GetUnit(this T e) where T: Enum { if (e == null || !e.GetType().IsEnum) return ""; return (e.GetType()? .GetField(e.ToString())? .GetCustomAttributes(typeof(ResultChannelUnitAttribute), false) .FirstOrDefault() as ResultChannelUnitAttribute)?.Unit ?? ""; } public static T[] FixedArray(this T[] value,int lenght) { if (lenght == 0) return Array.Empty(); if (value == null) return [.. Enumerable.Range(0, lenght).Select(x => Activator.CreateInstance())]; if (value.Length > lenght) return value[0..lenght]; return [.. value,..Enumerable.Range(0, lenght - value.Length).Select(x=>Activator.CreateInstance())]; } public static IEnumerable FixedArray(this IEnumerable value, int lenght) { if (lenght == 0) return Array.Empty(); if (value == null) return [.. Enumerable.Range(0, lenght).Select(x => Activator.CreateInstance())]; if (value.Count() > lenght) return value.Take(lenght); return [.. value, .. Enumerable.Range(0, lenght - value.Count()).Select(x => Activator.CreateInstance())]; } } }