// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;

namespace WPFMA.Vrca
{
    internal static class WPFMAVrcaLz4
    {
        public static int Decompress(byte[] source, int sourceOffset, int sourceLength, byte[] destination, int destinationOffset, int destinationLength)
        {
            int src = sourceOffset;
            int srcEnd = sourceOffset + sourceLength;
            int dst = destinationOffset;
            int dstEnd = destinationOffset + destinationLength;

            while (src < srcEnd)
            {
                int token = source[src++];

                int literalLength = token >> 4;
                if (literalLength == 15)
                    literalLength += ReadLengthTail(source, ref src, srcEnd);

                if (literalLength > 0)
                {
                    if (src + literalLength > srcEnd || dst + literalLength > dstEnd)
                        throw new FormatException("LZ4 literal run runs past the end of the block.");

                    Buffer.BlockCopy(source, src, destination, dst, literalLength);
                    src += literalLength;
                    dst += literalLength;
                }

                if (src >= srcEnd)
                    break;

                if (src + 2 > srcEnd)
                    throw new FormatException("LZ4 block ended in the middle of a match offset.");

                int offset = source[src++];
                offset |= source[src++] << 8;
                if (offset == 0 || dst - offset < destinationOffset)
                    throw new FormatException("LZ4 match offset points outside the output window.");

                int matchLength = (token & 0x0F) + 4;
                if ((token & 0x0F) == 15)
                    matchLength += ReadLengthTail(source, ref src, srcEnd);

                if (dst + matchLength > dstEnd)
                    throw new FormatException("LZ4 match runs past the end of the block.");

                int match = dst - offset;
                for (int i = 0; i < matchLength; i++)
                    destination[dst++] = destination[match++];
            }

            return dst - destinationOffset;
        }

        private static int ReadLengthTail(byte[] source, ref int src, int srcEnd)
        {
            int total = 0;
            byte current;
            do
            {
                if (src >= srcEnd)
                    throw new FormatException("LZ4 length escape ran past the end of the block.");

                current = source[src++];
                total += current;
            }
            while (current == 255);

            return total;
        }
    }
}
#endif
