Exemple #1
0
    public static int Compress(byte[] inputBuffer, ref IEnumerable <byte> outputBuffer, bool useRedHeader,
                               CompressionLevel level = CompressionLevel.Normal, Compressor compressor = Compressor.Kraken)
    {
        if (inputBuffer == null)
        {
            throw new ArgumentNullException(nameof(inputBuffer));
        }
        var inputCount = inputBuffer.Length;

        if (inputCount <= 0 || inputCount > inputBuffer.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(inputCount));
        }
        if (outputBuffer == null)
        {
            throw new ArgumentNullException(nameof(outputBuffer));
        }

        var result = 0;
        var compressedBufferSizeNeeded = Oodle.GetCompressedBufferSizeNeeded(inputCount);
        var compressedBuffer           = new byte[compressedBufferSizeNeeded];

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            result = CompressionSettings.Get().UseOodle
                ? OodleLib.OodleLZ_Compress(inputBuffer, compressedBuffer, compressor, level)
                : KrakenNative.Compress(inputBuffer, compressedBuffer, (int)level);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            result = KrakenNative.Compress(inputBuffer, compressedBuffer, (int)level);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            result = OozNative.Kraken_Compress(inputBuffer, compressedBuffer, (int)level);
        }
        else
        {
            throw new NotImplementedException();
        }


        if (result == 0 || inputCount <= (result + 8))
        {
            outputBuffer = inputBuffer;
            return(outputBuffer.Count());
        }

        if (useRedHeader)
        {
            // write KARK header
            var writelist = new List <byte>()
            {
                0x4B, 0x41, 0x52, 0x4B          //KARK, TODO: make this dependent on the compression algo
            };
            // write size
            writelist.AddRange(BitConverter.GetBytes(inputCount));
            // write compressed data
            writelist.AddRange(compressedBuffer.Take(result));

            outputBuffer = writelist;
        }
        else
        {
            outputBuffer = compressedBuffer.Take(result);
        }

        return(outputBuffer.Count());
    }