Skip to content

Commit

Permalink
Eliminate allocation in AsciiHexDecodeFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
iamcarbon authored and BobLd committed Apr 12, 2024
1 parent d85ea4f commit b498f5a
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions src/UglyToad.PdfPig/Filters/AsciiHexDecodeFilter.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace UglyToad.PdfPig.Filters
{
using System;
using System.IO;
using Core;
using Tokens;

/// <inheritdoc />
Expand Down Expand Up @@ -34,48 +34,45 @@ public byte[] Decode(ReadOnlySpan<byte> input, DictionaryToken streamDictionary,
Span<byte> pair = stackalloc byte[2];
var index = 0;

using (var memoryStream = new MemoryStream())
using (var binaryWriter = new BinaryWriter(memoryStream))
using var writer = new ArrayPoolBufferWriter<byte>(input.Length);

for (var i = 0; i < input.Length; i++)
{
for (var i = 0; i < input.Length; i++)
if (input[i] == '>')
{
if (input[i] == '>')
{
break;
}
break;
}

if (IsWhitespace(input[i]) || input[i] == '<')
{
continue;
}
if (IsWhitespace(input[i]) || input[i] == '<')
{
continue;
}

pair[index] = input[i];
index++;
pair[index] = input[i];
index++;

if (index == 2)
{
WriteHexToByte(pair, binaryWriter);
if (index == 2)
{
WriteHexToByte(pair, writer);

index = 0;
}
index = 0;
}
}

if (index > 0)
if (index > 0)
{
if (index == 1)
{
if (index == 1)
{
pair[1] = (byte) '0';
}

WriteHexToByte(pair, binaryWriter);
pair[1] = (byte)'0';
}

binaryWriter.Flush();
return memoryStream.ToArray();
WriteHexToByte(pair, writer);
}

return writer.WrittenSpan.ToArray();
}

private static void WriteHexToByte(ReadOnlySpan<byte> hexBytes, BinaryWriter writer)
private static void WriteHexToByte(ReadOnlySpan<byte> hexBytes, ArrayPoolBufferWriter<byte> writer)
{
var first = ReverseHex[hexBytes[0]];
var second = ReverseHex[hexBytes[1]];
Expand Down

0 comments on commit b498f5a

Please sign in to comment.