aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.HLE/Loaders/Compression/Lz4.cs
blob: cfb495517209957426b241f15c591073f9f08f9c (plain) (blame)
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
using System;

namespace Ryujinx.HLE.Loaders.Compression
{
    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 chunck
                LitCount = GetLength(LitCount);

                Buffer.BlockCopy(Cmp, CmpPos, Dec, DecPos, LitCount);

                CmpPos += LitCount;
                DecPos += LitCount;

                if (CmpPos >= Cmp.Length)
                {
                    break;
                }

                //Copy compressed chunck
                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;
        }
    }
}