Skip to content

Commit

Permalink
fix oversized reads causing issues with certain (most) (almost all) s…
Browse files Browse the repository at this point in the history
…tream implementations (DSharpPlus#1693)

* fix oversizing reads causing issues with certain (most) (almost all) stream implementations

* missed a 3072
  • Loading branch information
akiraveliara authored Nov 26, 2023
1 parent ed5377f commit b8c45b2
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions DSharpPlus/ImageTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ public ImageFormat GetFormat()
/// <returns>Data-scheme base64 string.</returns>
public string GetBase64()
{
const int readLength = 12288;
const int writeLength = 16384;

ImageFormat fmt = this.GetFormat();

int contentLength = Base64.GetMaxEncodedToUtf8Length((int)this.SourceStream.Length);
Expand All @@ -112,7 +115,9 @@ public string GetBase64()
};

byte[] b64Buffer = ArrayPool<byte>.Shared.Rent(formatLength + contentLength + 19);
byte[] readBuffer = ArrayPool<byte>.Shared.Rent(3072);
byte[] readBufferBacking = ArrayPool<byte>.Shared.Rent(readLength);

Span<byte> readBuffer = readBufferBacking.AsSpan()[..readLength];

int processed = 0;
int totalWritten = 0;
Expand All @@ -124,26 +129,26 @@ public string GetBase64()
totalWritten += 19;
totalWritten += formatLength;

while (processed < this.SourceStream.Length - 3072)
while (processed < this.SourceStream.Length - readLength)
{
this.SourceStream.Read(readBuffer);

Base64.EncodeToUtf8(readBuffer, b64Buffer.AsSpan().Slice(totalWritten, 4096), out int _, out int written, false);
Base64.EncodeToUtf8(readBuffer, b64Buffer.AsSpan().Slice(totalWritten, writeLength), out int _, out int written, false);

processed += 3072;
processed += readLength;
totalWritten += written;
}

int remainingLength = (int)this.SourceStream.Length - processed;

this.SourceStream.Read(readBuffer, 0, remainingLength);
this.SourceStream.Read(readBufferBacking, 0, remainingLength);

Base64.EncodeToUtf8(readBuffer.AsSpan()[..remainingLength], b64Buffer.AsSpan()[totalWritten..], out int _, out int lastWritten);
Base64.EncodeToUtf8(readBufferBacking.AsSpan()[..remainingLength], b64Buffer.AsSpan()[totalWritten..], out int _, out int lastWritten);

string value = Encoding.UTF8.GetString(b64Buffer.AsSpan()[..(totalWritten + lastWritten)]);

ArrayPool<byte>.Shared.Return(b64Buffer);
ArrayPool<byte>.Shared.Return(readBuffer);
ArrayPool<byte>.Shared.Return(readBufferBacking);

return value;
}
Expand Down

0 comments on commit b8c45b2

Please sign in to comment.