Project · Memory

Encode packets with an owned pooled buffer

Return an independent report from each bounded lease and keep byte lengths separate from pool capacity.

All C# source files below are loaded together in the playground. Files written by a run live in its virtual directory.

Program.cs

var packets = new[] { new Packet("B", "café"), new Packet("A", "rune") };
var encoded = packets.Select(PacketEncoder.Encode).ToArray();
foreach (var line in BatchReport.Build(encoded)) Console.WriteLine(line);

Models/Packet.cs

public sealed record Packet(string Id, string Text);
public sealed record EncodedPacket(string Id, int ByteCount, string Hex);

Buffers/PacketEncoder.cs

using System.Buffers;
using System.Text;
public static class PacketEncoder
{
    public static EncodedPacket Encode(Packet packet)
    {
        var pool = ArrayPool<byte>.Shared;
        int required = Encoding.UTF8.GetByteCount(packet.Text);
        byte[] buffer = pool.Rent(required);
        try
        {
            int used = Encoding.UTF8.GetBytes(packet.Text, 0, packet.Text.Length, buffer, 0);
            string hex = Convert.ToHexString(buffer.AsSpan(0, used));
            return new EncodedPacket(packet.Id, used, hex);
        }
        finally { pool.Return(buffer, clearArray: true); }
    }
}

Reports/BatchReport.cs

public static class BatchReport
{
    public static string[] Build(IEnumerable<EncodedPacket> packets)
    {
        var ordered = packets.OrderBy(packet => packet.Id, StringComparer.Ordinal).ToArray();
        var lines = ordered.Select(packet => $"{packet.Id}:{packet.ByteCount}:{packet.Hex}").ToList();
        lines.Add($"total:{ordered.Sum(packet => packet.ByteCount)}");
        return lines.ToArray();
    }
}

PooledPackets.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>