This commit is contained in:
Dan Clark
2025-02-10 12:50:45 +00:00
parent 18ceb512f6
commit f6e55b7a21
8 changed files with 150 additions and 69 deletions
+66
View File
@@ -0,0 +1,66 @@
using System.Buffers;
using System.IO.Pipelines;
namespace Toolkit.Foundation;
public class SerialStructReader(Stream stream) :
SerialReader<SerialStructEventArgs>(stream)
{
private readonly PipeReader reader = PipeReader.Create(stream);
public override async IAsyncEnumerable<SerialStructEventArgs> ReadAsync()
{
while (true)
{
ReadResult? result = default;
try
{
result = await reader.ReadAsync();
}
catch (IOException)
{
continue;
}
catch (OperationCanceledException)
{
yield break;
}
catch (Exception)
{
yield break;
}
if (result.HasValue)
{
ReadOnlySequence<byte> buffer = result.Value.Buffer;
while (TryParse(ref buffer, out SerialStructEventArgs serialEvent))
{
yield return serialEvent;
}
reader.AdvanceTo(buffer.Start, buffer.End);
}
}
}
private bool TryParse(ref ReadOnlySequence<byte> buffer, out SerialStructEventArgs serialEvent)
{
SequenceReader<byte> reader = new(buffer);
serialEvent = default!;
if (reader.Remaining < 3)
return false;
if (!reader.TryRead(out byte type))
return false;
if (!reader.TryReadLittleEndian(out short value))
return false;
serialEvent = new SerialStructEventArgs(type, value);
buffer = buffer.Slice(reader.Position);
return true;
}
}