Skip to content

Commit

Permalink
Fix reading from stream
Browse files Browse the repository at this point in the history
  • Loading branch information
ShortDevelopment committed Feb 4, 2023
1 parent 504356d commit 411c237
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions ShortDev.Networking/EndianReader.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.IO;
using System.Text;

Expand Down Expand Up @@ -35,8 +36,8 @@ public ReadOnlySpan<byte> ReadBytes(int length)
{
if (Stream != null)
{
Span<byte> buffer = new byte[length];
Stream.Read(buffer);
var buffer = new byte[length];
ReadStreamInternal(buffer);
return buffer;
}

Expand All @@ -46,11 +47,33 @@ public ReadOnlySpan<byte> ReadBytes(int length)
public void ReadBytes(Span<byte> buffer)
{
if (Stream != null)
Stream.Read(buffer);
ReadStreamInternal(buffer);
else
Buffer.ReadBytes(buffer);
}

/// <summary>
/// <see href="https://github.com/dotnet/runtime/blob/56c84971041ae1debfa5ff360c547392d29f4cb3/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs#L494-L506">BinaryReader.ReadBytes</see>
/// </summary>
void ReadStreamInternal(Span<byte> buffer)
{
Debug.Assert(Stream != null);

int count = buffer.Length;
int numRead = 0;
do
{
int n = Stream.Read(buffer[numRead..]);
if (n == 0)
throw new EndOfStreamException();

numRead += n;
count -= n;
} while (count > 0);

Debug.Assert(numRead == buffer.Length);
}

public byte ReadByte()
{
if (Stream != null)
Expand Down

0 comments on commit 411c237

Please sign in to comment.