Adding IPNetwork to Converter/Formatters
This commit is contained in:
74
AMWD.Common/Formatters/IPNetworkArrayFormatter.cs
Normal file
74
AMWD.Common/Formatters/IPNetworkArrayFormatter.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user