78 lines
2.1 KiB
C#
78 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using AMWD.Common.MessagePack.Utilities;
|
|
#if NET8_0_OR_GREATER
|
|
using IPNetwork = System.Net.IPNetwork;
|
|
#else
|
|
using Microsoft.AspNetCore.HttpOverrides;
|
|
using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
|
|
#endif
|
|
|
|
namespace MessagePack.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);
|
|
}
|
|
}
|
|
}
|