Skip to content

Commit

Permalink
Don't allocate when adding attachments. (#616)
Browse files Browse the repository at this point in the history
* Don't allocate when adding attachements.

* Update MimeKit/AttachmentCollection.cs

Co-authored-by: Anton Firszov <[email protected]>

* Use try.. finally..

* Update AttachmentCollection.cs

minor stylistic changes

* Update AttachmentCollection.cs

Co-authored-by: Anton Firszov <[email protected]>
Co-authored-by: Jeffrey Stedfast <[email protected]>
  • Loading branch information
3 people authored Nov 4, 2020
1 parent c177d2d commit fd604e7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
19 changes: 13 additions & 6 deletions MimeKit/AttachmentCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

using System;
using System.IO;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;

Expand All @@ -44,6 +45,8 @@ namespace MimeKit {
/// </example>
public class AttachmentCollection : IList<MimeEntity>
{
const int BufferLength = 4096;

readonly List<MimeEntity> attachments;
readonly bool linked;

Expand Down Expand Up @@ -133,17 +136,21 @@ static void LoadContent (MimePart attachment, Stream stream)
var content = new MemoryBlockStream ();

if (attachment.ContentType.IsMimeType ("text", "*")) {
var buf = ArrayPool<byte>.Shared.Rent (BufferLength);
var filter = new BestEncodingFilter ();
var buf = new byte[4096];
int index, length;
int nread;

while ((nread = stream.Read (buf, 0, buf.Length)) > 0) {
filter.Filter (buf, 0, nread, out index, out length);
content.Write (buf, 0, nread);
}
try {
while ((nread = stream.Read (buf, 0, BufferLength)) > 0) {
filter.Filter (buf, 0, nread, out index, out length);
content.Write (buf, 0, nread);
}

filter.Flush (buf, 0, 0, out index, out length);
filter.Flush (buf, 0, 0, out index, out length);
} finally {
ArrayPool<byte>.Shared.Return (buf);
}

attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
} else {
Expand Down
4 changes: 4 additions & 0 deletions MimeKit/MimeKit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@
<Reference Include="System.Security" />
<PackageReference Include="Portable.BouncyCastle" Version="1.8.5" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Buffers" Version="4.5.1" />
</ItemGroup>

<ItemGroup>
<Compile Include="Cryptography\ApplicationPgpEncrypted.cs" />
Expand Down

0 comments on commit fd604e7

Please sign in to comment.