Skip to content

06. Serialization

ogoun edited this page Apr 23, 2026 · 1 revision

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.

Explicit — IBinarySerializable

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.

Implicit — compiled-expression codec

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.

Streaming readers and writers

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.

Async variants

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).

Wire format in one glance

  • Strings are length-prefixed UTF-8 (int32 length, -1 for null).
  • Collections: int32 count + elements back-to-back.
  • Dictionaries: int32 count + (key, value) pairs.
  • Primitives: little-endian, stable across platforms.
  • IBinarySerializable root: [magic byte][payload].

The format is stable — snapshots written by older versions of ZeroLevel still deserialize cleanly.

Tips

  • Prefer explicit IBinarySerializable for hot paths — no reflection, no type-cache lookups.
  • Mix freely: your IBinarySerializable.Serialize can call w.WriteCompatible(someDto) for a nested object without an IBinarySerializable implementation.
  • Versioning: SerializeCompatible tolerates unknown trailing members; for structural changes, bump the wire format yourself (e.g. leading int version tag) and branch in Deserialize.
  • Never expose IBinarySerializable fields publicly as readonly — the deserializer uses uninitialized objects and sets fields via writer methods, so private/public both work equally.

Clone this wiki locally