| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using System.Buffers; |
| | | 4 | | |
| | | 5 | | namespace ZeroC.Tests.Common; |
| | | 6 | | |
| | | 7 | | /// <summary>Implements a buffer writer over a single Memory{byte}.</summary> |
| | | 8 | | public class MemoryBufferWriter : IBufferWriter<byte> |
| | | 9 | | { |
| | | 10 | | /// <summary>Gets the written portion of the underlying buffer.</summary> |
| | 3592 | 11 | | public Memory<byte> WrittenMemory => _initialBuffer[0.._written]; |
| | | 12 | | |
| | | 13 | | private Memory<byte> _available; |
| | | 14 | | |
| | | 15 | | private readonly Memory<byte> _initialBuffer; |
| | | 16 | | |
| | | 17 | | private int _written; |
| | | 18 | | |
| | | 19 | | /// <summary>Constructs a new memory buffer writer over a buffer.</summary> |
| | | 20 | | /// <param name="buffer">The underlying buffer.</param> |
| | 453 | 21 | | public MemoryBufferWriter(Memory<byte> buffer) |
| | 453 | 22 | | { |
| | 453 | 23 | | if (buffer.IsEmpty) |
| | 1 | 24 | | { |
| | 1 | 25 | | throw new ArgumentException($"The {nameof(buffer)} cannot be empty.", nameof(buffer)); |
| | | 26 | | } |
| | 452 | 27 | | _initialBuffer = buffer; |
| | 452 | 28 | | _available = _initialBuffer; |
| | 452 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc/> |
| | | 32 | | public void Advance(int count) |
| | 35703 | 33 | | { |
| | 35703 | 34 | | if (count < 0) |
| | 1 | 35 | | { |
| | 1 | 36 | | throw new ArgumentException($"The {nameof(count)} cannot be negative.", nameof(count)); |
| | | 37 | | } |
| | 35702 | 38 | | if (count > _available.Length) |
| | 1 | 39 | | { |
| | 1 | 40 | | throw new InvalidOperationException("Cannot advance past the end of the underlying buffer."); |
| | | 41 | | } |
| | 35701 | 42 | | _written += count; |
| | 35701 | 43 | | _available = _initialBuffer[_written..]; |
| | 35701 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary>Clears the data written to the underlying buffer.</summary> |
| | | 47 | | public void Clear() |
| | 2 | 48 | | { |
| | 2 | 49 | | _written = 0; |
| | 2 | 50 | | _available = _initialBuffer; |
| | 2 | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <inheritdoc/> |
| | | 54 | | public Memory<byte> GetMemory(int sizeHint = 0) |
| | 35709 | 55 | | { |
| | 35709 | 56 | | if (sizeHint > _available.Length) |
| | 1 | 57 | | { |
| | 1 | 58 | | throw new ArgumentException( |
| | 1 | 59 | | $"Requested {sizeHint} bytes from {nameof(MemoryBufferWriter)} but only {_available.Length} bytes are av |
| | 1 | 60 | | nameof(sizeHint)); |
| | | 61 | | } |
| | 35708 | 62 | | return _available; |
| | 35708 | 63 | | } |
| | | 64 | | |
| | | 65 | | /// <inheritdoc/> |
| | 35121 | 66 | | public Span<byte> GetSpan(int sizeHint = 0) => GetMemory(sizeHint).Span; |
| | | 67 | | } |