Skip to content

Commit 457c501

Browse files
committed
IndexedCapturingReader.IsValidIndex uses Stream.Length if available
#122
1 parent 4fadf7f commit 457c501

File tree

1 file changed

+35
-11
lines changed

1 file changed

+35
-11
lines changed

Diff for: MetadataExtractor/IO/IndexedCapturingReader.cs

+35-11
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public sealed class IndexedCapturingReader : IndexedReader
4141
private readonly List<byte[]> _chunks = new List<byte[]>();
4242
private bool _isStreamFinished;
4343
private int _streamLength;
44+
private bool _streamLengthRead;
4445
private bool _streamLengthThrewException;
4546

4647
public IndexedCapturingReader([NotNull] Stream stream, int chunkLength = DefaultChunkLength, bool isMotorolaByteOrder = true)
@@ -68,24 +69,42 @@ public override long Length
6869
{
6970
get
7071
{
71-
if (!_streamLengthThrewException)
72-
{
73-
try
74-
{
75-
return _stream.Length;
76-
}
77-
catch (NotSupportedException)
78-
{
79-
_streamLengthThrewException = true;
80-
}
81-
}
72+
if (TryGetStreamLength(out var streamLength))
73+
return streamLength;
8274

8375
IsValidIndex(int.MaxValue, 1);
8476
Debug.Assert(_isStreamFinished);
8577
return _streamLength;
8678
}
8779
}
8880

81+
private bool TryGetStreamLength(out long streamLength)
82+
{
83+
if (_streamLengthRead)
84+
{
85+
streamLength = _streamLength;
86+
return true;
87+
}
88+
89+
if (!_streamLengthThrewException)
90+
{
91+
try
92+
{
93+
_streamLength = checked((int)_stream.Length);
94+
streamLength = _streamLength;
95+
_streamLengthRead = true;
96+
return true;
97+
}
98+
catch (NotSupportedException)
99+
{
100+
_streamLengthThrewException = true;
101+
}
102+
}
103+
104+
streamLength = default;
105+
return false;
106+
}
107+
89108
/// <summary>Ensures that the buffered bytes extend to cover the specified index. If not, an attempt is made
90109
/// to read to that point.</summary>
91110
/// <remarks>If the stream ends before the point is reached, a <see cref="BufferBoundsException"/> is raised.</remarks>
@@ -119,6 +138,10 @@ protected override bool IsValidIndex(int index, int bytesRequested)
119138
return false;
120139

121140
var endIndex = (int)endIndexLong;
141+
142+
if (TryGetStreamLength(out var streamLength))
143+
return endIndex < streamLength;
144+
122145
if (_isStreamFinished)
123146
return endIndex < _streamLength;
124147

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

0 commit comments

Comments
 (0)