Compression
Gzip and deflate done by the browser's own native codec - useful on WebAssembly, where compressing a few megabytes in managed code runs on the single UI thread.
@inject Bit.Butil.Compression compressionMDN reference
GZipStream, and on Blazor Server that is the better tool. This
earns its place on WebAssembly: the browser's implementation is native rather than interpreted,
and not pulling the managed compression code into the published bundle is worth something on
its own.
Returns true when the runtime exposes CompressionStream. During prerender/SSR the check returns false rather than throwing, so defer it to OnAfterRenderAsync.
@inject Bit.Butil.Compression compression
var supported = await compression.IsSupported();The convenience pair for the common case: shrink a JSON payload before putting it in LocalStorage or IndexedDb, and expand it on the way back out. Text is encoded as UTF-8 in both directions. A corrupt payload comes back as null rather than throwing - bad data from storage or the network is a normal outcome, not an exceptional one.
var packed = await compression.CompressText(json); // byte[]?
var original = await compression.DecompressText(packed!); // string?
// pick a codec explicitly:
var raw = await compression.CompressText(json, CompressionFormat.DeflateRaw);The byte overloads take whatever you have. Which codec to pick depends on what is at the other end: Gzip is the interoperable default and matches .NET's GZipStream. Deflate is the zlib-wrapped variant that matches ZLibStream - and note that .NET's DeflateStream is actually the raw variant, so pair that one with DeflateRaw.
var packed = await compression.Compress(bytes, CompressionFormat.Gzip);
var original = await compression.Decompress(packed!, CompressionFormat.Gzip);
// matching .NET on the server:
// GZipStream <-> CompressionFormat.Gzip
// ZLibStream <-> CompressionFormat.Deflate
// DeflateStream <-> CompressionFormat.DeflateRawAPI reference
ValueTask<bool> IsSupported()ValueTask<byte[]?> Compress(byte[] data, CompressionFormat format = CompressionFormat.Gzip)ValueTask<byte[]?> Decompress(byte[] data, CompressionFormat format = CompressionFormat.Gzip)ValueTask<byte[]?> CompressText(string text, CompressionFormat format = CompressionFormat.Gzip)ValueTask<string?> DecompressText(byte[] data, CompressionFormat format = CompressionFormat.Gzip)Gzip | Deflate | DeflateRaw