Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,22 @@ public virtual int Read()

public virtual byte ReadByte() => InternalReadByte();

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCanRead(int byteCount)
{
ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
ThrowIfDisposed();

if (_stream.CanSeek)
{
long remaining = _stream.Length - _stream.Position;
if (remaining < 0 || remaining < byteCount)
{
ThrowHelper.ThrowEndOfFileException();
}
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)] // Inlined to avoid some method call overhead with InternalRead.
private byte InternalReadByte()
{
Expand Down Expand Up @@ -256,6 +272,8 @@ public virtual string ReadString()
return string.Empty;
}

EnsureCanRead(stringLength);

Span<byte> charBytes = stackalloc byte[MaxCharBytesSize];

int currPos = 0;
Expand Down Expand Up @@ -446,7 +464,6 @@ public virtual byte[] ReadBytes(int count)

if (numRead != result.Length)
{
// Trim array. This should happen on EOF & possibly net streams.
result = result[..numRead];
}

Expand All @@ -466,6 +483,7 @@ public virtual byte[] ReadBytes(int count)
public virtual void ReadExactly(Span<byte> buffer)
{
ThrowIfDisposed();
EnsureCanRead(buffer.Length);
_stream.ReadExactly(buffer);
}

Expand All @@ -481,10 +499,8 @@ private ReadOnlySpan<byte> InternalRead(Span<byte> buffer)
}
else
{
ThrowIfDisposed();

EnsureCanRead(buffer.Length);
_stream.ReadExactly(buffer);

return buffer;
}
}
Expand Down Expand Up @@ -523,8 +539,14 @@ protected virtual void FillBuffer(int numBytes)
return;
}
byte[] buffer = ArrayPool<byte>.Shared.Rent(numBytes);
_stream.ReadExactly(buffer.AsSpan(0, numBytes));
ArrayPool<byte>.Shared.Return(buffer);
try
{
_stream.ReadExactly(buffer.AsSpan(0, numBytes));
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
break;
}
}
Expand Down
Loading