Path: redb-route/redb.Route/Serialization/GZipMessageSerializer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Serialization/GZipMessageSerializer.cs
----
using System.IO.Compression;
namespace redb.Route.Serialization;
/// GZip as a data format: Marshal("application/gzip") compresses the body, Unmarshal<string>("application/gzip") decompresses it.
public sealed class GZipMessageSerializer : BinaryWrapperSerializer
{
/// Content type the format is registered under by default.
public const string DefaultContentType = "application/gzip";
private readonly CompressionLevel _level;
private readonly long _maxDecodedBytes;
/// Creates the format.
/// Compression level (default ).
/// Cap on the decompressed size (default , 128 MB); a body that expands past it is refused.
public GZipMessageSerializer(CompressionLevel level = CompressionLevel.Optimal, long maxDecodedBytes = DefaultMaxDecodedBytes)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxDecodedBytes);
_level = level;
_maxDecodedBytes = maxDecodedBytes;
}
///
public override string ContentType => DefaultContentType;
///
public override IReadOnlyCollection MediaTypes => [DefaultContentType, "application/x-gzip"];
///
protected override string FormatName => "GZip";
///
protected override byte[] Encode(byte[] payload)
{
using var output = new MemoryStream();
using (var gzip = new GZipStream(output, _level, leaveOpen: true))
gzip.Write(payload);
return output.ToArray();
}
///
protected override byte[] Decode(byte[] data)
{
using var input = new MemoryStream(data, writable: false);
using var gzip = new GZipStream(input, CompressionMode.Decompress);
return ReadBounded(gzip, _maxDecodedBytes, FormatName);
}
}