public override void Write(System.Byte[] b1, int off, int len)
        {
            if (len == 0)
            {
                return;
            }
            int err;

            byte[] b = new byte[b1.Length];
            System.Array.Copy(b1, 0, b, 0, b1.Length);
            z.next_in       = b;
            z.next_in_index = off;
            z.avail_in      = len;
            do
            {
                z.next_out       = buf;
                z.next_out_index = 0;
                z.avail_out      = bufsize;
                if (compress)
                {
                    err = z.deflate(flush_Renamed_Field);
                }
                else
                {
                    err = z.inflate(flush_Renamed_Field);
                }
                if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
                {
                    throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
                }
                out_Renamed.Write(buf, 0, bufsize - z.avail_out);
            }while (z.avail_in > 0 || z.avail_out == 0);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Reimplements function from zlib (uncompress) that is not present in ZLIB.NET.
        /// </summary>
        /// <param name="dest">Destination array of bytes. May be trimmed if necessary.</param>
        /// <param name="source">Source array of bytes.</param>
        /// <returns>Zlib status code.</returns>
        static int ZlibUncompress(ref byte[] dest, byte[] source)
        {
            ZStream stream = new ZStream();
            int     err;

            stream.next_in   = source;
            stream.avail_in  = source.Length;
            stream.next_out  = dest;
            stream.avail_out = dest.Length;

            err = stream.inflateInit();
            if (err != zlibConst.Z_OK)
            {
                return(err);
            }

            err = stream.inflate(zlibConst.Z_FINISH);
            if (err != zlibConst.Z_STREAM_END)
            {
                stream.inflateEnd();
                return(err == zlibConst.Z_OK ? zlibConst.Z_BUF_ERROR : err);
            }

            if (stream.total_out != dest.Length)
            {
                byte[] output = new byte[stream.total_out];
                Buffer.BlockCopy(stream.next_out, 0, output, 0, (int)stream.total_out);
                dest = output;
            }

            return(stream.inflateEnd());
        }
Ejemplo n.º 3
0
        public void Decompress()
        {
            byte[] numArray = new byte[this.data.Count];
            this.data.CopyTo(0, numArray, 0, this.data.Count);
            byte[]  numArray1 = new byte[800];
            ZStream zStream   = new ZStream()
            {
                avail_in = 0
            };

            zStream.inflateInit();
            zStream.next_in       = numArray;
            zStream.next_in_index = 2;
            zStream.avail_in      = (int)numArray.Length - 4;
            zStream.next_out      = numArray1;
            zStream.avail_out     = 800;
            if (zStream.inflate(4) != -3)
            {
                long totalOut = zStream.total_out;
                zStream.inflateEnd();
                zStream = null;
                this.data.Clear();
                this.data.Add(numArray[0]);
                this.data.Add(numArray[1]);
                for (int i = 0; (long)i < totalOut; i++)
                {
                    this.data.Add(numArray1[i]);
                }
                this.data.Add(numArray[(int)numArray.Length - 3]);
                this.data.Add(numArray[(int)numArray.Length - 2]);
                this.data.Add(numArray[(int)numArray.Length - 1]);
            }
        }
Ejemplo n.º 4
0
        static void uncompress(ref byte[] dest, byte[] src)
        {
            ZStream stream = new ZStream();

            stream.next_in  = src;
            stream.avail_in = src.Length;

            stream.next_out  = dest;
            stream.avail_out = dest.Length;

            stream.inflateInit();

            int err = stream.inflate(zlibConst.Z_FINISH);

            if (err != zlibConst.Z_STREAM_END)
            {
                stream.inflateEnd();
                throw new ApplicationException();
            }

            Array.Resize <byte>(ref dest, (int)stream.total_out);

            err = stream.inflateEnd();
            if (err != zlibConst.Z_OK)
            {
                throw new ApplicationException();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Uncompress a source byte array to a destination (old version)
        /// </summary>
        public static int UncompressOld(byte[] dest, ref ulong destLen, byte[] source, ref ulong sourceLen)
        {
            var stream = new ZStream
            {
                next_in   = source,
                avail_in  = (int)sourceLen,
                next_out  = dest,
                avail_out = (int)destLen,
            };

            destLen   = 0;
            sourceLen = 0;

            // make second parameter negative to disable checksum verification
            int err = stream.inflateInit(-Constants.MAX_WBITS);

            if (err != zlibConst.Z_OK)
            {
                return(err);
            }

            while (stream.avail_in > 1)
            {
                err = stream.inflate(Constants.Z_BLOCK);
                if (err != zlibConst.Z_OK)
                {
                    stream.inflateEnd();
                    return(err);
                }
            }

            destLen   = (ulong)stream.total_out;
            sourceLen = (ulong)stream.total_in;
            return(stream.inflateEnd());
        }
Ejemplo n.º 6
0
            private int Inflate(BufferStream tmp, byte[] outBuffer, int count)
            {
                inbound.next_in_index = 0;
                inbound.avail_in      = count;
                inbound.next_out      = outBuffer;
                int totalBytes = 0;

                do
                {
                    inbound.next_out_index = 0;

                    inbound.avail_out = outBuffer.Length;

                    long priorOut = inbound.total_out;
                    var  err      = inbound.inflate(zlibConst.Z_SYNC_FLUSH);

                    if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
                    {
                        throw new ZStreamException("inflating: " + inbound.msg);
                    }

                    int outCount = (int)(inbound.total_out - priorOut);
                    if (outCount > 0)
                    {
                        tmp.Write(outBuffer, 0, outCount);
                        totalBytes += outCount;
                    }
                } while (inbound.avail_in > 0);
                return(totalBytes);
            }
Ejemplo n.º 7
0
    public static byte[] Uncompress(byte[] buff, int offset = 0)
    {
        //using (MemoryStream md = new MemoryStream())
        //{
        //    Stream d = new ZOutputStream(md);
        //    d.Write(buff, offset, buff.Length - offset);
        //    d.Close();
        //    return md.ToArray();
        //}
        ZStream zs = new ZStream();

        zs.next_in   = buff;
        zs.avail_in  = buff.Length;
        zs.next_out  = _buffer;
        zs.avail_out = _buffer.Length;
        if (zlibConst.Z_OK != zs.inflateInit())
        {
            return(null);
        }
        if (zlibConst.Z_STREAM_END != zs.inflate(zlibConst.Z_FINISH))
        {
            return(null);
        }
        zs.inflateEnd();
        byte[] result = new byte[zs.total_out];
        System.Array.Copy(_buffer, result, zs.total_out);
        return(result);
    }
Ejemplo n.º 8
0
        private byte[] Decompress(byte[] pBuffer, ZStream iStream)
        {
            byte[] rBuff = new byte[pBuffer.Length + 4];
            Array.Copy(pBuffer, 0, rBuff, 0, pBuffer.Length);

            rBuff[rBuff.Length - 4] = 0x00;
            rBuff[rBuff.Length - 3] = 0x00;
            rBuff[rBuff.Length - 2] = 0xFF;
            rBuff[rBuff.Length - 1] = 0xFF;

            iStream.total_in  = 0;
            iStream.total_out = 0;

            iStream.next_in       = rBuff;
            iStream.next_in_index = 0;
            iStream.avail_in      = rBuff.Length;

            MemoryStream lStream = new MemoryStream();

            byte[] oBuff = new byte[pBuffer.Length * 8];

            iStream.next_out       = oBuff;
            iStream.next_out_index = 0;
            iStream.avail_out      = pBuffer.Length * 8;

            iStream.inflate(2);

            lStream.Write(oBuff, 0, (pBuffer.Length * 8) - iStream.avail_out);

            byte[] rBASD = lStream.ToArray();

            lStream.Dispose();

            return(rBASD);
        }
Ejemplo n.º 9
0
            /// <summary>
            /// Extract all files contained in the package in the folder pointed by the destination path.
            /// </summary>
            public void ExtractAll(String Destination)
            {
                Destination = Destination.Replace('/', '\\');
                if (!Destination.EndsWith("\\"))
                {
                    Destination += "\\";
                }

                using (FileStream Input = new FileStream(TpdFile.GetFilename(), FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Byte[] Buffer = new Byte[Kernel.MAX_BUFFER_SIZE];
                    Byte[] Tmp    = new Byte[Kernel.MAX_BUFFER_SIZE];

                    foreach (Entry Entry in Entries.Values)
                    {
                        String DestPath = Destination + Entry.Path.Replace("/", "\\");
                        if (!Directory.Exists(Path.GetDirectoryName(DestPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(DestPath));
                        }

                        Input.Seek(Entry.Offset, SeekOrigin.Begin);
                        using (FileStream Output = new FileStream(DestPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                        {
                            ZStream Stream = new ZStream();
                            Stream.inflateInit();

                            Int32 Result = 0;
                            Int32 Length = 0;
                            do
                            {
                                Stream.avail_in      = Input.Read(Buffer, 0, Kernel.MAX_BUFFER_SIZE);
                                Stream.next_in       = Buffer;
                                Stream.next_in_index = 0;

                                if (Stream.avail_in == 0)
                                {
                                    break;
                                }

                                do
                                {
                                    Stream.avail_out      = Kernel.MAX_BUFFER_SIZE;
                                    Stream.next_out       = Tmp;
                                    Stream.next_out_index = 0;

                                    Result = Stream.inflate(zlibConst.Z_NO_FLUSH);

                                    Length = Kernel.MAX_BUFFER_SIZE - Stream.avail_out;
                                    Output.Write(Tmp, 0, Length);
                                }while (Stream.avail_out == 0);
                            }while (Result != zlibConst.Z_STREAM_END);

                            Stream.inflateEnd();
                        }
                    }
                }
            }
Ejemplo n.º 10
0
        private static (byte[] bytes, int res) DecompressZ(byte[] inbuf, int index = 0)
        {
            var z      = new ZStream();
            var ms     = new MemoryStream();
            var outbuf = new byte[1024];

            if (z.inflateInit() != zlibConst.Z_OK)
            {
                throw new InvalidOperationException("zlib.inflateInit Error");
            }

            z.next_in       = inbuf;
            z.avail_in      = inbuf.Length;
            z.next_in_index = index;

            z.next_out       = outbuf;
            z.avail_out      = outbuf.Length;
            z.next_out_index = 0;

            while (true)
            {
                int status = z.inflate(zlibConst.Z_NO_FLUSH); /* 展開 */
                if (status == zlibConst.Z_STREAM_END)
                {
                    break;
                }

                if (status != zlibConst.Z_OK)
                {
                    throw new InvalidOperationException("zlib.inflate Error");
                }

                if (z.avail_out == 0)
                {
                    ms.Write(outbuf, 0, outbuf.Length);
                    z.next_out       = outbuf;
                    z.avail_out      = outbuf.Length;
                    z.next_out_index = 0;
                }
            }

            if ((outbuf.Length - z.avail_out) != 0)
            {
                ms.Write(outbuf, 0, outbuf.Length - z.avail_out);
            }

            if (z.inflateEnd() != zlibConst.Z_OK)
            {
                throw new InvalidOperationException("zlib.inflateEnd Error");
            }

            int count = z.next_in_index - index;

            z.free();

            return(ms.ToArray(), count);
        }
Ejemplo n.º 11
0
 public virtual void Finish()
 {
     do
     {
         z.next_out       = buf;
         z.next_out_index = 0;
         z.avail_out      = buf.Length;
         int num = compress ? z.deflate(4) : z.inflate(4);
         if (num != 1 && num != 0)
         {
             throw new IOException((compress ? "de" : "in") + "flating: " + z.msg);
         }
         int num2 = buf.Length - z.avail_out;
         if (num2 > 0)
         {
             output.Write(buf, 0, num2);
         }
     }while (z.avail_in > 0 || z.avail_out == 0);
     Flush();
 }
Ejemplo n.º 12
0
        async Task <int> ReadAsync(byte[] buffer, int offset, int count, bool doAsync, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (count == 0)
            {
                return(0);
            }

            zIn.next_out       = buffer;
            zIn.next_out_index = offset;
            zIn.avail_out      = count;

            do
            {
                if (zIn.avail_in == 0 && !eos)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    if (doAsync)
                    {
                        zIn.avail_in = await InnerStream.ReadAsync(zIn.next_in, 0, zIn.next_in.Length, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        zIn.avail_in = InnerStream.Read(zIn.next_in, 0, zIn.next_in.Length);
                    }

                    eos = zIn.avail_in == 0;
                    zIn.next_in_index = 0;
                }

                int retval = zIn.inflate(JZlib.Z_FULL_FLUSH);

                if (retval == JZlib.Z_STREAM_END)
                {
                    break;
                }

                if (eos && retval == JZlib.Z_BUF_ERROR)
                {
                    return(0);
                }

                if (retval != JZlib.Z_OK)
                {
                    throw new IOException("Error inflating: " + zIn.msg);
                }
            } while (zIn.avail_out == count);

            return(count - zIn.avail_out);
        }
Ejemplo n.º 13
0
        private static int zlib_inflate_rounds(ZStream zs, int max, out byte[] output)
        {
            int status = zlibConst.Z_OK;
            int round  = 0;

            output = null;
            int bufferFree = 0;
            int bufferSize = (max != 0 && max < zs.avail_in) ? max : zs.avail_in;
            int bufferUsed = 0;

            do
            {
                if (max != 0 && max <= bufferUsed)
                {
                    status = zlibConst.Z_MEM_ERROR;
                }

                try
                {
                    Array.Resize(ref output, bufferSize);
                }
                catch (OutOfMemoryException)
                {
                    status = zlibConst.Z_MEM_ERROR;
                }

                if (status != zlibConst.Z_MEM_ERROR)
                {
                    bufferFree        = bufferSize - bufferUsed;
                    zs.avail_out      = bufferFree;
                    zs.next_out       = output;
                    zs.next_out_index = bufferUsed;

                    status = zs.inflate(zlibConst.Z_NO_FLUSH);

                    bufferUsed += bufferFree - zs.avail_out;
                    bufferFree  = zs.avail_out;

                    bufferSize += (bufferSize >> 3) + 1;
                }
            }while ((status == zlibConst.Z_BUF_ERROR || (status == zlibConst.Z_OK && zs.avail_in != 0)) && ++round < 100);

            if (status == zlibConst.Z_STREAM_END)
            {
                Array.Resize(ref output, bufferUsed);
            }
            else
            {
                status = (status == zlibConst.Z_OK) ? zlibConst.Z_DATA_ERROR : status;
            }

            return(status);
        }
Ejemplo n.º 14
0
        private bool ZIPDecode(byte[] buffer, int offset, int count, short plane)
        {
            const string module = "ZIPDecode";

            Debug.Assert(m_state == ZSTATE_INIT_DECODE);
            m_stream.next_out       = buffer;
            m_stream.next_out_index = offset;
            m_stream.avail_out      = count;
            do
            {
                int state = m_stream.inflate(zlibConst.Z_PARTIAL_FLUSH);
                if (state == zlibConst.Z_STREAM_END)
                {
                    break;
                }

                if (state == zlibConst.Z_DATA_ERROR)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                                  "{0}: Decoding error at scanline {1}, {2}",
                                  m_tif.m_name, m_tif.m_row, m_stream.msg);

                    if (m_stream.inflateSync() != zlibConst.Z_OK)
                    {
                        return(false);
                    }

                    continue;
                }

                if (state != zlibConst.Z_OK)
                {
                    Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                                  "{0}: zlib error: {1}", m_tif.m_name, m_stream.msg);
                    return(false);
                }
            }while (m_stream.avail_out > 0);

            if (m_stream.avail_out != 0)
            {
                Tiff.ErrorExt(m_tif, m_tif.m_clientdata, module,
                              "{0}: Not enough data at scanline {1} (short {2} bytes)",
                              m_tif.m_name, m_tif.m_row, m_stream.avail_out);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 15
0
        public int read(byte[] b, int off, int len)
        {
            if (len == 0)
            {
                return(0);
            }
            int err;

            z.next_out       = b;
            z.next_out_index = off;
            z.avail_out      = len;
            do
            {
                if ((z.avail_in == 0) && (!nomoreinput))
                {
                    // if buffer is empty and more input is avaiable, refill it
                    z.next_in_index = 0;
                    z.avail_in      = SupportClass.ReadInput(in_Renamed, buf, 0, bufsize); //(bufsize<z.avail_out ? bufsize : z.avail_out));
                    if (z.avail_in == -1)
                    {
                        z.avail_in  = 0;
                        nomoreinput = true;
                    }
                }
                if (compress)
                {
                    err = z.deflate(flush);
                }
                else
                {
                    err = z.inflate(flush);
                }
                if (nomoreinput && (err == zlibConst.Z_BUF_ERROR))
                {
                    return(-1);
                }
                if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
                {
                    throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
                }
                if (nomoreinput && (z.avail_out == len))
                {
                    return(-1);
                }
            }while (z.avail_out == len && err == zlibConst.Z_OK);
            //System.err.print("("+(len-z.avail_out)+")");
            return(len - z.avail_out);
        }
Ejemplo n.º 16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Block"></param>
        /// <returns></returns>
        public byte[] ReadBlockDecompressed(uint Block)
        {
            if (Block >= NumberOfBlocks)
            {
                return(new byte[0]);
            }
            var In = ReadBlockCompressed(Block);

            // If block is not compressed, get the contents.
            if (!Blocks[Block].IsCompressed)
            {
                return(In);
            }

            var Out = new byte[this.Header.BlockSize];

            In = In.Concat(new byte[] { 0x00 });

            var ZStream = new ZStream();

            if (ZStream.inflateInit(-15) != zlibConst.Z_OK)
            {
                throw (new InvalidProgramException("Can't initialize inflater"));
            }
            try
            {
                ZStream.next_in       = In;
                ZStream.next_in_index = 0;
                ZStream.avail_in      = In.Length;

                ZStream.next_out       = Out;
                ZStream.next_out_index = 0;
                ZStream.avail_out      = Out.Length;

                int Status = ZStream.inflate(zlibConst.Z_FULL_FLUSH);
                if (Status != zlibConst.Z_STREAM_END)
                {
                    throw (new InvalidDataException("" + ZStream.msg));
                }
            }
            finally
            {
                ZStream.inflateEnd();
            }

            return(Out);
        }
Ejemplo n.º 17
0
        public static byte[] Uncompress(byte[] compressed, int start, int size, int maxUncompressedSize)
        {
            ZStream stream = new ZStream();

            stream.next_in       = compressed;
            stream.next_in_index = start;
            stream.avail_in      = compressed.Length;

            byte[] uncompressed = new byte[maxUncompressedSize];
            stream.next_out       = uncompressed;
            stream.next_out_index = 0;
            stream.avail_out      = maxUncompressedSize;

            int err = stream.inflateInit();

            if (err != zlibConst.Z_OK)
            {
                return(null);
            }

            err = stream.inflate(zlibConst.Z_FINISH);
            if (err != zlibConst.Z_STREAM_END)
            {
                stream.inflateEnd();
                return(null);
            }

            int realSize = (int)stream.total_out;

            err = stream.inflateEnd();
            if (err != zlibConst.Z_OK)
            {
                return(null);
            }

            if (realSize < maxUncompressedSize)
            {
                byte[] temp = new byte[realSize];
                Array.Copy(uncompressed, temp, realSize);
                return(temp);
            }
            else
            {
                return(uncompressed);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </summary>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
        /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The buffer offset.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public override int Read(byte[] buffer, int offset, int count)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (count == 0)
            {
                return(0);
            }

            zIn.next_out       = buffer;
            zIn.next_out_index = offset;
            zIn.avail_out      = count;

            do
            {
                if (zIn.avail_in == 0 && !eos)
                {
                    zIn.avail_in      = BaseStream.Read(zIn.next_in, 0, zIn.next_in.Length);
                    eos               = zIn.avail_in == 0;
                    zIn.next_in_index = 0;
                }

                int retval = zIn.inflate(JZlib.Z_FULL_FLUSH);

                if (retval == JZlib.Z_STREAM_END)
                {
                    break;
                }

                if (eos && retval == JZlib.Z_BUF_ERROR)
                {
                    return(0);
                }

                if (retval != JZlib.Z_OK)
                {
                    throw new IOException("Error inflating: " + zIn.msg);
                }
            } while (zIn.avail_out == count);

            return(count - zIn.avail_out);
        }
Ejemplo n.º 19
0
        public static byte[] Decompress(byte[] pBuffer, ZStream iStream)
        {
            byte[] rBuff = new byte[pBuffer.Length + 4];
            Array.Copy(pBuffer, 0, rBuff, 0, pBuffer.Length);

            rBuff[rBuff.Length - 4] = 0x00;
            rBuff[rBuff.Length - 3] = 0x00;
            rBuff[rBuff.Length - 2] = 0xFF;
            rBuff[rBuff.Length - 1] = 0xFF;

            iStream.total_in  = 0;
            iStream.total_out = 0;

            iStream.next_in       = rBuff;
            iStream.next_in_index = 0;
            iStream.avail_in      = rBuff.Length;

            MemoryStream lStream = new MemoryStream();

            do
            {
                byte[] oBuff = new byte[pBuffer.Length * 8];

                iStream.next_out       = oBuff;
                iStream.next_out_index = 0;
                iStream.avail_out      = pBuffer.Length * 8;

                int ret = iStream.inflate(2);

                if (ret != 0)
                {
                    Log.Write(LogLevel.Error, "Inflate error [{0}]:\n{1}", ret, iStream.msg);
                    break;
                }

                lStream.Write(oBuff, 0, (pBuffer.Length * 8) - iStream.avail_out);
            }while (iStream.avail_in != 0 || iStream.avail_out == 0);
            byte[] rBASD = lStream.ToArray();

            lStream.Dispose();

            return(rBASD);
        }
Ejemplo n.º 20
0
    public override int Read(byte[] b, int off, int len)
    {
        if (len == 0)
        {
            return(0);
        }
        z.next_out       = b;
        z.next_out_index = off;
        z.avail_out      = len;
        int num;

        do
        {
            if (z.avail_in == 0 && !nomoreinput)
            {
                z.next_in_index = 0;
                z.avail_in      = inp.Read(buf, 0, 4192);
                if (z.avail_in <= 0)
                {
                    z.avail_in  = 0;
                    nomoreinput = true;
                }
            }
            num = z.inflate(flushLevel);
            if (nomoreinput && num == -5)
            {
                return(0);
            }
            if (num != 0 && num != 1)
            {
                throw new IOException("inflating: " + z.msg);
            }
            if ((nomoreinput || num == 1) && z.avail_out == len)
            {
                return(0);
            }
        }while (z.avail_out == len && num == 0);
        return(len - z.avail_out);
    }
Ejemplo n.º 21
0
        private byte[] inflate_file(BinaryReader reader, long length)
        {
            byte[] uncompressed = new byte[length * 16];

            ZStream strm = new ZStream();

            strm.next_in   = reader.ReadBytes((int)length);
            strm.avail_in  = (int)length;
            strm.avail_out = 0;
            var code = strm.inflateInit(-15);

            var output = new System.Collections.Generic.List <byte>();

            while (code == zlibConst.Z_OK && strm.avail_out == 0)
            {
                strm.next_out  = uncompressed;
                strm.avail_out = uncompressed.Length;
                code           = strm.inflate(zlibConst.Z_SYNC_FLUSH);

                switch (code)
                {
                case zlibConst.Z_OK:
                    for (int i = 0; i < uncompressed.Length; i++)
                    {
                        output.Add(uncompressed[i]);
                    }
                    break;

                case zlibConst.Z_STREAM_END:
                    for (int i = 0; i < uncompressed.Length - strm.avail_out; i++)
                    {
                        output.Add(uncompressed[i]);
                    }
                    break;
                }
            }

            return(output.ToArray());
        }
Ejemplo n.º 22
0
        internal void Decompress(int type)
        {
            if (this is NetworkClient)
            {
                throw new Exception("Trying to decompress data on Client connection!");
            }

            zStream_Length = 0;

            zStream.avail_in      = inMaxIndex - inIndex;
            zStream.next_in       = inData;
            zStream.next_in_index = inIndex;

            zStream.next_out       = zStream_Out;
            zStream.next_out_index = 0;
            zStream.avail_out      = zStream_Out.Length;

            switch (zStream.inflate(type))
            {
            case zlibConst.Z_OK:
                inIndex           = zStream.next_in_index;
                zStream_Length    = (int)zStream.total_out;
                zStream.total_out = 0;
                break;

            case zlibConst.Z_STREAM_END:
                inIndex        = zStream.next_in_index;
                zStream_Length = (int)zStream.total_out;
                zStream.inflateEnd();
                zStream.free();
                zStream = null;
                break;

            default:
                //case zlibConst.Z_STREAM_ERROR:
                throw new Exception("Error while decompressing: " + (zStream.msg ?? "unknown error") + "!");
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Reimplements function from zlib (uncompress) that is not present in ZLIB.NET.
        /// </summary>
        /// <param name="dest">Destination array of bytes. May be trimmed if necessary.</param>
        /// <param name="source">Source array of bytes.</param>
        /// <param name="msg">Eventual message from zstream.</param>
        /// <returns>Zlib status code.</returns>
        static int ZlibUncompress(ref byte[] dest, byte[] source, out string msg)
        {
            var zs = new ZStream();
            int err;

            zs.next_in   = source;
            zs.avail_in  = source.Length;
            zs.next_out  = dest;
            zs.avail_out = dest.Length;

            err = zs.inflateInit();
            if (err != zlibConst.Z_OK)
            {
                msg = zs.msg;
                return(err);
            }

            err = zs.inflate(zlibConst.Z_FINISH);
            if (err != zlibConst.Z_STREAM_END)
            {
                zs.inflateEnd();
                msg = zs.msg;
                return(err == zlibConst.Z_OK ? zlibConst.Z_BUF_ERROR : err);
            }

            if (zs.total_out != dest.Length)
            {
                byte[] output = new byte[zs.total_out];
                Buffer.BlockCopy(zs.next_out, 0, output, 0, (int)zs.total_out);
                dest = output;
            }

            msg = zs.msg;

            return(zs.inflateEnd());
        }
Ejemplo n.º 24
0
        public static PhpString gzinflate(byte[] data, long length = 0)
        {
            uint factor = 1, maxfactor = 16;

            long ilength;

            var zs = new ZStream();

            zs.avail_in  = data.Length;
            zs.next_in   = data;
            zs.total_out = 0;

            // -15 omits the header (undocumented feature of zlib)
            int status = zs.inflateInit(-15);

            if (status != zlibConst.Z_OK)
            {
                PhpException.Throw(PhpError.Warning, zError(status));
                return(default(PhpString));
            }

            do
            {
                ilength = length != 0 ? length : data.Length * (1 << (int)(factor++));

                try
                {
                    byte[] newOutput = new byte[ilength];

                    if (zs.next_out != null)
                    {
                        Buffer.BlockCopy(zs.next_out, 0, newOutput, 0, zs.next_out.Length);
                    }

                    zs.next_out = newOutput;
                }
                catch (OutOfMemoryException)
                {
                    zs.inflateEnd();
                    return(default(PhpString));
                }

                zs.next_out_index = (int)zs.total_out;
                zs.avail_out      = unchecked ((int)(ilength - zs.total_out));
                status            = zs.inflate(zlibConst.Z_NO_FLUSH);
            }while ((status == zlibConst.Z_BUF_ERROR || (status == zlibConst.Z_OK && (zs.avail_in != 0 || zs.avail_out == 0))) && length == 0 && factor < maxfactor);

            zs.inflateEnd();

            if ((length != 0 && status == zlibConst.Z_OK) || factor >= maxfactor)
            {
                status = zlibConst.Z_MEM_ERROR;
            }

            if (status == zlibConst.Z_STREAM_END || status == zlibConst.Z_OK)
            {
                byte[] result = new byte[zs.total_out];
                Buffer.BlockCopy(zs.next_out, 0, result, 0, (int)zs.total_out);
                return(new PhpString(result));
            }
            else
            {
                PhpException.Throw(PhpError.Warning, zError(status) ?? zs.msg);
                return(default(PhpString));
            }
        }
Ejemplo n.º 25
0
 protected override int PerformZlibOperation(ZStream zs, int flush)
 {
     return(zs.inflate(flush));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Reads NBT data from the specified (compressed) stream.
        /// </summary>
        public static NBTNamedTag <INBTData> ReadChunk(Stream fs, Point <int> Pos)
        {
            // Read the chunk from the file.

            byte[] buf          = new byte[5];
            long   seekOffset   = 0;
            int    sectorNumber = 0;
            int    offset       = 0;
            // Read the chunk offset.
            Point <int> chunkOffsetInRegion;

            chunkOffsetInRegion.X = Pos.X % 32;
            if (chunkOffsetInRegion.X < 0)
            {
                chunkOffsetInRegion.X += 32;
            }
            chunkOffsetInRegion.Y = Pos.Y % 32;
            if (chunkOffsetInRegion.Y < 0)
            {
                chunkOffsetInRegion.Y += 32;
            }

            seekOffset  = 4 * (chunkOffsetInRegion.X + chunkOffsetInRegion.Y * 32);
            fs.Position = seekOffset;
            fs.Read(buf, 0, 4);
            sectorNumber = (int)buf[3];
            offset       = (int)buf[0] << 16 | (int)buf[1] << 8 | (int)buf[2];

            if (offset == 0)
            {
                throw new ArithmeticException();
            }

            // Get the chunk length and version.
            int chunkLength = 0;

            fs.Position = offset * 4096;
            fs.Read(buf, 0, 5);
            chunkLength = (int)buf[0] << 24 | (int)buf[1] << 14 | (int)buf[2] << 8 | (int)buf[3];

            if (chunkLength > sectorNumber * 4096 || chunkLength > CHUNK_DEFLATE_MAX)
            {
                throw new ArithmeticException();
            }

            if (buf[4] != 2)
            {
                throw new ArithmeticException();
            }

            // Read compressed chunk data.
            byte[] inChunk  = new byte[CHUNK_DEFLATE_MAX];
            byte[] outChunk = new byte[CHUNK_INFLATE_MAX];

            fs.Read(inChunk, 0, chunkLength - 1);

            fs.Close();

            // Decompress it.
            ZStream z = new ZStream();

            z.next_out  = outChunk;
            z.avail_out = CHUNK_INFLATE_MAX;
            z.next_in   = inChunk;
            z.avail_in  = chunkLength - 1;
            z.inflateInit();
            z.inflate(zlibConst.Z_NO_FLUSH);
            z.inflateEnd();

            System.IO.MemoryStream msUncompressed = new System.IO.MemoryStream(outChunk);

            return(NBT.ReadUncompressed(msUncompressed));
        }
Ejemplo n.º 27
0
            /// <summary>
            /// Get the data of the entry linked by the specified path.
            /// All the data will be allocated in memory. It may fail.
            ///
            /// Return false if the entry does not exist.
            /// </summary>
            public Boolean GetEntryData(String Path, Byte **pData, Int32 *pLength)
            {
                *pData = null;

                if (Path.StartsWith("/") || Path.StartsWith("\\"))
                {
                    return(false);
                }

                Entry Entry;

                lock (Entries)
                {
                    if (!Entries.TryGetValue(Path.ToLowerInvariant().Replace('\\', '/'), out Entry))
                    {
                        return(false);
                    }
                }

                *pData   = (Byte *)Kernel.malloc((Int32)Entry.UncompressedSize);
                *pLength = (Int32)Entry.UncompressedSize;
                using (FileStream Input = new FileStream(TpdFile.GetFilename(), FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Byte[] Buffer = new Byte[Kernel.MAX_BUFFER_SIZE];
                    Byte[] Tmp    = new Byte[Kernel.MAX_BUFFER_SIZE];
                    Int32  Pos    = 0;

                    Input.Seek(Entry.Offset, SeekOrigin.Begin);

                    {
                        ZStream Stream = new ZStream();
                        Stream.inflateInit();

                        Int32 Result = 0;
                        Int32 Length = 0;
                        do
                        {
                            Stream.avail_in      = Input.Read(Buffer, 0, Kernel.MAX_BUFFER_SIZE);
                            Stream.next_in       = Buffer;
                            Stream.next_in_index = 0;

                            if (Stream.avail_in == 0)
                            {
                                break;
                            }

                            do
                            {
                                Stream.avail_out      = Kernel.MAX_BUFFER_SIZE;
                                Stream.next_out       = Tmp;
                                Stream.next_out_index = 0;

                                Result = Stream.inflate(zlibConst.Z_NO_FLUSH);

                                Length = Kernel.MAX_BUFFER_SIZE - Stream.avail_out;
                                Kernel.memcpy((*pData) + Pos, Tmp, Length);
                                Pos += Length;
                            }while (Stream.avail_out == 0);
                        }while (Result != zlibConst.Z_STREAM_END);

                        Stream.inflateEnd();
                    }
                }
                return(true);
            }
Ejemplo n.º 28
0
        /// <summary>
        /// Returns the spectrum-data (m/z and intensity) of the given scan number.  The boundries
        /// for the scan number can be retrieved with <see cref="GetFirstSpectrumNumber"/> and
        /// <see cref="GetLastSpectrumNumber"/>. This method will throw an exception when the given
        /// scan number is outside these boundries. The spectrum data is returned as a 2-dimensional
        /// list of size (2, nrspectra) in emulation of the thermo RAW access DLL.
        /// </summary>
        /// <param name="scannumber">The scan number.</param>
        /// <returns>The scan-data.</returns>
        public double[,] GetMassListFromScanNum(int scannumber)
        {
            if (scannumber < minScanNumber || scannumber > maxScanNumber)
            {
                throw new Exception("Undefined scan number: " + scannumber + " outside (" + minScanNumber + "," + maxScanNumber +
                                    ")");
            }
            int           compressedLength = 0;
            string        compressionType  = null;
            int           precision        = -1;
            string        byteOrder        = null;
            string        contentType      = null;
            string        data             = null;
            string        peakData         = GetScanPeakData(scannumber);
            XmlTextReader xmlReader        = new XmlTextReader(new StringReader(peakData));

            while (xmlReader.Read())
            {
                xmlReader.MoveToElement();
                if (!xmlReader.IsStartElement("peaks"))
                {
                    continue;
                }
                precision   = Parser.Int(xmlReader.GetAttribute("precision"));
                byteOrder   = xmlReader.GetAttribute("byteOrder");
                contentType = xmlReader.GetAttribute("contentType");
                if (string.IsNullOrEmpty(contentType))
                {
                    contentType = xmlReader.GetAttribute("pairOrder");
                }
                compressionType = xmlReader.GetAttribute("compressionType");
                string sCompressedLen = xmlReader.GetAttribute("compressedLen");
                compressedLength = string.IsNullOrEmpty(sCompressedLen) ? -1 : Parser.Int(sCompressedLen);
                data             = xmlReader.ReadElementContentAsString();
            }
            if (byteOrder == null || contentType == null || data == null)
            {
                throw new Exception("Malformed mz-xml File.");
            }
            if (!contentType.Equals("m/z-int") && !contentType.Equals("mz-int"))
            {
                throw new Exception("Non-supported content type: ' " + contentType + "'.");
            }
            // convert from base64 encoding
            byte[] bytes = Convert.FromBase64String(data);
            // decompress
            if (compressionType != null && compressionType.Equals("zlib"))
            {
                if (compressedLength != bytes.Length)
                {
                    throw new Exception("Attribute 'compressedLen' has a different value from the reconstructed data array.");
                }
                ZStream   z         = new ZStream();
                const int bufferLen = 1024;
                z.next_in       = bytes;
                z.next_in_index = 0;
                z.avail_in      = bytes.Length;
                z.inflateInit();
                int           totalLength = 0;
                List <byte[]> pieces      = new List <byte[]>();
                while (true)
                {
                    z.next_out       = new byte[bufferLen];
                    z.next_out_index = 0;
                    z.avail_out      = bufferLen;
                    pieces.Add(z.next_out);
                    int err = z.inflate(zlibConst.Z_NO_FLUSH);
                    totalLength += bufferLen - z.avail_out;
                    if (err == zlibConst.Z_STREAM_END)
                    {
                        break;
                    }
                    if (err != zlibConst.Z_OK)
                    {
                        throw new ZStreamException(z.msg);
                    }
                }
                z.inflateEnd();
                bytes = new byte[totalLength];
                int pos = 0;
                foreach (byte[] piece in pieces)
                {
                    Buffer.BlockCopy(piece, 0, bytes, pos, totalLength - pos > 1024 ? bufferLen : totalLength - pos);
                    pos += piece.Length;
                }
            }
            // convert from byte encoding
            double[] massintensities = ByteArray.ToDoubleArray(bytes,
                                                               byteOrder.Equals("network") ? ByteArray.endianBig : ByteArray.endianLittle, precision);
            double[,] masslist = new double[2, massintensities.Length / 2];
            for (int i = 0; i < massintensities.Length; i += 2)
            {
                masslist[0, i / 2] = massintensities[i];
                masslist[1, i / 2] = massintensities[i + 1];
            }
            return(masslist);
        }
Ejemplo n.º 29
0
        internal static byte[] Decompress(byte[] input, int wbits = MAX_WBITS, int bufsize = DEFAULTALLOC)
        {
            byte[] outputBuffer = new byte[bufsize];
            byte[] output       = new byte[bufsize];
            int    outputOffset = 0;

            ZStream zst = new ZStream();

            zst.next_in   = input;
            zst.avail_in  = input.Length;
            zst.next_out  = outputBuffer;
            zst.avail_out = outputBuffer.Length;

            int err = zst.inflateInit(wbits);

            if (err != Z_OK)
            {
                zst.inflateEnd();
                throw zlib_error(zst, err, "while preparing to decompress data");
            }

            do
            {
                err = zst.inflate(FlushStrategy.Z_FINISH);
                if (err != Z_STREAM_END)
                {
                    if (err == Z_BUF_ERROR && zst.avail_out > 0)
                    {
                        zst.inflateEnd();
                        throw zlib_error(zst, err, "while decompressing data");
                    }
                    else if (err == Z_OK || (err == Z_BUF_ERROR && zst.avail_out == 0))
                    {
                        // copy to the output and reset the buffer
                        if (outputOffset + outputBuffer.Length > output.Length)
                        {
                            Array.Resize(ref output, output.Length * 2);
                        }

                        Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length);
                        outputOffset += outputBuffer.Length;

                        zst.next_out       = outputBuffer;
                        zst.avail_out      = outputBuffer.Length;
                        zst.next_out_index = 0;
                    }
                    else
                    {
                        zst.inflateEnd();
                        throw zlib_error(zst, err, "while decompressing data");
                    }
                }
            } while(err != Z_STREAM_END);

            err = zst.inflateEnd();
            if (err != Z_OK)
            {
                throw zlib_error(zst, err, "while finishing data decompression");
            }

            if (outputOffset + outputBuffer.Length - zst.avail_out > output.Length)
            {
                Array.Resize(ref output, output.Length * 2);
            }

            Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length - zst.avail_out);
            outputOffset += outputBuffer.Length - zst.avail_out;

            return(output.Take(outputOffset).ToArray());
        }
Ejemplo n.º 30
0
        public static BufLen BCGZipDecompressNew(BufLen buf)
        {
            var reader = new BufRefLen(buf);

            // Skip gzip header
            var gzheader = reader.ReadBufLen(10);
            var flag     = gzheader.Peek8(3);

            if ((flag & 0x04) != 0)
            {
                reader.Seek(reader.Read16());                           // "Extra"
            }
            if ((flag & 0x08) != 0)
            {
                while (reader.Read8() != 0)
                {
                    ;                                                   // "Name"
                }
            }
            if ((flag & 0x10) != 0)
            {
                while (reader.Read8() != 0)
                {
                    ;                                                   // "Comment"
                }
            }
            if ((flag & 0x02) != 0)
            {
                reader.Read16();                         // "CRC16"
            }
            var z = new ZStream();
            z.inflateInit(true);

            var dest   = new byte[buf.Length * 2];
            var destix = 0;

            z.next_in_index = reader.BaseArrayOffset;
            z.next_in       = reader.BaseArray;
            z.avail_in      = reader.Length - 8;

bigger_dest:

            z.next_out       = dest;
            z.next_out_index = destix;
            z.avail_out      = dest.Length - destix;
            var err = z.inflate(JZlib.Z_FINISH);
            if (err != JZlib.Z_BUF_ERROR && err != JZlib.Z_OK && err != JZlib.Z_STREAM_END)
            {
                throw new IOException("inflating: " + z.msg);
            }

            if (z.avail_out == 0)
            {
                var newdest = new byte[dest.Length * 2];
                Array.Copy(dest, newdest, dest.Length);
                destix = dest.Length;
                dest   = newdest;
                goto bigger_dest;
            }

            var result = new BufLen(dest, 0, dest.Length - z.avail_out);
            z.inflateEnd();

            return(result);
        }