-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLZO.cs
57 lines (42 loc) · 1.87 KB
/
LZO.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace bagpipe {
static class LZO {
[DllImport("minilzo.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int lzo1x_1_compress(IntPtr src, uint src_len, IntPtr dst, ref uint dst_len, IntPtr wrkmem);
[DllImport("minilzo.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int lzo1x_decompress_safe(IntPtr src, uint src_len, IntPtr dst, ref uint dst_len, IntPtr wrkmem);
private static readonly IntPtr workMem = Marshal.AllocHGlobal(16384);
public static byte[] Compress(byte[] data, int offset, int len) {
IntPtr srcPtr = Marshal.AllocHGlobal(len);
IntPtr dstPtr = Marshal.AllocHGlobal(len + (len / 16) + 64 + 3);
Marshal.Copy(data, offset, srcPtr, len);
uint outSize = 0;
int res = lzo1x_1_compress(srcPtr, (uint)len, dstPtr, ref outSize, workMem);
if (res != 0) {
throw new Win32Exception($"Compression failed: {res}");
}
byte[] output = new byte[outSize];
Marshal.Copy(dstPtr, output, 0, (int)outSize);
Marshal.FreeHGlobal(srcPtr);
Marshal.FreeHGlobal(dstPtr);
return output;
}
public static byte[] Decompress(int decompressedSize, byte[] data, int offset, int len) {
IntPtr srcPtr = Marshal.AllocHGlobal(len);
IntPtr dstPtr = Marshal.AllocHGlobal(decompressedSize);
Marshal.Copy(data, offset, srcPtr, len);
uint outSize = (uint)decompressedSize;
int res = lzo1x_decompress_safe(srcPtr, (uint)len, dstPtr, ref outSize, workMem);
if (res != 0) {
throw new Win32Exception($"Decompression failed: {res}");
}
byte[] output = new byte[outSize];
Marshal.Copy(dstPtr, output, 0, (int)outSize);
Marshal.FreeHGlobal(srcPtr);
Marshal.FreeHGlobal(dstPtr);
return output;
}
}
}