Read flags and data-terminated arrays
Intermediate · C#. A flag decomposes into member names; entry entries[] reads until an all-zero element and uint16 trailer[EOF] takes every whole element that remains.
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 -- flags-and-data-sized-arrays
The runner checks READ, EXEC and HIDDEN from 0x0105, two entries before the all-zero terminator, a read-to-end trailer, and a write that appends the terminator. Success includes PASS flags-and-data-sized-arrays.
Try the related browser lesson.
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()
{
FlagsAndDataSizedArrays();
Console.WriteLine("PASS flags-and-data-sized-arrays");
}
private static void FlagsAndDataSizedArrays()
{
// A flag reads as a decomposed name list; `[]` on a struct is an array terminated by an all-zero
// element (the exFAT/APFS habit) and `[EOF]` takes every whole element that remains.
const string definition = """
flag access : uint16 { READ, WRITE, EXEC, HIDDEN = 0x100 };
struct entry { uint8 kind; uint8 size; };
struct root {
access mode;
entry entries[];
uint16 trailer[EOF];
};
""";
var layout = new CStruct(definition);
byte[] bytes = [0x05, 0x01, 1, 10, 2, 20, 0, 0, 0x34, 0x12, 0x78, 0x56];
StructValue root = layout.Parse(bytes, "root");
FlagValueResult mode = root.Get<FlagValueResult>("mode");
Equal("READ|EXEC|HIDDEN", string.Join("|", mode.Names));
True(mode.Has("EXEC") && !mode.Has("WRITE"), "EXEC is set and WRITE is not");
Equal(2, root.Get<IReadOnlyList<object?>>("entries").Count);
Equal((ushort)0x5678, root.Get<ushort>("trailer[1]"));
// Writing appends the terminator element and nothing after the read-to-end array; a flag accepts names.
byte[] written = layout.Serialize(
"root",
new Dictionary<string, object?>
{
["mode"] = "READ|HIDDEN",
["entries"] = new object[] { new Dictionary<string, object?> { ["kind"] = (byte)3, ["size"] = (byte)30 } },
["trailer"] = new ushort[] { 1 },
});
SequenceEqual([0x01, 0x01, 3, 30, 0, 0, 0x01, 0x00], written);
}
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 True(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
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
Drop the final trailer byte.
Answer: The read fails: a partial trailing element is not a whole uint16, and [EOF] never rounds down silently. 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.