Skip to content

Commit

Permalink
Ensure the BufferReader can't advance past the end of data
Browse files Browse the repository at this point in the history
  • Loading branch information
iamcarbon committed Feb 2, 2024
1 parent 5205495 commit e6d86bd
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions MetadataExtractor/IO/BufferReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ internal ref struct BufferReader(ReadOnlySpan<byte> bytes, bool isBigEndian)
private int _position = 0;
private bool _isBigEndian = isBigEndian;

public readonly int Available => _bytes.Length - _position;

public int Position => _position;

public byte GetByte()
{
Debug.Assert(_position < _bytes.Length, "attempted to read past end of data");
if (_position >= _bytes.Length)
throw new IOException("End of data reached.");

return _bytes[_position++];
}
Expand All @@ -40,8 +43,6 @@ public byte[] GetBytes(int count)
return bytes;
}

public readonly int Available => _bytes.Length - _position;

public void Advance(int n)
{
Debug.Assert(n >= 0, "n must be zero or greater");
Expand Down Expand Up @@ -75,7 +76,7 @@ public sbyte GetSByte()
public ushort GetUInt16()
{
var bytes = _bytes.Slice(_position, 2);
_position += 2;
Advance(2);

return _isBigEndian
? BinaryPrimitives.ReadUInt16BigEndian(bytes)
Expand All @@ -85,7 +86,7 @@ public ushort GetUInt16()
public short GetInt16()
{
var bytes = _bytes.Slice(_position, 2);
_position += 2;
Advance(2);

return _isBigEndian
? BinaryPrimitives.ReadInt16BigEndian(bytes)
Expand All @@ -95,7 +96,7 @@ public short GetInt16()
public uint GetUInt32()
{
var bytes = _bytes.Slice(_position, 4);
_position += 4;
Advance(4);

return _isBigEndian
? BinaryPrimitives.ReadUInt32BigEndian(bytes)
Expand All @@ -105,7 +106,7 @@ public uint GetUInt32()
public int GetInt32()
{
var bytes = _bytes.Slice(_position, 4);
_position += 4;
Advance(4);

return _isBigEndian
? BinaryPrimitives.ReadInt32BigEndian(bytes)
Expand All @@ -115,7 +116,7 @@ public int GetInt32()
public long GetInt64()
{
var bytes = _bytes.Slice(_position, 8);
_position += 8;
Advance(8);

return _isBigEndian
? BinaryPrimitives.ReadInt64BigEndian(bytes)
Expand All @@ -125,7 +126,7 @@ public long GetInt64()
public ulong GetUInt64()
{
var bytes = _bytes.Slice(_position, 8);
_position += 8;
Advance(8);

return _isBigEndian
? BinaryPrimitives.ReadUInt64BigEndian(bytes)
Expand Down

0 comments on commit e6d86bd

Please sign in to comment.