1
0

Adding IPNetwork to Converter/Formatters

This commit is contained in:
2022-08-05 17:21:31 +02:00
parent 1522c0cbc9
commit 7ee10e4a6d
9 changed files with 310 additions and 17 deletions

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AMWD.Common.Utilities;
using MessagePack;
using MessagePack.Formatters;
using Microsoft.AspNetCore.HttpOverrides;
namespace AMWD.Common.Formatters
{
/// <summary>
/// Serialization of an <see cref="IPNetwork"/> array to and from <see cref="MessagePack"/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class IPNetworkArrayFormatter : IMessagePackFormatter<IPNetwork[]>
{
/// <inheritdoc/>
public IPNetwork[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.IsNil)
return null;
int bytePos = 0;
byte[] bytes = options.Resolver.GetFormatterWithVerify<byte[]>().Deserialize(ref reader, options);
byte[] buffer = bytes.Skip(bytePos).Take(sizeof(int)).ToArray();
bytePos += sizeof(int);
NetworkHelper.SwapBigEndian(buffer);
int length = BitConverter.ToInt32(buffer, 0);
int arrayPos = 0;
var array = new IPNetwork[length];
while (bytePos < bytes.Length)
{
byte len = bytes.Skip(bytePos).First();
bytePos++;
buffer = bytes.Skip(bytePos).Take(len).ToArray();
bytePos += len;
array[arrayPos] = IPNetworkFormatter.DeserializeInternal(buffer);
arrayPos++;
}
return array;
}
/// <inheritdoc/>
public void Serialize(ref MessagePackWriter writer, IPNetwork[] value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
var bytes = new List<byte>();
int length = value.Length;
byte[] buffer = BitConverter.GetBytes(length);
NetworkHelper.SwapBigEndian(buffer);
bytes.AddRange(buffer);
foreach (var network in value)
{
buffer = IPNetworkFormatter.SerializeInternal(network);
bytes.Add((byte)buffer.Length);
bytes.AddRange(buffer);
}
options.Resolver.GetFormatterWithVerify<byte[]>().Serialize(ref writer, bytes.ToArray(), options);
}
}
}