Path: redb-route/redb.Route/Serialization/BinaryWrapperSerializer.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/BinaryWrapperSerializer.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Serialization; /// /// Base for data formats that wrap bytes rather than serialize an object model (Base64, GZip, Zip). /// Marshal accepts a byte[], a string (UTF-8) or a ; /// Unmarshal yields byte[], string, or object (bytes). /// Anything else is an error that names the format, not a NullReferenceException later. /// public abstract class BinaryWrapperSerializer : IMessageSerializer { /// public abstract string ContentType { get; } /// public virtual IReadOnlyCollection MediaTypes => [ContentType]; /// public bool WrapsBytes => true; /// /// Default cap on the unwrapped size, 128 MB. A body that expands past the cap is refused, so a small /// compressed message cannot exhaust the process memory; raise it per format instance when a bigger /// payload is expected (new GZipMessageSerializer(maxDecodedBytes: …)). /// public const long DefaultMaxDecodedBytes = 128L * 1024 * 1024; /// Wraps the payload (encode / compress). protected abstract byte[] Encode(byte[] payload); /// Unwraps the data (decode / decompress). protected abstract byte[] Decode(byte[] data); /// Short format name for error messages (GZip). protected abstract string FormatName { get; } /// public byte[] Serialize(T value) => Encode(ToBytes(value)); /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(type); byte[] raw; try { raw = Decode(data); } catch (Exception ex) when (ex is FormatException or IOException or InvalidDataException) { throw new InvalidOperationException($"{FormatName} data format: the body is not valid {FormatName} data ({ex.Message}).", ex); } if (type == typeof(byte[]) || type == typeof(object)) return raw; if (type == typeof(string)) return Encoding.UTF8.GetString(raw); if (type == typeof(Stream) || type == typeof(MemoryStream)) return new MemoryStream(raw, writable: false); if (type == typeof(ReadOnlyMemory)) return new ReadOnlyMemory(raw); throw new InvalidOperationException( $"{FormatName} data format wraps bytes: unmarshal to byte[], string or Stream, not {type.Name}."); } private byte[] ToBytes(object? value) => value switch { null => [], byte[] bytes => bytes, string text => Encoding.UTF8.GetBytes(text), ReadOnlyMemory memory => memory.ToArray(), Stream stream => ReadAll(stream), _ => throw new InvalidOperationException( $"{FormatName} data format wraps bytes: the body must be byte[], string or Stream, not {value.GetType().Name}."), }; /// /// Copies the decoded into a buffer, refusing to grow past /// bytes. Thrown as on purpose: it is /// not "invalid data" (the stream may be perfectly valid), it is a body the format refuses to unwrap. /// protected static byte[] ReadBounded(Stream source, long limit, string formatName) { using var output = new MemoryStream(); var buffer = new byte[81920]; long total = 0; int read; while ((read = source.Read(buffer, 0, buffer.Length)) > 0) { total += read; if (total > limit) throw new InvalidOperationException( $"{formatName} data format: the decoded body exceeds the limit of {limit} bytes; raise maxDecodedBytes on the {formatName} format if a body this large is expected."); output.Write(buffer, 0, read); } return output.ToArray(); } private static byte[] ReadAll(Stream stream) { if (stream is MemoryStream ms) return ms.ToArray(); using var buffer = new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); } }