public string Read(Stream stream) { int count = stream.Read(_compressedBlock, 0, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength); if (count == 0) { return(string.Empty); } if (!BlockGZipStream.HasValidHeader(count, _compressedBlock)) { throw new InvalidDataException("Found an invalid header when reading the GZip block"); } int blockLength = BitConverter.ToUInt16(_compressedBlock, 16) + 1; int remaining = blockLength - BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength; count = stream.Read(_compressedBlock, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength, remaining); if (count != remaining) { throw new InvalidDataException("Found unexpected truncation when reading the GZip block"); } count = _bgzf.Decompress(_compressedBlock, blockLength, _uncompressedBlock, MaxBlockSize); if (count < 0) { throw new CompressionException("Encountered an error when uncompressing the GZip block"); } return(Encoding.UTF8.GetString(_uncompressedBlock, 0, count)); }
//read the next compressed block into provided buffer public int ReadCompressedBlock(byte[] buffer) { if (buffer.Length < BlockGZipStream.BlockGZipFormatCommon.MaxBlockSize) { throw new InsufficientMemoryException($"Pease provide a buffer at least {BlockGZipStream.BlockGZipFormatCommon.MaxBlockSize} bytes in size."); } int headerSize = _stream.Read(buffer, 0, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength); // handle the case where no data was read if (headerSize == 0) { return(0); } // check the header if (!BlockGZipStream.HasValidHeader(headerSize, buffer)) { throw new CompressionException($"Found an invalid header when reading the GZip block ({_filePath})"); } int blockLength = BitConverter.ToUInt16(buffer, 16) + 1; int expectedDataSize = blockLength - BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength; var dataSize = _stream.Read(buffer, BlockGZipStream.BlockGZipFormatCommon.BlockHeaderLength, expectedDataSize); // handle unexpected truncation if (expectedDataSize != dataSize) { throw new CompressionException($"Found unexpected truncation when reading the GZip block ({_filePath})"); } return(headerSize + dataSize); }