Skip to content

Commit

Permalink
Copied MessagePackHubProtocol files from https://github.com/dotnet/…
Browse files Browse the repository at this point in the history
  • Loading branch information
Y-Sindo committed Dec 17, 2024
1 parent bc37ff1 commit caf37b7
Show file tree
Hide file tree
Showing 5 changed files with 1,323 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;

namespace Microsoft.AspNetCore.Internal;

internal static class BinaryMessageFormatter
{
public static void WriteLengthPrefix(long length, IBufferWriter<byte> output)
{
Span<byte> lenBuffer = stackalloc byte[5];

var lenNumBytes = WriteLengthPrefix(length, lenBuffer);

output.Write(lenBuffer.Slice(0, lenNumBytes));
}

public static int WriteLengthPrefix(long length, Span<byte> output)
{
// This code writes length prefix of the message as a VarInt. Read the comment in
// the BinaryMessageParser.TryParseMessage for details.
var lenNumBytes = 0;
do
{
ref var current = ref output[lenNumBytes];
current = (byte)(length & 0x7f);
length >>= 7;
if (length > 0)
{
current |= 0x80;
}
lenNumBytes++;
}
while (length > 0);

return lenNumBytes;
}

public static int LengthPrefixLength(long length)
{
var lenNumBytes = 0;
do
{
length >>= 7;
lenNumBytes++;
}
while (length > 0);

return lenNumBytes;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.IO;

using MessagePack;

namespace Microsoft.AspNetCore.SignalR.Protocol;

internal sealed class DefaultMessagePackHubProtocolWorker : MessagePackHubProtocolWorker
{
private readonly MessagePackSerializerOptions _messagePackSerializerOptions;

public DefaultMessagePackHubProtocolWorker(MessagePackSerializerOptions messagePackSerializerOptions)
{
_messagePackSerializerOptions = messagePackSerializerOptions;
}

protected override object? DeserializeObject(ref MessagePackReader reader, Type type, string field)
{
try
{
return MessagePackSerializer.Deserialize(type, ref reader, _messagePackSerializerOptions);
}
catch (Exception ex)
{
throw new InvalidDataException($"Deserializing object of the `{type.Name}` type for '{field}' failed.", ex);
}
}

protected override void Serialize(ref MessagePackWriter writer, Type type, object value)
{
MessagePackSerializer.Serialize(type, ref writer, value, _messagePackSerializerOptions);
}
}
Loading

0 comments on commit caf37b7

Please sign in to comment.