Visitar URL original
Add memory size check to `GetMemoryCheckResult` by AArnott · Pull Request #2172 · MessagePack-CSharp/MessagePack-CSharp · GitHub
Skip to content
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
14 changes: 12 additions & 2 deletions src/MessagePack/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace MessagePack
{
Expand All @@ -28,13 +29,22 @@ internal static byte[] GetWriterBytes<TArg>(TArg arg, GetWriterBytesAction<TArg>

internal static Memory<byte> GetMemoryCheckResult(this IBufferWriter<byte> bufferWriter, int size = 0)
{
var memory = bufferWriter.GetMemory(size);
Memory<byte> memory = bufferWriter.GetMemory(size);
if (memory.IsEmpty)
{
throw new InvalidOperationException("The underlying IBufferWriter<byte>.GetMemory(int) method returned an empty memory block, which is not allowed. This is a bug in " + bufferWriter.GetType().FullName);
ThrowInvalidOperationException("The underlying IBufferWriter<byte>.GetMemory(int) method returned an empty memory block, which is not allowed. This is a bug in " + bufferWriter.GetType().FullName);
}

if (memory.Length < size)
{
ThrowInvalidOperationException("The underlying IBufferWriter<byte>.GetMemory(int) returned a buffer that is smaller than the requested size. This is a bug in " + bufferWriter.GetType().FullName);
}

return memory;

// Keep the throw statement in another method to encourage JIT inlining of the outer CheckResult method.
[DoesNotReturn]
static void ThrowInvalidOperationException(string message) => throw new InvalidOperationException(message);
}

/// <summary>
Expand Down