Skip to content

Span-based (non-stream) compression APIs #39327

@timmydo

Description

@timmydo

Background and Motivation

Currently to compress/decompress in .NET, you typically would use GZipStream or DeflateStream. However, there are a lot of times where you have an array of bytes and you want to get your output in an array of bytes. It would be simpler/faster to not have to have a bunch of stream redirection to the underlying byte array.

The request is that we add some methods that operate on bytes.

Proposed API

Roughly something like this

namespace System.IO.Compression
{
public class GZipCompressor
public class DeflateCompressor
{
 private object state;
 public ctor(CompressionLevel)
 public void Compress(ReadOnlySpan<byte> in, Span<byte> out, enum flushType, out uint outputBytesWritten);
}
}

Usage Examples

I'm just sort of pseudo-coding this out:

var input = new List<byte[]> {...};
var output = ArrayPool.Shared.Rent(GetMaxCompressedSize(input.Sum(x => x.Length)));
var compressor = new GZipCompressor(CompressionLevel.Optimal);
var outputIndex = 0;
foreach (var array in input)
{
compressor.Compress(new ReadOnlySpan<byte>(array), new Span<byte>(output, outputIndex, output.Length - outputIndex), Z.NoFlush, out var written)
outputIndex += written;
}

compressor.Compress(default(), new Span<byte>(output, outputIndex, output.Length - outputIndex, Z.FinalFlush, out var finalWrite);

 var finalOutput = new Span<byte>(output, 0, outputIndex + finalWrite);
// do stuff with finalOutput

}

Metadata

Metadata

Assignees

Labels

api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.IO.Compressionin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions