Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Wire/CipWriter.cs
T
Joseph Doherty abbaac3615 perf(ab-transport): pool CipWriter, reassembly and frame-header buffers
R07:L5 (AB half): CipWriter rents its working buffer from ArrayPool and returns
it in ToArray (which now completes the writer; later writes throw). A single-reply
Logix read is one copy of the data (no List<byte> + ToArray); a fragmented read
reassembles in a pooled buffer. EncapsulationClient reads the frame header into a
per-session buffer (reads only happen under the session gate) instead of a new
array per reply. Measured per op (scratch A/B, Release): frame encode 784 -> 200 B,
Logix read 1994 -> 1655 B, 3-fragment read 11.9 -> 8.2 KB, EIP round trip
2.75 -> 2.15 KB; encode time 41-46 -> 28-39 ms per 500k, other timings within
noise; Ab.Transport.Tests 3 s before and after. Modbus transports are left to a
follow-up (its lane is still in review).

Refs #747
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
2026-10-22 16:52:26 -04:00

93 lines
4.6 KiB
C#

using System.Buffers;
using System.Buffers.Binary;
namespace ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Wire;
/// <summary>Growable little-endian writer for CIP / EIP frames.</summary>
/// <remarks>
/// R07:L5: the working buffer is rented from <see cref="ArrayPool{T}.Shared"/> (a 256-byte array per request used
/// to be allocated and thrown away) and handed back by <see cref="ToArray"/>, which therefore COMPLETES the writer:
/// the result is the caller's own array, a second <see cref="ToArray"/> returns another copy of it, and any further
/// write throws <see cref="InvalidOperationException"/> (the buffer belongs to the pool again). A writer abandoned
/// before <see cref="ToArray"/> (a builder that threw) simply leaves its buffer to the GC.
/// </remarks>
public sealed class CipWriter
{
private const int InitialCapacity = 256;
private byte[]? _buf = ArrayPool<byte>.Shared.Rent(InitialCapacity);
private byte[]? _result;
/// <summary>Gets the number of bytes written so far.</summary>
public int Length { get; private set; }
private byte[] Buffer => _buf ?? throw new InvalidOperationException(
"This CipWriter was completed by ToArray(); its buffer has been returned to the pool.");
private Span<byte> Take(int n)
{
var buf = Buffer;
if (Length + n > buf.Length)
{
var bigger = ArrayPool<byte>.Shared.Rent(Math.Max(buf.Length * 2, Length + n));
buf.AsSpan(0, Length).CopyTo(bigger);
ArrayPool<byte>.Shared.Return(buf);
_buf = buf = bigger;
}
var s = buf.AsSpan(Length, n);
Length += n;
return s;
}
/// <summary>Appends an unsigned 8-bit value.</summary>
/// <param name="v">The value to write.</param>
/// <returns>This writer, for chaining.</returns>
public CipWriter U8(byte v) { Take(1)[0] = v; return this; }
/// <summary>Appends a little-endian unsigned 16-bit value.</summary>
/// <param name="v">The value to write.</param>
/// <returns>This writer, for chaining.</returns>
public CipWriter U16(ushort v) { BinaryPrimitives.WriteUInt16LittleEndian(Take(2), v); return this; }
/// <summary>Appends a little-endian unsigned 32-bit value.</summary>
/// <param name="v">The value to write.</param>
/// <returns>This writer, for chaining.</returns>
public CipWriter U32(uint v) { BinaryPrimitives.WriteUInt32LittleEndian(Take(4), v); return this; }
/// <summary>Appends a little-endian unsigned 64-bit value.</summary>
/// <param name="v">The value to write.</param>
/// <returns>This writer, for chaining.</returns>
public CipWriter U64(ulong v) { BinaryPrimitives.WriteUInt64LittleEndian(Take(8), v); return this; }
/// <summary>Appends raw bytes.</summary>
/// <param name="v">The bytes to write.</param>
/// <returns>This writer, for chaining.</returns>
public CipWriter Bytes(ReadOnlySpan<byte> v) { v.CopyTo(Take(v.Length)); return this; }
/// <summary>Appends a zero byte if the current length is odd.</summary>
/// <returns>This writer, for chaining.</returns>
public CipWriter PadToEven() { if ((Length & 1) == 1) U8(0); return this; }
/// <summary>Overwrite a u16 already written at <paramref name="offset"/> (length back-patching).</summary>
/// <param name="offset">The offset of the first byte of the u16 to overwrite.</param>
/// <param name="v">The replacement value.</param>
/// <exception cref="ArgumentOutOfRangeException">The two bytes at <paramref name="offset"/> are not already
/// written (an offset in the spare buffer capacity would otherwise be patched silently and lost).</exception>
/// <exception cref="InvalidOperationException">The writer was completed by <see cref="ToArray"/>.</exception>
public void PatchU16(int offset, ushort v)
{
var buf = Buffer;
if (offset < 0 || offset > Length - 2)
throw new ArgumentOutOfRangeException(nameof(offset), offset, $"Cannot patch 2 bytes at {offset}: only {Length} bytes written.");
BinaryPrimitives.WriteUInt16LittleEndian(buf.AsSpan(offset, 2), v);
}
/// <summary>
/// Copies the written bytes to a new array and returns the working buffer to the pool, completing the writer
/// (see the remarks on <see cref="CipWriter"/>).
/// </summary>
/// <returns>The bytes written, in an array the caller owns.</returns>
public byte[] ToArray()
{
if (_result is { } done) return (byte[])done.Clone();
var buf = Buffer;
_result = buf.AsSpan(0, Length).ToArray();
_buf = null;
ArrayPool<byte>.Shared.Return(buf);
return _result;
}
}