Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update IOUtils.cs #1389

Merged
merged 1 commit into from
Jul 19, 2024
Merged
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
33 changes: 17 additions & 16 deletions main/Util/IOUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,26 +129,27 @@ public static byte[] ToByteArray(Stream stream)
/// <returns></returns>
public static byte[] ToByteArray(Stream stream, int length)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Int32.MaxValue ? 4096 : length);

byte[] buffer = new byte[4096];
int totalBytes = 0, readBytes;
do
using (ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Int32.MaxValue ? 4096 : length))
{
readBytes = stream.Read(buffer, 0, Math.Min(buffer.Length, length - totalBytes));
totalBytes += Math.Max(readBytes, 0);
if (readBytes > 0)
byte[] buffer = new byte[4096];
int totalBytes = 0, readBytes;
do
{
readBytes = stream.Read(buffer, 0, Math.Min(buffer.Length, length - totalBytes));
totalBytes += Math.Max(readBytes, 0);
if(readBytes > 0)
{
baos.Write(buffer, 0, readBytes);
}
} while(totalBytes < length && readBytes > 0);

if(length != Int32.MaxValue && totalBytes < length)
{
baos.Write(buffer, 0, readBytes);
throw new IOException("unexpected EOF");
}
} while (totalBytes < length && readBytes > 0);

if (length != Int32.MaxValue && totalBytes < length)
{
throw new IOException("unexpected EOF");

return baos.ToByteArray();
}

return baos.ToByteArray();
}

public static byte[] ToByteArray(ByteBuffer buffer, int length)
Expand Down
Loading