Skip to content

Commit 0c98b5a

Browse files
committed
Improved DecodeString performance
1 parent 508de11 commit 0c98b5a

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

BencodeNET.Net45/Bencode.cs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -165,20 +165,17 @@ public static BString DecodeString(BencodeStream stream, Encoding encoding)
165165
var startPosition = stream.Position;
166166

167167
var lengthString = new StringBuilder();
168-
while (stream.Peek() != ':' && stream.Peek() != -1)
168+
for (var c = stream.ReadChar(); c != ':' && c != default(char); c = stream.ReadChar())
169169
{
170-
lengthString.Append(stream.ReadChar());
171-
}
172-
173-
// Skip ':'
174-
stream.Skip(1);
170+
// Because of memory limitations (~1-2 GB) we know for certain we cannot handle more than 10 digits (10GB)
171+
if (lengthString.Length >= BString.LengthMaxDigits)
172+
{
173+
throw new UnsupportedBencodeException(
174+
string.Format("Length of string is more than {0} digits (>10GB) and is not supported (max is ~1-2GB).", BString.LengthMaxDigits),
175+
stream.Position);
176+
}
175177

176-
// Because of memory limitations (~1-2 GB) we know for certain we cannot handle more than 10 digits (10GB)
177-
if (lengthString.Length >= BString.LengthMaxDigits)
178-
{
179-
throw new UnsupportedBencodeException(
180-
string.Format("Length of string is more than {0} digits (>10GB) and is not supported (max is ~1-2GB).", BString.LengthMaxDigits),
181-
stream.Position);
178+
lengthString.Append(c);
182179
}
183180

184181
long stringLength;
@@ -195,7 +192,6 @@ public static BString DecodeString(BencodeStream stream, Encoding encoding)
195192
stream.Position);
196193
}
197194

198-
// TODO: Catch possible OutOfMemoryException when stringLength is close Int32.MaxValue ?
199195
var bytes = stream.Read((int)stringLength);
200196

201197
// If the two don't match we've reached the end of the stream before reading the expected number of chars

0 commit comments

Comments
 (0)