-
Notifications
You must be signed in to change notification settings - Fork 45
/
Lz4.cs
147 lines (113 loc) · 3.34 KB
/
Lz4.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// https://github.com/Ryujinx/Ryujinx/blob/0254a84f90ea03037be15b8fd1f9e0a4be5577e9/Ryujinx.HLE/Loaders/Compression/Lz4.cs
using System;
namespace LibHac.Util;
public static class Lz4
{
public static byte[] Decompress(byte[] cmp, int decLength)
{
byte[] dec = new byte[decLength];
int cmpPos = 0;
int decPos = 0;
int GetLength(int length)
{
byte sum;
if (length == 0xf)
{
do
{
length += sum = cmp[cmpPos++];
}
while (sum == 0xff);
}
return length;
}
do
{
byte token = cmp[cmpPos++];
int encCount = (token >> 0) & 0xf;
int litCount = (token >> 4) & 0xf;
//Copy literal chunk
litCount = GetLength(litCount);
Buffer.BlockCopy(cmp, cmpPos, dec, decPos, litCount);
cmpPos += litCount;
decPos += litCount;
if (cmpPos >= cmp.Length)
{
break;
}
//Copy compressed chunk
int back = cmp[cmpPos++] << 0 |
cmp[cmpPos++] << 8;
encCount = GetLength(encCount) + 4;
int encPos = decPos - back;
if (encCount <= back)
{
Buffer.BlockCopy(dec, encPos, dec, decPos, encCount);
decPos += encCount;
}
else
{
while (encCount-- > 0)
{
dec[decPos++] = dec[encPos++];
}
}
}
while (cmpPos < cmp.Length &&
decPos < dec.Length);
return dec;
}
public static void Decompress(ReadOnlySpan<byte> cmp, Span<byte> dec)
{
int cmpPos = 0;
int decPos = 0;
// ReSharper disable once VariableHidesOuterVariable
int GetLength(int length, ReadOnlySpan<byte> cmp)
{
byte sum;
if (length == 0xf)
{
do
{
length += sum = cmp[cmpPos++];
}
while (sum == 0xff);
}
return length;
}
do
{
byte token = cmp[cmpPos++];
int encCount = (token >> 0) & 0xf;
int litCount = (token >> 4) & 0xf;
//Copy literal chunk
litCount = GetLength(litCount, cmp);
cmp.Slice(cmpPos, litCount).CopyTo(dec.Slice(decPos));
cmpPos += litCount;
decPos += litCount;
if (cmpPos >= cmp.Length)
{
break;
}
//Copy compressed chunk
int back = cmp[cmpPos++] << 0 |
cmp[cmpPos++] << 8;
encCount = GetLength(encCount, cmp) + 4;
int encPos = decPos - back;
if (encCount <= back)
{
dec.Slice(encPos, encCount).CopyTo(dec.Slice(decPos));
decPos += encCount;
}
else
{
while (encCount-- > 0)
{
dec[decPos++] = dec[encPos++];
}
}
}
while (cmpPos < cmp.Length &&
decPos < dec.Length);
}
}