Skip to content

Commit

Permalink
IndexedCapturingReader.IsValidIndex uses Stream.Length if available
Browse files Browse the repository at this point in the history
  • Loading branch information
drewnoakes committed Feb 8, 2018
1 parent 4fadf7f commit 457c501
Showing 1 changed file with 35 additions and 11 deletions.
46 changes: 35 additions & 11 deletions MetadataExtractor/IO/IndexedCapturingReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public sealed class IndexedCapturingReader : IndexedReader
private readonly List<byte[]> _chunks = new List<byte[]>();
private bool _isStreamFinished;
private int _streamLength;
private bool _streamLengthRead;
private bool _streamLengthThrewException;

public IndexedCapturingReader([NotNull] Stream stream, int chunkLength = DefaultChunkLength, bool isMotorolaByteOrder = true)
Expand Down Expand Up @@ -68,24 +69,42 @@ public override long Length
{
get
{
if (!_streamLengthThrewException)
{
try
{
return _stream.Length;
}
catch (NotSupportedException)
{
_streamLengthThrewException = true;
}
}
if (TryGetStreamLength(out var streamLength))
return streamLength;

IsValidIndex(int.MaxValue, 1);
Debug.Assert(_isStreamFinished);
return _streamLength;
}
}

private bool TryGetStreamLength(out long streamLength)
{
if (_streamLengthRead)
{
streamLength = _streamLength;
return true;
}

if (!_streamLengthThrewException)
{
try
{
_streamLength = checked((int)_stream.Length);
streamLength = _streamLength;
_streamLengthRead = true;
return true;
}
catch (NotSupportedException)
{
_streamLengthThrewException = true;
}
}

streamLength = default;
return false;
}

/// <summary>Ensures that the buffered bytes extend to cover the specified index. If not, an attempt is made
/// to read to that point.</summary>
/// <remarks>If the stream ends before the point is reached, a <see cref="BufferBoundsException"/> is raised.</remarks>
Expand Down Expand Up @@ -119,6 +138,10 @@ protected override bool IsValidIndex(int index, int bytesRequested)
return false;

var endIndex = (int)endIndexLong;

if (TryGetStreamLength(out var streamLength))
return endIndex < streamLength;

if (_isStreamFinished)
return endIndex < _streamLength;

Expand All @@ -139,6 +162,7 @@ protected override bool IsValidIndex(int index, int bytesRequested)
// the stream has ended, which may be ok
_isStreamFinished = true;
_streamLength = _chunks.Count * _chunkLength + totalBytesRead;
_streamLengthRead = true;
// check we have enough bytes for the requested index
if (endIndex >= _streamLength)
{
Expand Down

0 comments on commit 457c501

Please sign in to comment.