Add extension method to get Memory<byte> from MemoryStream, attempting to do it without allocation and update CMapParser

This commit is contained in:
BobLd
2025-05-30 11:27:02 +01:00
parent b5b58434e9
commit fe3d15d5db
4 changed files with 20 additions and 17 deletions

View File

@@ -10,7 +10,7 @@
public static class MemoryHelper
{
/// <summary>
/// Gets a read-only <see cref="MemoryStream"/> from a ReadOnlyMemory&lt;byte&gt;.
/// Gets a read-only <see cref="MemoryStream"/> from a ReadOnlyMemory&lt;byte&gt;, attempting without memory allocation.
/// </summary>
public static MemoryStream AsReadOnlyMemoryStream(this ReadOnlyMemory<byte> memory)
{
@@ -21,5 +21,18 @@
return new MemoryStream(memory.ToArray(), false);
}
/// <summary>
/// Gets the Memory&lt;byte&gt; from a <see cref="MemoryStream"/>, attempting without memory allocation.
/// </summary>
public static Memory<byte> AsMemory(this MemoryStream stream)
{
if (stream.TryGetBuffer(out ArraySegment<byte> segment))
{
return segment.AsMemory();
}
return stream.ToArray();
}
}
}

View File

@@ -70,12 +70,7 @@
deflate.CopyTo(f);
f.Flush();
if (output.TryGetBuffer(out var segment))
{
return segment.AsMemory();
}
return output.ToArray();
return output.AsMemory();
}
}
catch (InvalidDataException ex)

View File

@@ -2,6 +2,7 @@
namespace UglyToad.PdfPig.Filters
{
using Core;
using System;
using System.Collections.Generic;
using Lzw;
@@ -131,12 +132,7 @@ namespace UglyToad.PdfPig.Filters
result.Flush();
if (output.TryGetBuffer(out var segment))
{
return segment.AsMemory();
}
return output.ToArray();
return output.AsMemory();
}
}

View File

@@ -11,7 +11,7 @@
using Tokenization.Scanner;
using Tokens;
internal class CMapParser
internal sealed class CMapParser
{
private static readonly BaseFontRangeParser BaseFontRangeParser = new BaseFontRangeParser();
private static readonly BaseFontCharacterParser BaseFontCharacterParser = new BaseFontCharacterParser();
@@ -139,7 +139,7 @@
return false;
}
byte[] bytes;
ReadOnlyMemory<byte> bytes;
using (var stream = typeof(CMapParser).Assembly.GetManifestResourceStream(resource))
{
if (stream is null)
@@ -150,8 +150,7 @@
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
bytes = memoryStream.AsMemory();
}
}