Repository navigation
06. Serialization
ZeroLevel includes a compact, high-throughput binary serializer. It is the same codec used by the network stack and by the PartitionStorage engine — so you can freely mix it with those subsystems.
Two shapes are supported:
| Style | When to use |
|---|---|
Implicit (PrimitiveTypeSerializer) |
Primitives, arrays, collections, dictionaries of well-known types. No code to write. |
Explicit (IBinarySerializable) |
Your custom types. You write Serialize / Deserialize. |
The entry point is MessageSerializer.
using ZeroLevel.Services.Serialization;
public sealed class Payload : IBinarySerializable
{
public string Title;
public DateTimeOffset CreatedAt;
public int[] Tags;
public void Serialize(IBinaryWriter w)
{
w.WriteString(Title);
w.WriteDateTimeOffset(CreatedAt);
w.WriteIntArray(Tags);
}
public void Deserialize(IBinaryReader r)
{
Title = r.ReadString();
CreatedAt = r.ReadDateTimeOffset();
Tags = r.ReadIntArray();
}
}
byte[] bytes = MessageSerializer.Serialize(new Payload
{
Title = "hello",
CreatedAt = DateTimeOffset.UtcNow,
Tags = new[] { 1, 2, 3 },
});
Payload back = MessageSerializer.Deserialize<Payload>(bytes);Deserialization of IBinarySerializable uses FormatterServices.GetUninitializedObject — your constructor is not called. Initialize everything in Deserialize.
For types without IBinarySerializable, MessageSerializer.SerializeCompatible<T> picks a path automatically:
byte[] bytes = MessageSerializer.SerializeCompatible<MyDto>(dto);
MyDto back = MessageSerializer.DeserializeCompatible<MyDto>(bytes);Supported out of the box (~50 kinds, including nullable / arrays / collections / dictionaries):
- Primitives:
byte,sbyte,short,ushort,int,uint,long,ulong,float,double,decimal,bool,char. - Strings and
Guid. -
DateTime,DateTimeOffset,TimeSpan. -
IPAddress,IPEndPoint. -
byte[],char[], arrays of all above. -
List<T>,IEnumerable<T>,HashSet<T>of supported element types. -
Dictionary<TKey, TValue>with supported key/value types. -
Nullable<T>of any primitive.
PrimitiveTypeSerializer compiles expression trees once per (type, direction) pair and caches the delegates, so subsequent calls are JIT-fast.
IBinaryReader / IBinaryWriter expose the full low-level surface:
using var ms = new MemoryStream();
using (var w = new MemoryStreamWriter(ms))
{
w.WriteInt32(42);
w.WriteString("hello");
w.WriteCollection(new[] { new Payload(), new Payload() });
}
ms.Position = 0;
using (var r = new MemoryStreamReader(ms))
{
var n = r.ReadInt32();
var s = r.ReadString();
var batch = r.ReadCollection<Payload>(); // eager
// or: var lazy = r.ReadCollectionLazy<Payload>(); // streaming
}ReadCollectionLazy<T> returns IEnumerable<T> — items are deserialized as you iterate, so large payloads don't need to fit into a list.
Interfaces IAsyncBinaryReader / IAsyncBinaryWriter mirror the sync ones with Task-returning methods:
public sealed class AsyncPayload : IAsyncBinarySerializable
{
public string Title;
public async Task SerializeAsync(IAsyncBinaryWriter w)
=> await w.WriteStringAsync(Title);
public async Task DeserializeAsync(IAsyncBinaryReader r)
=> Title = await r.ReadStringAsync();
}The async interfaces are not wired into the network stack today — they are primarily for your own stream-based persistence (e.g. FileStream, PipeReader).
- Strings are length-prefixed UTF-8 (
int32length,-1for null). - Collections:
int32count + elements back-to-back. - Dictionaries:
int32count + (key, value) pairs. - Primitives: little-endian, stable across platforms.
-
IBinarySerializableroot:[magic byte][payload].
The format is stable — snapshots written by older versions of ZeroLevel still deserialize cleanly.
- Prefer explicit
IBinarySerializablefor hot paths — no reflection, no type-cache lookups. - Mix freely: your
IBinarySerializable.Serializecan callw.WriteCompatible(someDto)for a nested object without anIBinarySerializableimplementation. - Versioning:
SerializeCompatibletolerates unknown trailing members; for structural changes, bump the wire format yourself (e.g. leadingintversion tag) and branch inDeserialize. - Never expose
IBinarySerializablefields publicly as readonly — the deserializer uses uninitialized objects and sets fields via writer methods, so private/public both work equally.
Application basics
Data & serialization
Networking
Text & search