lz4.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Runtime.InteropServices;
  3. public class lz4
  4. {
  5. public class API
  6. {
  7. #if (UNITY_IOS || UNITY_WEBGL) && !UNITY_EDITOR
  8. const string LUADLL = "__Internal";
  9. #else
  10. const string LUADLL = "lz4";
  11. #endif
  12. [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
  13. public static extern int Unity_LZ4_compress(IntPtr src, int srcSize, IntPtr dst, int dstCapacity, int compressionLevel);
  14. [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
  15. public static extern int Unity_LZ4_compressSize(int srcSize, int compressionLevel);
  16. [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
  17. public static extern int Unity_LZ4_uncompressSize(IntPtr srcBuffer, int srcSize);
  18. [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
  19. public static extern int Unity_LZ4_decompress(IntPtr src, int srcSize, IntPtr dst, int dstCapacity);
  20. }
  21. public static byte[] Compress(byte[] input, int compressionLevel = 3)
  22. {
  23. byte[] result = null;
  24. if (input != null && input.Length > 0)
  25. {
  26. int maxSize = API.Unity_LZ4_compressSize(input.Length, compressionLevel);
  27. if (maxSize > 0)
  28. {
  29. var buffer = new byte[maxSize];
  30. var srcHandle = GCHandle.Alloc(input, GCHandleType.Pinned);
  31. var dstHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  32. var actualSize = API.Unity_LZ4_compress(srcHandle.AddrOfPinnedObject(), input.Length, dstHandle.AddrOfPinnedObject(), maxSize, compressionLevel);
  33. if (actualSize > 0)
  34. {
  35. result = new byte[actualSize];
  36. Array.Copy(buffer, result, actualSize);
  37. }
  38. srcHandle.Free();
  39. dstHandle.Free();
  40. }
  41. }
  42. return result;
  43. }
  44. public static byte[] Decompress(byte[] input)
  45. {
  46. byte[] result = null;
  47. if (input != null && input.Length > 0)
  48. {
  49. var srcHandle = GCHandle.Alloc(input, GCHandleType.Pinned);
  50. var uncompressSize = API.Unity_LZ4_uncompressSize(srcHandle.AddrOfPinnedObject(), input.Length);
  51. result = new byte[uncompressSize];
  52. var dstHandle = GCHandle.Alloc(result, GCHandleType.Pinned);
  53. if (API.Unity_LZ4_decompress(srcHandle.AddrOfPinnedObject(), input.Length, dstHandle.AddrOfPinnedObject(), result.Length) != 0)
  54. {
  55. result = null;
  56. }
  57. srcHandle.Free();
  58. dstHandle.Free();
  59. }
  60. return result;
  61. }
  62. }