private long LoadBlock(long beginning, long end, ref byte[] buf)
{
long bufSize = buf.LongLength;
bzip2.StatusCode status = bzip2.BZ2_bzLoadBlock(filePath, beginning, end, buf, ref bufSize);
if (status != bzip2.StatusCode.BZ_OK)
{
throw new Exception(String.Format(Properties.Resources.FailedLoadingBlock, filePath, beginning, status));
}
// Just some initial value, we will reallocate the buffer as needed
if (decompressionBuf == null)
{
decompressionBuf = new byte[buf.Length * 4];
}
int intBufSize = (int)bufSize;
int intDecompSize = decompressionBuf.Length;
status = bzip2.BZ2_bzDecompress(buf, intBufSize, decompressionBuf, ref intDecompSize);
// Limit a single uncompressed block size to 32 Mb
while (status == bzip2.StatusCode.BZ_OUTBUFF_FULL &&
decompressionBuf.Length < 32000000)
{
decompressionBuf = new byte[decompressionBuf.Length * 2];
intDecompSize = decompressionBuf.Length;
status = bzip2.BZ2_bzDecompress(buf, intBufSize, decompressionBuf, ref intDecompSize);
}
if (decompressionBuf.Length > 32000000)
{
throw new Exception(String.Format(Properties.Resources.FailedUncompressingMemory, beginning));
}
if (status != bzip2.StatusCode.BZ_OK)
{
throw new Exception(String.Format(Properties.Resources.FailedUncompressingStatus, beginning, status));
}
// Exchange the raw buffer and the uncompressed one
byte[] exch = buf;
buf = decompressionBuf;
decompressionBuf = exch;
return intDecompSize;
}