Table of Contents

Reuse a layout with different output storage

Advanced · C#. An owned array is simplest. A span or buffer writer lets the caller provide storage but has different partial-write behavior.

Run this example

Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:

dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- round-trip

The runner checks 34 12 A5 from array, span, and buffer writer; unused capacity preserved. Success includes PASS round-trip.

This example uses the C# API. Browser capabilities and result shapes are described in the browser guide.

Complete program

The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.

Download the complete C# source.

// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;

internal static partial class Program
{
    public static void Main()
    {
        RoundTrip();
        Console.WriteLine("PASS round-trip");
    }

    private static void RoundTrip()
    {
        var layout = new CStruct("struct sample { uint16 id; uint8 flags; };");
        byte[] input = [0x34, 0x12, 0xA5];
        object parsed = layout.Parse(input, "sample");
        SequenceEqual(input, layout.Serialize("sample", parsed));

        Span<byte> destination = stackalloc byte[8];
        destination.Fill(0xCC);
        int written = layout.Serialize(destination, "sample", parsed);
        Equal(3, written);
        SequenceEqual(input, destination[..written].ToArray());
        Equal((byte)0xCC, destination[written]);

        var writer = new ArrayBufferWriter<byte>();
        Equal(3L, layout.Serialize(writer, "sample", parsed));
        SequenceEqual(input, writer.WrittenSpan.ToArray());
    }

    private static void Equal<T>(T expected, T actual)
    {
        if (!EqualityComparer<T>.Default.Equals(expected, actual))
        {
            throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
        }
    }

    private static void SequenceEqual(byte[] expected, byte[] actual)
    {
        if (!expected.AsSpan().SequenceEqual(actual))
        {
            throw new InvalidOperationException(
                $"Expected {Convert.ToHexString(expected)}, received {Convert.ToHexString(actual)}.");
        }
    }
}

Try it and diagnose mistakes

Predict how many bytes are initialized in the eight-byte span.

Answer: Only three. Use the returned count rather than treating all capacity as output. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.

Continue with the related guide or choose another recipe.